<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-container>
      <!-- 侧边栏 -->

      <el-main>
        <!-- 查询 -->
        <Conditions ref="conditions" :search-params.sync="searchParams" @search="search" />
        <!-- 表格 -->
        <Tables ref="dyTable" :tree-ids="treeIds" :search-params="searchParams" @rowOperation="rowOperation" />
        <!-- 新增编辑弹窗 -->
        <Details ref="detail" />
        <!-- 查看弹窗 -->
        <SeeDetails ref="seeDetail" />
      </el-main>

    </el-container>
  </div>
</template>

<script>
import Tables from './components/table.vue'
import Conditions from './components/conditions.vue'
import Details from './components/detail.vue'
import SeeDetails from './components/seeDetail.vue'
import { getRolePage, getUserRole } from '@/apiV2/role'
import _ from 'lodash'
import { deleteUser, disableUser, enableUser, resetUserPwd } from '@/apiV2/user'

export default {
  name: 'UserManage',
  components: { Conditions, Tables, Details, SeeDetails },
  data() {
    return {
      global: {
        loading: true,
        companyids: '',
        companyid: '',
        projectid: '',
        dict: {
          status: { 0: '正常', 1: '已停用' }
        },
        roleList: [],
        userRoleList: []
      },
      treeIds: '', // 侧边栏选中ID
      searchParams: {} // 查询(此处不赋值)
    }
  },
  provide() {
    return {
      global: this.global, // 全局数据对象
      reload: this.reload, // 重置
      refresh: this.refresh // 刷新
    }
  },
  async created() {
    // // 获取该登录用户拥有的和创建的角色
    const res1 = await getUserRole()
    if (res1.success) {
      this.global.userRoleList = res1.data.filter(item => item.state === true)
    }
    // 获取所有角色（角色管理里的所有角色）
    const res2 = await getRolePage({ platform: 1, size: 9999 }) // 1总部 2客户 3商户 4金服 5云坐席 8物联网
    if (res2.success) {
      this.global.roleList = _.cloneDeep(res2.data.records)
    }
  },
  methods: {
    /* common */
    reload() { // 重置搜索 回到第一页
      this.$refs.conditions.reset()
    },
    refresh() { // 不重置搜索 刷新当前页
      this.$refs.dyTable.getList(this.searchParams)
    },
    /* tree -> table */
    changeTree(e) {
      this.global.companyids = e.companyids
      this.global.companyid = e.companyid
      this.global.projectid = e.projectid
    },
    /* search -> table */
    search(params) { // 搜索
      this.searchParams = params
      this.$refs.dyTable.pageObj.current = 1
      this.$refs.dyTable.getList(this.searchParams)
    },
    /* table -> dialog */
    async rowOperation(row, idx, actionName) {
      if (['add', 'edit', 'see'].includes(actionName)) { // 增改查统一
        this.$refs['detail'].showDialog({
          mode: actionName,
          formData: row || {}
        })
      } else if (actionName === 'delete') { // 删除
        const txt = `
        <p class="delText" style="padding: 0 15px;margin-bottom: 5px">确定要删除用户【${row.username}】吗？</p>
        <div style="font-size:12px;color:#aaa;line-height:1.5;padding: 0 15px">
          删除后，系统将不再显示此用户，该用户也无法登录，无法恢复，请谨慎操作！
        </div>
        `
        await this.$confirm(txt, '温馨提示', {
          dangerouslyUseHTMLString: true,
          type: 'none'
        })
        try {
          this.loading = true
          const res = await deleteUser(row.id)
          if (res.success) {
            this.reload()
          }
        } finally {
          this.loading = false
        }
      } else if (actionName === 'toggleStatus') { // 停用/启用
        const doDisable = row.status === 0
        const actionNameString = doDisable ? '停用' : '启用'
        const txt = `<p class="delText">确定要${actionNameString}用户【${row.username}】吗？</p>`
        await this.$confirm(txt, '温馨提示', {
          dangerouslyUseHTMLString: true,
          type: 'none'
        })
        try {
          this.loading = true
          let res = {}
          if (doDisable) {
            res = await disableUser(row.id)
          } else {
            res = await enableUser(row.id)
          }
          if (res.success) {
            this.refresh()
          }
        } finally {
          this.loading = false
        }
      } else if (actionName === 'resetPassword') { // 重置密码
        const txt = `<p class="delText" style="text-align:center;">确定要重置密码吗？</p>`
        await this.$confirm(txt, '温馨提示', {
          dangerouslyUseHTMLString: true,
          type: 'none'
        })
        try {
          this.loading = true
          let res = {}
          res = await resetUserPwd(row.id)
          if (res.success) {
            const txt = `
            <p class="delText">密码已重置</p>
            <p class="delText">初始密码为：${res.data}</p>
            `
            this.$confirm(txt, '温馨提示', {
              dangerouslyUseHTMLString: true,
              type: 'none',
              showCancelButton: false,
              confirmButtonText: '我知道了'
            })
            this.reload()
          }
        } finally {
          this.loading = false
        }
      } else { // 表格其它操作
        this.$refs[actionName].showDialog({
          formData: row || {}
        })
      }
    }
  }
}
</script>

<style lang="scss">
</style>
