<template>
  <a-modal
    wrapClassName="t20"
    :width="modalWidth"
    :visible="visible"
    :title="title"
    @ok="handleSubmit"
    @cancel="close"
    cancelText="关闭"
    style="margin-top: -70px"
  >
    <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px">
      <a-col :md="6" :sm="24">
        <a-card>
          <!--组织机构-->
          <a-directory-tree
            selectable
            :selectedKeys="selectedDepIds"
            :expandedKeys.sync="expandedKeys"
            :checkStrictly="true"
            @select="onDepSelect"
            :treeData="departTree"
          />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <a-card :bordered="false">
          用户名:
          <a-input-search
            :style="{ width: '150px', marginBottom: '15px' }"
            placeholder="请输入用户名"
            v-model="queryParam.realname"
            @search="onSearch"
            @change="onSearch"
          ></a-input-search>
          <a-button @click="searchReset(1)" style="margin-left: 20px" icon="redo">重置</a-button>
          <!--用户列表-->
          <a-table
            ref="table"
            :scroll="scrollTrigger"
            size="small"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :rowSelection="{
              selectedRowKeys: selectedRowKeys,
              onSelect: onSelect,
              onSelectAll: onSelectAll,
              onChange: onSelectChange,
              type: getType
            }"
            @change="handleTableChange"
          >
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import { filterObj } from '@/utils/util'
import {
  queryTreeListBySysDepart,
  queryUserByDepId,
  queryUserListByUserIds,
  selectUserlistByDeptIdAndParam
} from './api'

export default {
  name: 'JSelectUserByDepModal',
  components: {},
  // eslint-disable-next-line vue/require-prop-types
  props: ['modalWidth', 'multi', 'userIds', 'condition', 'selectMaxNum'],
  data() {
    return {
      queryParam: {
        username: undefined,
        orgCode: undefined
      },
      columns: [
        {
          title: '用户账号',
          align: 'center',
          dataIndex: 'username'
        },
        {
          title: '真实姓名',
          align: 'center',
          dataIndex: 'realname'
        },
        {
          title: '性别',
          align: 'center',
          dataIndex: 'sex',
          customRender: function (text) {
            if (text === '1') {
              return '男'
            } else if (text === '2') {
              return '女'
            } else {
              return text
            }
          }
        },
        {
          title: '手机号码',
          align: 'center',
          dataIndex: 'phone'
        },
        {
          title: '邮箱',
          align: 'center',
          dataIndex: 'email'
        }
      ],
      scrollTrigger: {},
      dataSource: [],
      selectedRowKeys: [],
      selectUserRows: [],
      selectUserIds: [],
      title: '根据部门选择用户',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      selectedDepIds: [],
      departTree: [],
      visible: false,
      form: this.$form.createForm(this),
      expandedKeys: [],
      departParam: {},
      selectRowList: []
    }
  },
  computed: {
    // 计算属性的 getter
    getType: function () {
      return this.multi === true ? 'checkbox' : 'radio'
    }
  },
  watch: {
    userIds: {
      immediate: true,
      handler() {
        this.initUserNames()
      }
    }
  },
  created() {
    // 该方法触发屏幕自适应
    this.resetScreenSize()
  },
  methods: {
    initUserNames() {
      if (this.userIds) {
        let currUserIds = this.userIds
        queryUserListByUserIds({ userIds: currUserIds }).then(res => {
          let value = res.value
          let realnameList = value.map(item => {
            return item.realname
          })
          this.$emit('initComp', realnameList.join())
        })
      } else {
        // JSelectUserByDep组件bug issues/I16634
        this.$emit('initComp', '')
      }
    },
    async loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.queryParam.deptId = this.selectedDepIds[0]
      //查询条件
      let params = this.getQueryParams()
      // 设置传入的查询条件
      Object.assign(params.value, this.condition)

      await selectUserlistByDeptIdAndParam(params).then(res => {
        if (res.code === '200') {
          this.dataSource = res.value.records
          this.ipagination.total = res.value.total
        }
      })
    },
    // 触发屏幕自适应
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
    showModal(allDepart) {
      if (allDepart) {
        this.departParam = {}
      } else {
        if (this.$store.getters.userInfo.dataAuth === 1) {
          this.departParam = { orgCode: this.$store.getters.userInfo.orgCode }
        } else {
          this.departParam = {}
        }
      }

      this.queryDepartTree()
      this.form.resetFields()
    },
    getQueryParams() {
      let param = Object.assign({}, this.isorter)
      param.value = this.queryParam
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      let str = 'id,'
      for (let a = 0; a < this.columns.length; a++) {
        str += ',' + this.columns[a].dataIndex
      }
      return str
    },
    searchReset() {
      this.queryParam = { deptId: this.selectedDepIds[0] }
      this.loadData(1)
    },
    close() {
      // this.searchReset(0);
      this.visible = false
    },
    handleTableChange(pagination, filters, sorter) {
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    async handleSubmit() {
      let that = this
      // await this.getSelectUserRows()
      that.$emit('ok', that.selectRowList)
      // that.searchReset(0)
      that.close()
    },
    // //获取选择用户信息
    // getSelectUserRows(rowId) {
    // 	let dataSource = this.dataSource;
    // 	let userIds = "";
    // 	this.selectUserRows = [];
    // 	for (let i = 0, len = dataSource.length; i < len; i++) {
    // 		if (this.selectedRowKeys.includes(dataSource[i].id)) {
    // 			this.selectUserRows.push(dataSource[i]);
    // 			userIds = userIds + "," + dataSource[i].username
    // 		}
    // 	}
    // 	this.selectUserIds = userIds.substring(1);
    // },
    // 点击树节点,筛选出对应的用户
    onDepSelect(selectedDepIds) {
      this.queryParam = { deptId: selectedDepIds }
      if (selectedDepIds[0] != null) {
        this.initQueryUserByDepId(selectedDepIds) // 调用方法根据选选择的id查询用户信息
        if (this.selectedDepIds[0] !== selectedDepIds[0]) {
          this.selectedDepIds = [selectedDepIds[0]]
        }
      }
    },
    onSelect(record, selected) {
      if (!this.multi) {
        this.selectRowList = []
        this.selectRowList = [record]
        return
      }
      if (!selected) {
        // 移除
        for (let i = 0; i < this.selectRowList.length; i++) {
          if (this.selectRowList[i].id === record.id) {
            this.selectRowList.splice(i, 1)
          }
        }
      } else {
        this.selectRowList.push(record)
      }
      if (this.selectRowList.length > this.selectMaxNum) {
        this.selectRowList = this.selectRowList.slice(0, this.selectMaxNum)
      }
    },
    onSelectAll(selected, selectedRows, changeRows) {
      if (!selected) {
        for (let i = 0; i < changeRows.length; i++) {
          for (let j = 0; j < this.selectRowList.length; j++) {
            if (changeRows[i].id === this.selectRowList[j].id) {
              this.selectRowList.splice(j, 1)
            }
          }
        }
      } else {
        for (let i = 0; i < selectedRows.length; i++) {
          for (let j = 0; j < this.selectRowList.length; j++) {
            if (selectedRows[i].id === this.selectRowList[j].id) {
              this.selectRowList.splice(j, 1)
            }
          }
        }
        this.selectRowList = selectedRows.concat(this.selectRowList)
      }
      if (this.selectRowList.length > this.selectMaxNum) {
        this.selectRowList = this.selectRowList.slice(0, this.selectMaxNum)
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
      if (this.selectedRowKeys.length > this.selectMaxNum) {
        this.selectedRowKeys = this.selectedRowKeys.slice(0, this.selectMaxNum)
        this.$message.warn('最多只能选择' + this.selectMaxNum + '人')
      }
    },
    onSearch() {
      this.loadData(1)
    },
    // 根据选择的id来查询用户信息
    initQueryUserByDepId(selectedDepIds) {
      queryUserByDepId({ id: selectedDepIds.toString() })
        .then(res => {
          if (res.code === '200') {
            this.dataSource = res.value
            this.ipagination.total = res.value.length
          }
        })
        .finally(() => {
          this.visible = true
        })
    },
    queryDepartTree() {
      queryTreeListBySysDepart(this.departParam)
        .then(res => {
          if (res.code === '200') {
            this.departTree = res.value
            this.expandedKeys = []
            res.value.forEach((item, index) => {
              if (index === 0) {
                //展开父级（新能源辽宁分公司）
                this.expandedKeys.push(item.id)
                if (item.children) {
                  //循环子集
                  item.children.forEach(itemChildren => {
                    //默认选择当前风电场
                    if (itemChildren.orgCode === this.$store.getters.userInfo.orgCode) {
                      this.expandedKeys.push(itemChildren.id)
                      this.selectedDepIds = [itemChildren.id]
                      this.initQueryUserByDepId(itemChildren.id)
                    }
                  })
                } else {
                  this.selectedDepIds = [item.id]
                  this.initQueryUserByDepId(item.id)
                }
              }
            })
          }
        })
        .finally(() => {
          this.visible = true
        })
    },
    modalFormOk() {
      this.loadData()
    },
    clearForm() {
      this.selectedDepIds = []
      this.expandedKeys = []
      this.selectedRowKeys = []
      this.selectRowList = []
    }
  }
}
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

#components-layout-demo-custom-trigger .trigger {
  font-size: 18px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color 0.3s;
}
</style>
