<template>
  <a-spin :spinning="spinning">
    <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="false"
              :defaultExpandedKeys="expandedKeys"
              :defaultSelectedKeys="selectedKeys"
              :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 = {}, $refs.table.refresh(true)}">重置</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:edit')">人员</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="setAdmin" type="primary" v-if="hasPerm('person:setAdmin')">设置管理员</a-button>
              <a-button @click="personExport" type="primary" v-if="hasPerm('person:export')">导出</a-button>
              <a-button @click="personBatch" type="primary" v-if="hasPerm('person:import')">导入</a-button>
              <a-button @click="downloadDemo" type="primary" v-if="hasPerm('person:import')">导入模板下载</a-button>
              <input ref="inputFile" type="file" style="display: none" @change="personImport" />
            </template>

          </div>

          <div class="table-operator"  v-if="orgType === 1">
            <div class="person-type">
              <a-radio-group v-model="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:get')" @click="$refs.personDetail.detail(record)">详情</a>
              <a-divider type="vertical" v-if="hasPerm('person:get')" />
              <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>
                  <template v-if="orgType === 2">
                    <a-menu-item v-if="hasPerm('person:org:remove')">
                      <a-popconfirm placement="topRight" title="确认移除？" @confirm="() => personRemove(record)">
                        <a>移除</a>
                      </a-popconfirm>
                    </a-menu-item>
                  </template>

                </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>
  </a-spin>
</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,
          personExport, personImport } from '@/api/person/person'
import { removePersonOrg } from '@/api/person/personOrg'
import PersonForm from './PersonForm'
import PersonDetail from './PersonDetail'
import OrgTree from '../org/OrgTree'
import { downloadExportFile } from '@/api/common/common'

import { ossUpload } from '@/api/sys/oss'

import axios from 'axios'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const rootParentId = 0

export default {
  components: {
    STable,
    PersonForm,
    PersonDetail,
    OrgTree
  },
  data () {
    return {
      // 查询参数
      queryParam: { },
      // 表头
      columns: [
        {
          title: '姓名',
          dataIndex: 'name'
        },
        {
          title: '用户名',
          dataIndex: 'userName'
        },
        {
          title: '单位信息',
          dataIndex: 'unit'
        },
        {
          title: '部门信息',
          dataIndex: 'dept'
        },
        {
          title: '年度学时要求',
          dataIndex: 'planClassHour'
        },
        {
          title: '注册时间',
          dataIndex: 'registerDate',
          scopedSlots: { customRender: 'registerDate' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (!this.orgId) return []
        return personPage(Object.assign(parameter, this.queryParam,
            { isAdmin: this.isAdmin, orgType: this.orgType, orgId: this.orgId }
          )).then((res) => {
          return res
        })
      },
      orgTree: [],
      selectedRowKeys: [],
      selectedRows: [],
      expandedKeys: [],
      selectedKeys: [],
      treeLoading: true,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id'
      },
      isAdmin: 2,
      orgId: '',
      orgType: 1,
      spinning: false
    }
  },
  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
        this.expandedKeys = []
        this.selectedKeys = []
        if (!res.code === 200 || !res.data.length) {
          this.orgTree = []
          this.$refs.table.refresh(true)
          return
        }
        this.orgTree = listToTree(res.data, [], rootParentId)
        this.orgId = this.orgTree[0].id
        this.selectedKeys.push(this.orgId)
        // 默认展开
        this.orgTree.forEach(item => {
          this.expandedKeys.push(item.id)
        })

        this.handleClick(this.orgId)
      })
    },
    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)
      })
    },
    /**
     * 移除项目
     */
    personRemove (record) {
      removePersonOrg({ personId: record.id, orgId: this.orgId }).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 }
        })
      }
    },
    personExport () {
      personExport(Object.assign(this.queryParam,
            { isAdmin: this.isAdmin, orgType: this.orgType, orgId: this.orgId }
          )).then(res => {
        downloadExportFile(res.data)
      })
    },
    // 批量导入
    personBatch () {
      this.$refs.inputFile.click()
    },
    personImport () {
      if (!this.$refs.inputFile.value || this.$refs.inputFile.value === '') return
      this.spinning = true
      const data = new FormData()
      data.append('file', this.$refs.inputFile.files[0])
      data.append('sourceId', 'personImport')
      data.append('fileType', 'excel')

      const header = {}
      header['Content-Type'] = 'multipart/form-data'
      header[ACCESS_TOKEN] = storage.get(ACCESS_TOKEN)

      axios
        .post(ossUpload(), data, { headers: header })
        .then((res) => {
          this.$refs.inputFile.value = ''
          if (res.data.code === 200) {
            const params = { fileUrl: res.data.url, orgId: this.orgId }
            personImport(params).then((res1) => {
              this.$message.success('导入成功!')
              this.$refs.table.refresh()
              this.spinning = false
            }).catch(() => {
              this.spinning = false
            })
          } else {
            this.$message.error(res.data.msg)
            this.spinning = false
          }
        })
        .catch((err) => {
          this.$refs.inputFile.value = ''
          this.$message.error(err)
          this.spinning = false
        })
    },

    /**
     * 点击左侧机构树查询列表
     */
    handleClick (e) {
      this.orgId = e.toString()
      this.$refs.table.refresh(true)
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onRadioChange (e) {
      this.isAdmin = e.target.value
      this.$refs.table.refresh(true)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 下载模板
    downloadDemo () {
      window.location.href = '/dawa/sys/oss/show?id=3'
    }
  }
}
</script>
<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.person-type span {
  font-size: 24px;
}
</style>
