<template>
  <div>
    <el-form :inline="true">
      <el-form-item label="姓名：">
        <el-input v-model="queryParams.nickName"></el-input>
      </el-form-item>
      <el-form-item label="部门：">
        <el-select v-model="queryParams.deptId" clearable @change="getList">
          <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getList" type="primary">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-table ref="chooseUser" :data="userList" @selection-change="handleSelectionChange" :row-key="getRowKeys"
      @current-change="handleCurrentChange" @row-dblclick="confirmChooseBySingle" :highlight-current-row="!multiple">
      <el-table-column type="selection" width="50" align="center" :reserve-selection="true" v-if="multiple" />
      <!-- <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" /> -->
      <el-table-column label="姓名" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
      <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" :show-overflow-tooltip="true" />
      <el-table-column label="年龄" align="center" key="age" prop="age" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ getAgeByIdCard(scope.row.idCard) }}
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" key="sex" prop="sex" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.sex == 0 ? '男' : '女' }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="岗级" align="center" key="postLevel" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ formatLevel(scope.row.postLevel, scope.row.salaryLevel,
            dict.type.sys_user_postlevel, dict.type.sys_user_salarylevel) }}
        </template>
      </el-table-column> -->
    </el-table>
    <div style="text-align: right;">
      <el-pagination @current-change="getList" :current-page.sync="queryParams.pageNum"
        :page-size="queryParams.pageSize" layout="total, prev, pager, next" :total="total">
      </el-pagination>
    </div>
    <div v-if="multiple">
      已选人员：<el-tag v-for="item in chooseUser" style="margin: 5px;" :key="item.userId">{{ item.nickName }}</el-tag>
    </div>
    <div v-if="!multiple">
      已选人员：<el-tag style="margin: 5px;">{{ chooseUser.nickName }}</el-tag>
    </div>
    <div style="text-align: center;margin-top: 20px;">
      <el-button type="primary" @click="confirmChoose">确认选择</el-button>
      <el-button @click="clearChoose">清空选择</el-button>
    </div>
  </div>
</template>

<script>
import { listUser, deptTreeSelect } from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import { getUserDayValue } from "@/api/oa/wage/wage";
export default {
  dicts: ['sys_normal_disable', 'sys_user_sex', 'sys_user_titles', 'sys_user_certificates', 'sys_user_pmlevel', 'sys_user_postlevel', 'sys_user_salarylevel'],
  props: {
    deptId: {
      type: Number
    },
    multiple: {
      type: Boolean,
      default: true
    },
    selectedUserIds: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      userList: [],
      dateRange: [],
      deptList: [],
      chooseUser: [],
      deptOptions: undefined,
      total: 0
    }
  },
  created() {
    this.queryParams.deptId = this.deptId
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows.filter(item => item.status != '1' && item.status != '2')
        let month = this.parseTime(new Date(), '{y}-{m}')
        this.userList.forEach(item => {
          getUserDayValue({ userId: item.userId, payMonth: month }).then(res => {
            if (res.data) {
              item.socialSecurityUnit = res.data.socialSecurityUnit
              item.houseFund = res.data.houseFund
            }
          })
        })
        this.total = response.total;
      });
    },
    /** 查询部门 */
    getDeptTree() {
      // deptTreeSelect().then(response => {
      //   this.deptOptions = response.data;
      //   this.deptList = response.data[0].children
      // });
      listDept().then(res => {
        this.deptList = res.data.filter(item => item.deptName != '四川中水成勘院测绘工程有限责任公司')
      })
    },
    // 格式化表格里的薪资岗级
    formatLevel(postLevel, salaryLevel, postLevelList, salaryLevelList) {
      if (postLevel && salaryLevel) {
        let post = postLevelList[postLevel].label
        let salary = salaryLevelList[salaryLevel].label
        return post + salary
      } else {
        return ''
      }
    },
    handleSelectionChange(val) {
      this.chooseUser = val
    },
    handleCurrentChange(val) {
      if (!this.multiple) {
        this.chooseUser = val
      }
    },
    getRowKeys(row) {
      return row.userId;
    },
    confirmChoose() {
      // 当 this.chooseUser 为空数组或空对象时，不做操作
      if (
        !this.chooseUser ||
        (Array.isArray(this.chooseUser) && this.chooseUser.length === 0) ||
        (typeof this.chooseUser === 'object' && !Array.isArray(this.chooseUser) && Object.keys(this.chooseUser).length === 0)
      ) {
        return;
      }
      let users = Array.isArray(this.chooseUser) ? this.chooseUser : [this.chooseUser];
      // 找出已存在的用户
      const existedUsers = users.filter(u => this.selectedUserIds.includes(u.userId));
      // 过滤掉已存在的 userId
      users = users.filter(u => !this.selectedUserIds.includes(u.userId));
      if (users.length === 0) {
        const names = existedUsers.map(u => u.nickName).join('、');
        this.$message.warning(`所选人员【${names}】已存在，无法重复添加`);
        return;
      }
      if (existedUsers.length > 0) {
        const names = existedUsers.map(u => u.nickName).join('、');
        this.$message.warning(`人员【${names}】已存在，已自动过滤`);
      }
      this.$emit('chooseUser', this.multiple ? users : users[0]);
      this.clearChoose();
    },
    confirmChooseBySingle() {
      if (!this.multiple) {
        if (this.chooseUser)
          this.$emit('chooseUser', this.chooseUser)
      }
    },
    clearChoose() {
      if (this.multiple)
        this.$refs.chooseUser.clearSelection();
      else {
        this.chooseUser = {}
      }
    },
    getAgeByIdCard(idCard) {
      const sexAndAge = {}
      //获取用户身份证号码
      const userCard = idCard
      //如果用户身份证号码为undefined则返回空
      if (!userCard) {
        return sexAndAge
      }
      // 获取出生日期
      const yearBirth = userCard.substring(6, 10)
      const monthBirth = userCard.substring(10, 12)
      const dayBirth = userCard.substring(12, 14)
      // 获取当前年月日并计算年龄
      const myDate = new Date()
      const monthNow = myDate.getMonth() + 1
      const dayNow = myDate.getDate()
      let age = myDate.getFullYear() - yearBirth

      if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
        age--
      }
      // 得到年龄
      sexAndAge.age = age
      return sexAndAge.age
    },
  },
}
</script>

<style lang="scss" scoped></style>