<template>
  <a-row :gutter="24">
    <a-col :md="5" :sm="24">
      <a-card :bordered="false" :loading="treeLoading">
        <div v-if="this.orgTree != ''">
          <a-tree
            :treeData="orgTree"
            :onLoadData="orgTree"
            v-if="orgTree.length"
            @select="handleClick"
            :defaultExpandAll="true"
            :defaultExpandedKeys="defaultExpandedKeys"
            :defaultSelectedKeys="defaultSelectedKeys"
            :replaceFields="replaceFields" />
        </div>
        <div v-else>
          <a-empty :image="simpleImage" />
        </div>

        <a-button type="primary" @click="changeOrgType" style="display: block; margin: 10px auto;">
          {{ orgType === 1 ? '切换到项目组' : '切换到人员管理' }}
        </a-button>
      </a-card>
    </a-col>
    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <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.name" allow-clear placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="用户名">
                  <a-input v-model="queryParam.userName" allow-clear placeholder="请输入用户名" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => {queryParam = {}, this.loadData()}">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-card>
      <a-card :bordered="false">
        <div class="table-operator">
          <a-button @click="addPerson" icon="plus" type="primary" v-if="hasPerm('person:add')">新增人员</a-button>

          <template v-if="orgType === 1">
            <a-button @click="transfer" type="primary" v-if="hasPerm('person:transfer')">转移部门</a-button>
            <a-button @click="quit" type="primary" v-if="hasPerm('person:quit')">离职</a-button>
            <!-- <a-button @click="export" type="primary" >导出</a-button> -->
            <a-button @click="setAdmin" type="primary" v-if="hasPerm('person:setAdmin')">设置管理员</a-button>
            <!-- <a-button @click="import" type="primary" v-if="hasPerm('person:import')">批量导入</a-button> -->
          </template>

        </div>

        <div class="table-operator">
          <div class="person-type">
            <a-radio-group v-model="queryParam.isAdmin" @change="onRadioChange">
              <a-radio :value="2">学员</a-radio>
              <a-radio :value="1">管理员</a-radio>
            </a-radio-group>
          </div>
        </div>

        <s-table ref="table" :columns="columns" :data="loadData" :rowKey="(record) => record.id" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
          <template slot="registerDate" slot-scope="text, record">
            {{ record.registerDate | moment('YYYY-MM-DD') }}
          </template>

          <span slot="action" slot-scope="text, record">
            <a v-if="hasPerm('person:detail')" @click="$refs.personDetail.detail(record)">详情</a>
            <a-divider type="vertical" v-if="hasPerm('person:detail')" />
            <a-dropdown v-if="hasPerm('person:edit') || hasPerm('person:resetPwd') || hasPerm('person:del')">
              <a class="ant-dropdown-link">
                更多
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-if="hasPerm('person:edit')">
                  <a @click="$refs.personForm.edit(record)">编辑</a>
                </a-menu-item>
                <a-menu-item v-if="hasPerm('person:resetPwd')">
                  <a-popconfirm placement="topRight" title="确认重置密码？" @confirm="() => resetPwd(record)">
                    <a>重置密码</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item v-if="hasPerm('person:certificate:edit')">
                  <a @click="addPersonCertificate(record)">添加证书</a>
                </a-menu-item>
                <a-menu-item v-if="hasPerm('person:del')">
                  <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => personDelete(record)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
        </s-table>

        <person-form ref="personForm" @ok="handleOk" />
        <person-detail ref="personDetail" @ok="handleOk" />
        <org-tree @selectOrg="selectOrg($event)" ref="orgModal" />

      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import { STable } from '@/components'
import { Empty } from 'ant-design-vue'
import { orgList } from '@/api/org/org'
import { listToTree } from '@/utils/util'
import { personPage, personDel, personQuit, personTransferOrg, personSetAdmin, personResetPwd } from '@/api/person/person'
import PersonForm from './PersonForm'
import PersonDetail from './PersonDetail'
import OrgTree from '../org/OrgTree'
const rootParentId = 0

export default {
  components: {
    STable,
    PersonForm,
    PersonDetail,
    OrgTree
  },
  data () {
    return {
      // 查询参数
      queryParam: { isAdmin: 2 },
      // 表头
      columns: [
        {
          title: '姓名',
          dataIndex: 'name'
        },
        {
          title: '用户名',
          dataIndex: 'userName'
        },
        {
          title: '单位信息',
          dataIndex: 'unit'
        },
        {
          title: '部门信息',
          dataIndex: 'dept'
        },
        {
          title: '年度学时要求',
          dataIndex: 'classHours'
        },
        {
          title: '注册时间',
          dataIndex: 'registerDate',
          scopedSlots: { customRender: 'registerDate' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return personPage(Object.assign(parameter, this.queryParam)).then((res) => {
          return res
        })
      },
      orgTree: [],
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      defaultSelectedKeys: [],
      treeLoading: true,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id'
      },
      orgId: '',
      orgType: 1
    }
  },
  mounted () {

  },
  created () {
    const orgType = this.$route.query.orgType
    if (!orgType) {
      this.orgType = 1
    } else {
      this.orgType = parseInt(orgType)
    }

    this.getOrgTree()

    if (this.hasPerm('person:edit') || this.hasPerm('person:resetPwd') || this.hasPerm('person:del')) {
      this.columns.push({
        title: '操作',
        width: '150px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
  },
  methods: {
    /**
     * 获取到机构树，展开顶级下树节点，考虑到后期数据量变大，不建议全部展开
     */
    async getOrgTree () {
      await orgList({ orgType: this.orgType }).then(res => {
        this.treeLoading = false
        if (!res.code === 200 || !res.data.length) {
          return
        }
        this.defaultExpandedKeys = []
        this.defaultSelectedKeys = []
        this.orgTree = listToTree(res.data, [], rootParentId)
        this.orgId = this.orgTree[0].id
        this.defaultSelectedKeys.push(this.orgId)
        for (var item of this.orgTree) {
          if (item.pid === 0) {
            this.defaultExpandedKeys.push(item.id)
          }
        }
      })
    },
    async changeOrgType () {
      this.orgType = this.orgType === 1 ? 2 : 1
      await this.getOrgTree()
      // 此处使用async和await 由于需要等待orgTree的返回 再往下依据结果继续执行
      this.handleClick(this.orgId)
    },
    /**
     * 重置密码
     */
    resetPwd (record) {
      personResetPwd({ id: record.id }).then(res => {
        if (res.code === 200) {
          this.$message.success('重置成功')
          // this.$refs.table.refresh()
        } else {
          this.$message.error('重置失败：' + res.msg)
        }
      })
    },
    /**
     * 删除用户
     */
    personDelete (record) {
      personDel({ id: record.id, deleteReason: '' }).then((res) => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('删除失败：' + res.msg)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.msg)
      })
    },
    /**
     * 添加证书
     */
    addPersonCertificate (record) {
      this.$router.push({
        path: '/archives/certificate/EditCertificate',
		query: {
          personId: record.id
        }
      })
    },
    quit () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择人员')
        return
      }
      this.$confirm({
        title: '提示',
        content: '确认离职吗',
        onOk: () => {
          const paramIds = this.selectedRowKeys.join(',')
          const param = { 'ids': paramIds }
          personQuit(param).then((res) => {
            if (res.code === 200) {
              this.$message.success('操作成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('操作失败：' + res.msg)
            }
          }).catch((err) => {
            this.$message.error('操作错误：' + err.msg)
          })
        },
        onCancel () {
        }
      })
    },
    transfer () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择人员')
        return
      }
      this.$refs.orgModal.loadOrg()
    },
    selectOrg (orgData) {
      this.$confirm({
        title: '提示',
        content: '确认转移部门至' + orgData.name + '吗',
        onOk: () => {
          const paramIds = this.selectedRowKeys.join(',')
          const param = { ids: paramIds, targetOrgId: orgData.id }
          personTransferOrg(param).then((res) => {
            if (res.code === 200) {
              this.$message.success('操作成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('操作失败：' + res.msg)
            }
          }).catch((err) => {
            this.$message.error('操作错误：' + err.msg)
          })
        },
        onCancel () {
        }
      })
    },
    setAdmin () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择人员')
        return
      }
      this.$confirm({
        title: '提示',
        content: '确认设置为管理员吗',
        onOk: () => {
          const paramIds = this.selectedRowKeys.join(',')
          const param = { 'ids': paramIds }
          personSetAdmin(param).then((res) => {
            if (res.code === 200) {
              this.$message.success('操作成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('操作失败：' + res.msg)
            }
          }).catch((err) => {
            this.$message.error('操作错误：' + err.msg)
          })
        },
        onCancel () {
        }
      })
    },
    addPerson () {
      if (this.orgType === 1) {
        this.$router.push({
          path: '/person/personRegister',
          query: { orgId: this.orgId }
        })
      } else {
        this.$router.push({
          path: '/person/personOrg',
          query: { orgId: this.orgId }
        })
      }
    },
    /**
     * 点击左侧机构树查询列表
     */
    handleClick (e) {
      this.queryParam.orgId = e.toString()
      this.orgId = e.toString()
      this.queryParam.orgType = this.orgType
      this.$refs.table.refresh(true)
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onRadioChange (e) {
      this.queryParam.isAdmin = e.target.value
      this.$refs.table.refresh(true)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.person-type span {
  font-size: 24px;
}
</style>
