<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="人员姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入人员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="定位卡号" prop="cardId">
        <el-input
          v-model="queryParams.cardId"
          placeholder="请输入定位卡号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来访状态" prop="personType">
        <el-select
          v-model="queryParams.onlineStatus"
          placeholder="请选择来访状态"
          clearable
        >
          <el-option label="未离开" :value="1"></el-option>
          <el-option label="已离开" :value="0"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="infoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="姓名" align="center" prop="realName" width="85" />
      <el-table-column label="性别" align="center" prop="sex" width="55" />
      <el-table-column label="身份证号" align="center" prop="idNumber" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="来访单位" align="center" prop="company" />
      <el-table-column label="定位卡号" align="center" prop="cardId" />
      <el-table-column
        label="来访时间"
        align="center"
        prop="visitTime"
        width="150"
      />
      <el-table-column
        label="离开时间"
        align="center"
        prop="leaveTime"
        width="150"
      />
      <el-table-column
        label="来访状态"
        align="center"
        width="85"
        prop="visitorStatus"
      >
        <template slot-scope="scope">
          {{ scope.row.visitorStatus === 1 ? "未离开" : "已离开" }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="380"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.visitorStatus == 1"
            size="small"
            type="warning"
            icon="el-icon-circle-close"
            @click="handleLeave(scope.row)"
            >离开</el-button
          >
          <el-button
            v-if="scope.row.visitorStatus == 0"
            size="small"
            type="success"
            icon="el-icon-circle-close"
            @click="handleHistory(scope.row)"
            >历史轨迹</el-button
          >
          <el-button
            size="small"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改访客信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 使用el-row和el-col实现一行两列布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="定位卡号" prop="cardId">
              <el-select
                v-model="form.cardId"
                placeholder="请选择定位卡号"
                clearable
              >
                <el-option
                  v-for="item in cardIdOptions"
                  :key="item.cardId"
                  :label="item.cardId"
                  :value="item.cardId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthTime">
              <el-date-picker
                clearable
                v-model="form.birthTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择出生日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来访单位" prop="company">
              <el-input v-model="form.company" placeholder="请输入来访单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来访时间" prop="visitTime">
              <el-date-picker
                clearable
                v-model="form.visitTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择来访时间"
                :picker-options="visitTimeOptions"
                default-time="00:00:00"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInfo,
  delInfo,
  addInfo,
  updateInfo,
  getInfo,
  getCardList, // 引入获取定位卡号列表的接口
} from "@/api/jinrun/fangke";
import { listUnboundCard } from "@/api/jinrun/card"; // 引入获取未绑定定位卡号列表的接口

import { getDict } from "@/api/jinrun/common";

export default {
  name: "Info",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 访客信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personType: "2",
        realName: null,
        cardId: null,
        jobNumber: null,
      },
      // 表单参数
      form: {
        personType: "2",
        sex: "男", // 默认选择男
      },
      // 表单校验
      rules: {
        realName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getCardIdList();
  },

  methods: {
    // 来访时间选择器配置
    visitTimeOptions: {
      // 设置可选择的时间范围为当前时间之前
      disabledDate(time) {
        return time.getTime() > Date.now();
      },
      // 可以根据需要添加更多配置
    },
    /** 解绑卡按钮操作 */
    handleLeave(row) {
      const formData = { ...row };

      // 获取当前系统时间并格式化为yyyy-MM-dd HH:mm:ss格式
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      formData.leaveTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      formData.visitorStatus = 0;
      this.$modal
        .confirm("是否确认离开？")
        .then(function () {
          return updateInfo(formData);
        })
        .then(() => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        })
        .catch(() => {});
    },
    handleHistory(row) {
      //  跳转到李麒麟页面
      window.open("https://www.baidu.com");
    },

    /** 获取定位卡号列表数据 */
    getCardIdList() {
      listUnboundCard()
        .then((response) => {
          this.cardIdOptions = response.data || [];
        })
        .catch((error) => {
          this.$modal.msgError("获取定位卡号列表失败");
          console.error("获取定位卡号列表失败:", error);
        });
    },

    /** 查询访客信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then((response) => {
        this.infoList = response.records || [];
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sex: "男", // 默认选择男
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.personId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加访客信息";
      this.dialogType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getInfo(row.personId).then((response) => {
        this.form = response;
        this.open = true;
        this.title = "修改访客信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.personType = "2"; // 访客

          // 创建一个表单数据的副本，避免直接修改原表单
          const formData = { ...this.form };

          if (formData.personId != null) {
            updateInfo(formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除该数据项？")
        .then(function () {
          return delInfo(row.personId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
</style>