<!--version: 3, 选择弹窗-->
<!--版本更新内容：添加prop属性，修复多选-->

<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small"  v-show="showSearch" :inline="true" label-width="4em">
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      ref="multipleTable"
      :data="tableData"
      v-loading="loadTable"
      @row-click="changeSelection"
      @row-dblclick="select"
      @select-all="selectionAll"
      @select="changeSelection"
      highlight-current-row
    >
      <el-table-column align="center" type="selection" v-if="multiple"/>
      <el-table-column label="#" type="index" align="center"/>
      <template v-for="column of showColumns">
        <el-table-column
          :key="column.key"
          :label="column.label"
          :prop="column.key"
          :align="column.align"
          :min-width="column.minWidth"
          :sortable="column.sortable"
          :show-overflow-tooltip="column.overflow"
          :width="column.width"
        >
          <template slot-scope="d">
            <template v-if="column.key === 'userId'">
              {{d.row[column.key]}}
            </template>
            <template v-else-if="column.key === 'deptId'">
              {{d.row.dept == null ? '' : d.row.dept.deptName}}
            </template>
            <template v-else-if="column.key === 'status'">
              <dict-tag :value="d.row.status" :options="dict.type.sys_normal_disable"/>
            </template>
            <template v-else-if="column.key === 'employStatus'">
              <dict-tag :value="d.row.employStatus" :options="dict.type.user_employ_status"/>
            </template>
            <template v-else-if="['birthday'].includes(column.key)">
              {{calcBirthDay(d.row[column.key], new Date()) | dv}} 岁
            </template>
            <template v-else-if="['employDate'].includes(column.key)">
              {{calcFullYear(d.row[column.key], new Date()) | dv}} 年
            </template>
            <template v-else>
              {{d.row[column.key] | dv}}
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>

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

<script>
import { deepClone } from '@/utils'
import DeptTreeSelect from '@/components/Business/Dept/DeptTreeSelect.vue'
import Price from '@/views/bst/price/index.vue'
import BooleanTag from '@/components/BooleanTag/index.vue'
import { $showColumns } from '@/utils/mixins'
import { listUser } from '@/api/system/user'
import { calcBirthDay, calcFullYear } from '@/utils/date'

const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "UserCheck",
  mixins: [$showColumns],
  dicts: ['sys_normal_disable', 'sys_user_sex', 'user_employ_status'],
  components: {BooleanTag, Price, DeptTreeSelect},
  props: {
    // 标题
    title: {
      type: String,
      default: `选择用户`
    },
    value: {
      type: [String, Number, Array],
      default: null,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    show: {
      type: Boolean,
      default: false
    },
    query: {
      type: Object,
      default: () => ({})
    },
    initSelect: {
      type: Array,
      default: null,
    },
    prop: {
      type: String,
      default: 'userId'
    },
    listApi: {
      type: Function,
      default: listUser
    }
  },
  data() {
    return {
      showSearch: true,
      loadTable: false,
      tableData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
      },
      total: 0,
      row: null,
      selected: [],
      // 列信息
      columns: [
        {key: 'userId', visible: false, label: 'ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'userNo', visible: true, label: '工号', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'nickName', visible: true, label: '姓名', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'deptId', visible: true, label: '部门', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'phonenumber', visible: false, label: '手机号码', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'birthday', visible: true, label: '年龄', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100"},
        {key: 'employDate', visible: true, label: '工龄', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100"},
        {key: 'status', visible: true, label: '账号状态', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'employStatus', visible: true, label: '在职情况', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'remark', visible: true, label: '备注', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'loginIp', visible: false, label: '最后登录IP', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'loginDate', visible: false, label: '最后登录时间', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100"},
      ],
    }
  },
  created() {
      this.queryParams = {
        ...this.queryParams,
        ...this.query,
      }

      if (this.initSelect != null) {
        this.selected = deepClone(this.initSelect);
      } else {
        this.selected = [];
      }

      this.getList();
  },
  methods: {
    calcFullYear,
    calcBirthDay,
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 获取数据列表
    getList() {
      this.loadTable = true;
      this.listApi(this.queryParams).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        // 刷新表格状态
        this.$nextTick(()=>{
          this.refreshTableSelection();
        })
      }).finally(() =>{
        this.loadTable = false;
      })
    },
    // 刷新表格的选中状态
    refreshTableSelection() {
      if(this.multiple){
        this.tableData.forEach(item => {
          if (this.selected.map(j => j[this.prop]).includes(item[this.prop])) {
            this.$refs.multipleTable.toggleRowSelection(item, true);
          } else {
            this.$refs.multipleTable.toggleRowSelection(item, false);
          }
        });
      }
    },
    // 全选
    selectionAll(val){
      let flag = val.length > 0;
      this.tableData.forEach(item => {
        if (flag && !this.selected.map(i => i[this.prop]).includes(item[this.prop])){
          this.selected.push(item);
        } else if (!flag && this.selected.map(i => i[this.prop]).includes(item[this.prop])){
          this.selected = this.selected.filter(i => i[this.prop] !== item[this.prop]);
        }
      })
    },
    // 确认选中
    submit() {
      if (this.multiple) {
        this.$emit('select', this.selected);
      } else {
        this.select(this.row);
      }
    },
    // 更换某一行的选中状态
    changeSelection(row){
      if(this.multiple){
        if (this.selected.map(i => i[this.prop]).includes(row[this.prop])){
          this.$refs.multipleTable.toggleRowSelection(row, false);
          this.selected = this.selected.filter(i => i[this.prop] !== row[this.prop]);
        }else {
          this.$refs.multipleTable.toggleRowSelection(row, true);
          this.selected.push(row);
        }
      } else {
        this.selected = [row];
      }
    },
    // 点击搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 选中一行
    select(row) {
      if (!this.multiple) {
        if (!row) return this.$message.error('请选择一行');
        this.selected = [row];
        this.$emit('select', row);
      }
    },
  },
}
</script>
