<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small"  v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责工序" prop="process">
        <el-input
          v-model="queryParams.process"
          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"
      row-key="deptId"
      :data="tableData"
      v-loading="loadTable"
      :default-expand-all="true"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @row-click="changeSelection"
      @row-dblclick="select"
      @select-all="selectionAll"
      @select="changeSelection"
      highlight-current-row
      style="width: 100%"
      size="small"
    >
      <el-table-column align="center" type="selection" v-if="multiple"/>
      <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 === 'deptId'">
              {{d.row[column.key]}}
            </template>
            <template v-else-if="column.key === 'status'">
              <dict-tag :options="dict.type.sys_normal_disable" :value="d.row.status"/>
            </template>
            <template v-else>
              {{d.row[column.key] | dv}}
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<script>
import BooleanTag from '@/components/BooleanTag/index.vue'
import DeptTreeSelect from '@/components/Business/Dept/DeptTreeSelect.vue'
import { $showColumns } from '@/utils/mixins'
import { deepClone } from '@/utils'
import { listDept } from '@/api/system/dept'

export default {
  name: "DeptCheck",
  mixins: [$showColumns],
  dicts: ['sys_normal_disable'],
  components: {BooleanTag, DeptTreeSelect},
  props: {
    value: {
      type: [String, Number, Array],
      default: null,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    query: {
      type: Object,
      default: () => ({})
    },
    initSelect: {
      type: Array,
      default: null,
    },
    prop: {
      type: String,
      default: 'deptId'
    },
    listApi: {
      type: Function,
      default: listDept
    }
  },
  data() {
    return {
      showSearch: true,
      loadTable: false,
      tableData: [],
      queryParams: {},
      total: 0,
      selected: [],
      columns: [
        {key: 'deptId', visible: false, label: '部门ID', minWidth: null, sortable: false, overflow: false, align: 'left', width: null},
        {key: 'deptName', visible: true, label: '部门名称', minWidth: null, sortable: false, overflow: false, align: 'left', width: null},
        {key: 'status', visible: true, label: '状态', minWidth: null, sortable: false, overflow: false, align: 'center', width: null},
        {key: 'leaderName', visible: true, label: '负责人', minWidth: null, sortable: false, overflow: false, align: 'center', width: null},
        {key: 'process', visible: true, label: '负责工序', minWidth: null, sortable: false, overflow: false, align: 'center', width: null},
        {key: 'createTime', visible: true, label: '创建时间', minWidth: null, sortable: false, overflow: false, align: 'center', width: null},
      ],
    }
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query,
    }

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

    this.getList();
  },
  methods: {
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 获取数据列表
    getList() {
      this.loadTable = true;
      this.listApi(this.queryParams).then(response => {
        this.tableData = this.handleTree(response.data, "deptId");
        this.total = response.data.length;
        // 刷新表格状态
        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]);
        }
      })
    },
    // 更换某一行的选中状态
    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();
    },
    // 关闭弹窗
    close() {
      this.$emit('update:show', false);
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
    },
    // 选中一行
    select(row) {
      if (!this.multiple) {
        if (!row) return this.$message.error('请选择一行');
        this.selected = [row];
        this.$emit('select', row);
      }
    },
  },
}
</script>
