<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>
        <el-button
          type="primary"
          icon="el-icon-search1"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh1" 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" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="身份证号" align="center" prop="idNumber" />
      <el-table-column label="所在部门" align="center" prop="deptName" />
      <el-table-column label="岗位名称" align="center" prop="positionName" />
      <el-table-column label="定位卡号" align="center" prop="cardId" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="380"
      >
        <template slot-scope="scope">
          <el-button
            type="success"
            size="small"
            icon="el-icon-link"
            v-if="!scope.row.cardId"
            @click="handleBindCard(scope.row)"
            >定位卡绑定</el-button
          >
          <el-button
            type="warning"
            size="small"
            icon="el-icon-unlock"
            v-if="scope.row.cardId"
            @click="handleUnbindCard1(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="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                placeholder="请选择部门"
                :normalizer="normalizer"
                @select="handleDeptSelect"
              ></treeselect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位名称" prop="positionId">
              <el-select
                v-model="form.positionId"
                placeholder="请选择岗位名称"
                clearable
                @change="handlePositionChange"
              >
                <el-option
                  v-for="item in positionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value * 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <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-row>
        <el-row>
          <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="joiningTime">
              <el-date-picker
                clearable
                v-model="form.joiningTime"
                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="address">
              <el-input v-model="form.address" placeholder="请输入家庭住址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称" prop="jobName">
              <el-input v-model="form.jobName" placeholder="请输入职称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称证书编号" prop="jobNumber">
              <el-input
                v-model="form.jobNumber"
                placeholder="请输入职称证书编号"
              />
            </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="定位卡绑定"
      :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,
  getInfo, // 引入获取人员信息的接口
  updateInfo,
} from "@/api/jinrun/yuangong";
import { listUnboundCard } from "@/api/jinrun/card"; // 引入获取未绑定定位卡号列表的接口
import { getDict } from "@/api/jinrun/common";
import { getDept, getPosition } from "@/api/jinrun/zhongkong";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

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

  methods: {
    /** 处理岗位选择 */
    handlePositionChange(value) {
      if (value) {
        // 根据选择的岗位ID查找对应的岗位对象
        const positionItem = this.positionOptions.find(
          (item) => item.value == value
        );
        if (positionItem) {
          // 将岗位名称存储到form.positionName
          this.form.positionName = positionItem.label;
        }
      } else {
        // 如果取消选择，清空岗位名称
        this.form.positionName = null;
      }
    },
    normalizer(node) {
      const result = {
        id: node.index, // 用index作为唯一标识
        label: node.name, // 用name作为显示文本
      };
      // 只有当children不为null且有值时才添加该属性
      if (node.children && node.children.length > 0) {
        result.children = node.children;
      }
      return result;
    },
    /** 处理部门选择 */
    handleDeptSelect(selectedNode) {
      if (selectedNode) {
        // 直接从选中的节点获取name属性值
        this.form.deptName = selectedNode.name;
        // 同时设置deptId以便后续处理
        this.form.deptId = selectedNode.index;
      } else {
        // 如果取消选择，清空相关字段
        this.form.deptName = null;
        this.form.deptId = null;
      }
    },

    /** 查找部门节点（递归函数，用于备用） */
    findDepartmentNode(deptId, options = this.deptOptions) {
      for (let i = 0; i < options.length; i++) {
        const node = options[i];
        if (node.index === deptId) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = this.findDepartmentNode(deptId, node.children);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    /** 获取部门列表 */
    getDeptList() {
      getDept({})
        .then((response) => {
          console.log(response.data, "部门数据");
          // 添加递归处理函数过滤children为null的情况
          const processDepartmentData = (data) => {
            if (!data || !Array.isArray(data)) return [];

            return data.map((item) => {
              const processedItem = { ...item };

              // 如果children存在且是数组，递归处理
              if (
                processedItem.children &&
                Array.isArray(processedItem.children)
              ) {
                // 递归处理子部门
                processedItem.children = processDepartmentData(
                  processedItem.children
                );
                // 如果处理后的children为空数组，移除该属性
                if (processedItem.children.length === 0) {
                  delete processedItem.children;
                }
              } else if (
                processedItem.children === null ||
                processedItem.children === undefined
              ) {
                // 如果children为null或undefined，移除该属性
                delete processedItem.children;
              }

              return processedItem;
            });
          };

          // 处理部门数据
          this.deptOptions = processDepartmentData(
            // response.data.data[0].children
            response.data.data[0].children
          );
        })
        .catch((error) => {
          console.error("获取部门列表失败:", error);
          this.deptOptions = [];
        });
    },
    /** 获取岗位列表 */
    getPositionList() {
      getPosition({
        pageNum: 1,
        pageSize: 1000,
      }).then((response) => {
        console.log(response.data, "22222");
        this.positionOptions = response.data.map((item) => ({
          label: item.posName,
          value: item.id,
        }));
      });
    },

    /** 解绑卡按钮操作 */
    handleUnbindCard1(row) {
      const formData = { ...row };
      formData.cardId = "";
      this.$modal
        .confirm("是否确认解绑该数据项？")
        .then(function () {
          return updateInfo(formData);
        })
        .then(() => {
          this.$modal.msgSuccess("解绑成功");
          this.bindOpen = false;
          this.getList();
        })
        .catch(() => {});
    },
    /** 绑定卡按钮操作 */
    handleBindCard(row) {
      this.bindForm = { ...row };
      this.bindOpen = true;
    },
    /** 取消绑定卡对话框 */
    cancelBind() {
      this.bindOpen = false;
      this.bindForm = {};
    },

    /** 提交绑定卡表单 */
    submitBindForm() {
      this.$refs["bindForm"].validate((valid) => {
        if (valid) {
          updateInfo(this.bindForm).then((response) => {
            this.$modal.msgSuccess("绑定成功");
            this.bindOpen = false;
            this.getList();
          });
        }
      });
    },

    /** 获取人员类型下拉列表数据 */
    getPersonTypeOptions() {
      // 调用数据字典接口
      getDict({ dictType: "staff_type" })
        .then((response) => {
          this.personTypeOptions = response.data;
        })
        .catch((error) => {
          this.$modal.msgError("获取人员类型数据失败");
          console.error("获取人员类型数据失败:", error);
        });
    },
    /** 获取定位卡号列表数据 */
    getCardIdList() {
      listUnboundCard().then((response) => {
        this.cardIdOptions = response.data || [];
      });
    },

    /** 查询员工信息列表 */
    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 = "修改员工信息";

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

          // 创建一个表单数据的副本，避免直接修改原表单
          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.replace(/^├─/, ""); // 移除前缀后作为部门名称
            }
          }

          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>