<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"
          plain
          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" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="身份证号" align="center" prop="idCard" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="来访单位1" align="center" prop="dept" />
      <el-table-column label="定位卡号" align="center" prop="cardId" />
      <el-table-column label="来访时间1" align="center" prop="dept" />
      <el-table-column label="离开时间1" align="center" prop="idCard" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.laifangStatus == 'Y'"
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleLeave(scope.row)"
            >离开</el-button
          >
          <el-button
            v-if="scope.row.laifangStatus == 'N'"
            size="mini"
            type="text"
            icon="el-icon-unlock"
            @click="handleHistory(scope.row)"
            >历史轨迹</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            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="birth">
              <el-date-picker
                clearable
                v-model="form.birth"
                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="seniority">
              <el-input v-model="form.seniority" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来访时间" prop="hireDate">
              <el-datetime-picker
                clearable
                v-model="form.hireDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择入职日期"
              >
              </el-datetime-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="dialogType !== 'dimission' && dialogType !== 'return'">
          <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>

    <!-- 定位卡绑定对话框 -->
    <el-dialog
      :title="'定位卡绑定 - ' + bindForm.realName"
      :visible.sync="bindOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="bindForm"
        :model="bindForm"
        :rules="bindRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="realName">
          <el-input
            v-model="bindForm.realName"
            disabled
            placeholder="人员姓名"
          />
        </el-form-item>
        <el-form-item label="定位卡号" prop="cardId">
          <el-select
            v-model="bindForm.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-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindForm">确 定</el-button>
        <el-button @click="cancelBind">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

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

export default {
  name: "Info",
  data() {
    return {
      deptOptions: [
        {
          label: "部门1",
          value: "1",
        },
        {
          label: "部门2",
          value: "2",
        },
      ],
      // 绑定卡对话框
      bindOpen: false,
      // 绑定卡表单
      bindForm: {
        personId: null,
        realName: null,
        cardId: null,
        personType: "staff",
      },
      // 绑定卡表单校验
      bindRules: {
        cardId: [
          { required: true, message: "请选择定位卡号", trigger: "change" },
        ],
      },
      dialogType: "",
      // 人员类型下拉列表数据
      personTypeOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personType: "staff",
        realName: null,
        cardId: null,
        jobNumber: null,
      },
      // 表单参数
      form: {
        personType: "staff",
        sex: "男", // 默认选择男
      },
      // 表单校验
      rules: {
        personType: [
          { required: true, message: "人员类型不能为空", trigger: "change" },
        ],
        realName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getPersonTypeOptions();
    // 获取定位卡号列表
    this.getCardIdList();
  },

  methods: {
    /** 解绑卡按钮操作 */
    handleLeave(row) {
      this.$modal
        .confirm("是否确认离开？")
        .then(function () {
          return unbindCard({
            personId: row.personId,
            personType: row.personType,
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    /** 绑定卡按钮操作 */
    handleHistory(row) {
      //  跳转到李麒麟页面
      window.open("https://www.baidu.com");
    },
    /** 取消绑定卡对话框 */
    cancelBind() {
      this.bindOpen = false;
      this.bindForm = {
        personId: null,
        realName: null,
        cardId: null,
        personType: "staff",
      };
    },

    /** 提交绑定卡表单 */
    submitBindForm() {
      this.$refs["bindForm"].validate((valid) => {
        if (valid) {
          bindCard(this.bindForm)
            .then((response) => {
              this.$modal.msgSuccess("绑定成功");
              this.bindOpen = false;
              this.getList();
            })
            .catch((error) => {
              this.$modal.msgError("绑定失败，请重试");
              console.error("绑定卡失败:", error);
            });
        }
      });
    },

    /** 获取人员类型下拉列表数据 */
    getPersonTypeOptions() {
      // 调用数据字典接口
      getDict({ dictType: "staff_type" })
        .then((response) => {
          this.personTypeOptions = response.data;
        })
        .catch((error) => {
          this.$modal.msgError("获取人员类型数据失败");
          console.error("获取人员类型数据失败:", error);
        });
    },
    /** 获取定位卡号列表数据 */
    getCardIdList() {
      getCardList()
        .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.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        createBy: null,
        createTime: null,
        updateTime: null,
        remark: null,
        personId: null,
        personType: null,
        personTypeName: null,
        staffType: null,
        staffTypeName: null,
        positionIconType: null,
        positionIconTypeName: null,
        realName: null,
        phone: null,
        sex: "男",
        birth: null,
        email: null,
        nativePlace: null,
        nation: null,
        maritalStatus: null,
        politicsStatus: null,
        healthStatus: null,
        idType: null,
        idNumber: null,
        personIc: null,
        personCode: null,
        personSource: null,
        company: null,
        companyName: null,
        administratorName: null,
        administratorPhone: null,
        jobNumber: null,
        jobStatus: null,
        hireDate: null,
        hireDateAlias: null,
        dimissionDate: null,
        officePhone: null,
        duty: null,
        professionalTitle: null,
        professionalTitleNumber: null,
        seniority: null,
        experience: null,
        yearPlusExperience: null,
        highestEducation: null,
        highestDegree: null,
        profession: null,
        school: null,
        diplomaNumber: null,
        cengNumber: null,
        accessory: null,
        accessoryList: null,
        contractorId: null,
        contractorName: null,
        receiveLeader: null,
        receivePhone: null,
        gateThrough: null,
        leaveTime: null,
        visitorStatus: null,
        visitTime: null,
        process: null,
        lastUpdateDate: null,
        lastCreateDate: null,
        updateFail: null,
        onlineStatus: null,
        inOutStatus: null,
        cardType: null,
        cardTypeName: null,
        cardId: null,
        icCardId: null,
        cardPower: null,
        personPhoto: null,
        photoSign: null,
        deptName: null,
        reservationEntryStartTime: null,
        reservationEntryEndTime: null,
        reservationVisitingTime: null,
        curUserName: null,
        visitorId: null,
      };
      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();
      listInfo({
        pageNum: 1,
        pageSize: 1,
        personId: row.personId,
      }).then((response) => {
        this.form = response.data[0];
        this.open = true;
        this.title = "修改员工信息";

        this.dialogType = "update";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.personType = "staff";

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

          // 根据 deptId 查找对应的部门名称
          if (
            formData.deptId &&
            this.deptOptions &&
            this.deptOptions.length > 0
          ) {
            const deptItem = this.deptOptions.find(
              (item) => item.value === formData.deptId
            );
            if (deptItem) {
              formData.deptName = deptItem.label; // 添加部门名称参数
            }
          }

          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({
            personIds: [row.personId],
            personType: row.personType,
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
</style>