<template>
  <a-modal
    :title="modalTitle"
    :width="1300"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-card :bordered="false">
      <a-row :gutter="8">
        <a-col :span="5">
          <a-tree
            @expand="onExpand"
            :expandedKeys="expandedKeys"
            :autoExpandParent="autoExpandParent"
            @select="onSelect"
            :selectedKeys="selectedKeys"
            :treeData="treeData"
          />
        </a-col>
        <a-col :span="19">
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="关键字">
                    <a-input v-model="queryParam.keyword" placeholder="请输入账户或姓名"/>
                    <a-input v-model="queryParam.deptId" type="hidden"/>
                  </a-form-item>
                </a-col>
                <a-col :md="8 || 24" :sm="24">
                  <span class="table-page-search-submitButtons">
                    <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                    <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <s-table
            ref="table"
            size="default"
            rowKey="userId"
            :columns="columns"
            :data="loadData"
            :alert="options.alert"
            :customRow="options.customRow"
            :rowSelection="options.rowSelection"
            showPagination="auto"
          >
            <span slot="status" slot-scope="text">
              <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
            </span>
          </s-table>
        </a-col>
      </a-row>
    </a-card>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="handleCancel()">取消</a-button>
      <a-button :loading="confirmLoading" type="primary" @click="handleSelect()">选择</a-button>
    </template>
    <base-form ref="baseModal" @ok="handleOk" :roleList="roleList" :treeData="treeData"/>

  </a-modal>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseForm from './BaseForm'
import { getUserPage, fetchUser, deleteUsers, resetUserPwd, updateUserStatus } from '@/api/upms/user'
import { queryRole } from '@/api/upms/role'
import { getDeptTree } from '@/api/upms/dept'

const statusMap = {
  1: {
    status: 'success',
    text: '正常'
  },
  2: {
    status: 'error',
    text: '冻结'
  }
}

export default {
  name: 'UserSelectModel',
  components: {
    STable,
    Ellipsis,
    BaseForm
  },
  props: {
    type: {
      type: String,
      default: 'radio'
    },
    selectedRowKey: {
      type: Array,
      default: () => {
        return []
      }
    },
    selectedRow: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      confirmLoading: false,
      mdl: {},
      modalTitle: null,
      visible: false,
      selectedKeys: [],
      selectedRowKeys: [],
      selectedRows: [],
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      identityTypeMap: {},
      jobTypeMap: {},
      // 查询参数
      queryParam: {
        keyword: null
      },
      // 表头
      columns: [
        {
          title: '姓名',
          dataIndex: 'realName'
        },
        {
          title: '手机号',
          dataIndex: 'phone'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        /* {
          title: '上次登录时间',
          dataIndex: 'lastLoginTime',
          sorter: true
        }, */
        {
          title: '身份',
          dataIndex: 'identityType',
          customRender: (text, record, index) => {
            return this.BaseTool.Object.getField(this.identityTypeMap, text)
          }
        },
        {
          title: '职务',
          dataIndex: 'jobType',
          customRender: (text, record, index) => {
            return this.BaseTool.Object.getField(this.jobTypeMap, text)
          }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getUserPage(Object.assign(parameter, this.queryParam))
          .then(res => {
            return res.data
          })
      },
      roleList: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true,
      isCreated: false
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.tableOption()
    this.identityTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_USER_IDENTITY_TYPE)
    this.jobTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_USER_JOB_TYPE)
  },
  methods: {
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            type: this.type,
            getCheckboxProps: record => ({
              props: {
                disabled: false, // Column configuration not to be checked
                name: record.userId
              }
            })
          },
          customRow: (record) => {
            return {
              on: { // 事件
                click: (event) => { // 点击行
                  // 选择对象
                  this.mySelect([record.id], [record])
                },
                dblclick: (event) => {
                  this.mySelect([record.id], [record])
                  this.handleSelect()
                }
              }
            }
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    getRoles () {
      queryRole({ status: 1 }).then(res => {
        this.roleList = res.data
      })
    },
    batchDelete () {
      const length = this.selectedRows.length
      if (length === 0) {
        this.$message.info(`请选择要删除的记录`)
      } else {
        deleteUsers(this.selectedRows.map(item => item.userId)).then(res => {
          this.$message.info(`删除成功`)
          this.handleOk()
          this.$refs.table.clearSelected()
        })
      }
    },
    base (record, queryParam = {}) {
      this.visible = true
      this.modalTitle = '选择人员'
      this.extraQueryParam = queryParam
      this.getRoles()
      getDeptTree().then(res => {
        this.treeData = res.data
      })
      this.record = record
      if (this.isCreated) {
        this.$refs.table.clearSelected()
        this.options.rowSelection.type = this.type
        this.handleOk()
      } else {
        this.tableOption()
        this.isCreated = true
      }
    },
    handleEdit (record) {
      fetchUser({ userId: record.userId }).then(res => {
        this.$refs.baseModal.base(res.data)
      })
    },
    handleChangeStatus (userId, status) {
      updateUserStatus({
        userId: userId,
        status: status
      }).then(res => {
        this.$message.info(`操作成功`)
        this.handleOk()
      })
    },
    handleResetPwd (userId) {
      resetUserPwd({
        userId: userId,
        status: status
      }).then(res => {
        this.$message.info(res.message)
        this.handleOk()
      })
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleSelect () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warn('请至少选择一项信息')
      } else {
        this.confirmLoading = true
        this.$emit('selected', this.selectedRowKeys, this.selectedRows)
        this.confirmLoading = false
        this.visible = false
      }
    },
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
    },
    mySelect (selectedRowKeys, selectedRows) {
      this.$refs.table.updateSelect(selectedRowKeys, selectedRows)
      this.$refs.table.rowSelection.onChange(selectedRowKeys, selectedRows)
    },
    resetSearchForm () {
      this.queryParam = {
      }
      this.selectedKeys = []
      this.$refs.table.refresh(true)
    },
    onSelect: function (selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.queryParam.deptId = selectedKeys.length > 0 ? selectedKeys[0] : ''
      this.$refs.table.refresh(true)
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    }
  }
}
</script>
