<template>
  <a-modal
    v-model="visible"
    :title="title"
    destroy-on-close
    v-bind="{ width: 850 }"
    :mask-closable="false"
  >
    <sd-data-table
      ref="dataTable"
      :key="updateKey"
      :data-url="listDataUrl"
      :actions="actions"
      :columns="columns"
      :show-selection="showSelection"
      :process-res="processRes"
      :process-req="processReq"
      hide-pagination
      :pagination="pagination"
      :row-key="'account'"
    >
    </sd-data-table>

    <template slot="footer">
      <a-button
        type="white"
        @click="
          () => {
            visible = false
          }
        "
        >取消</a-button
      >
    </template>
  </a-modal>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import pickValues from '@/common/services/pick-values'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import { message } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import OrgService from './org-service'
import components from './_import-components/sd-org-role-assign-user-import'
import PermissionService from '@/permission-manage/permission-service'

export default {
  name: 'SdOrgRoleAssignUser',
  metaInfo: {
    title: 'SdOrgRoleAssignUser',
  },
  components,
  mixins: [storeMixin],
  props: {
    unid: {
      type: String,
      default: function() {
        return null
      },
    },
    curParent: {
      type: Object,
      default: function() {
        return null
      },
    },
  },
  data() {
    return {
      title: '',
      visible: false,
      listDataUrl: '', // `api/framework/v1/user-manager/roles/${this.unid}/users`,
      columns: [
        {
          title: '账号',
          dataIndex: 'account',
        },
        {
          title: '姓名',
          dataIndex: 'text',
        },
        {
          title: '机构',
          dataIndex: 'fullpath',
        },
      ],
      actions: [
        {
          label: '添加',
          id: 'new',
          permission: null,
          // type: TableActionTypes.ex.create,
          callback: () => {
            this.actAddUsers()
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: (keys, rows) => {
            return this.deleteUsers(
              rows.map((item) => {
                return item.account
              })
            )
          },
        },
      ],
      pagination: {},
      showSelection: true,
      updateKey: 0,
      msgKey: 'updatable',
    }
  },
  watch: {
    unid: {
      handler(newVal, oldVal) {
        this.listDataUrl = `api/framework/v1/role-manager/users/${newVal}`
      },
      immediate: true,
    },
  },
  methods: {
    show(title, sType) {
      this.title = title
      // this.unid = unid
      this.visible = true
      this.listDataUrl = `api/framework/v1/role-manager/users/${this.unid}`

      // this.getDefaultValue()
    },
    processRes(resData) {
      this.curUsers = resData.treeNode.children.map((item) => {
        return {
          code: item.props.account,
          account: item.props.account,
          title: item.props.name,
        }
      })
      this.pagination.pageSize = resData.treeNode.children.length
      return {
        totalSize: this.pagination.pageSize,
        data: resData.treeNode.children.map((item) => {
          return {
            account: item.props.account,
            text: item.props.name,
            fullpath: item.props.fullpath,
          }
        }),
      }
    },
    processReq(req) {
      delete req.data.expressions
      delete req.data.columns
      req.params = {}
      req.method = 'get'

      return req
    },
    actAddUsers() {
      pickValues(sdUserPicker, {
        disabledKeys: this.curUsers.map((item) => {
          return item.account
        }),
        rootNode: [{ code: this.curParent.id, name: this.curParent.name }],
        hierarchical: false,
        required: true,
      }).then((res) => {
        if (!res) return
        const adminUserCodes = new Set()
        PermissionService.getRoleUsers({ code: 'ADMINISTRATOR' }).then((res1) => {
          res1.data.treeNode.children.forEach((u) => {
            adminUserCodes.add(u.props.account)
          })
          PermissionService.getRoleUsers({ code: 'SECURITYADMINISTRATOR' }).then((res2) => {
            res2.data.treeNode.children.forEach((u) => {
              adminUserCodes.add(u.props.account)
            })
            PermissionService.getRoleUsers({ code: 'SECURITYAUDITOR' }).then((res3) => {
              res3.data.treeNode.children.forEach((u) => {
                adminUserCodes.add(u.props.account)
              })
              const assingUserCode = []
              res.forEach((u) => {
                if (adminUserCodes.has(u.code) === true) {
                  message.error('用户 ' + u.name + ' 已经是系统三员之一, 不能再添加其它角色')
                } else {
                  assingUserCode.push(u.code)
                }
              })
              if (assingUserCode.length !== 0) {
                this.addUsers(assingUserCode)
              }
            })
          })
        })
      })
    },
    addUsers(ids) {
      this.loadingMsg = message.loading({
        key: this.msgKey,
        content: '处理中...',
        duration: 0,
      })
      return OrgService.roles
        .addUsers({
          id: this.unid,
          account: ids.join(','),
        })
        .then((res) => {
          if (res.status === 200) {
            message.success('处理成功')
            this.$refs.dataTable.refresh(true)
            this.$refs.dataTable.clearSelection(true)
          } else {
            message.error(res.data?.message || '处理失败')
          }
        })
        .catch((error) =>
          message.error({ content: error.response?.data?.message || '处理失败', key: this.msgKey })
        )
        .finally(() => {
          this.loadingMsg?.()
        })
    },
    deleteUsers(ids) {
      this.loadingMsg = message.loading({
        key: this.msgKey,
        content: '处理中...',
        duration: 0,
      })
      return OrgService.roles
        .deleteUsers({
          id: this.unid,
          account: ids.join(','),
        })
        .then((res) => {
          if (res.status === 200) {
            message.success('处理成功')
            this.$refs.dataTable.refresh(true)
            this.$refs.dataTable.clearSelection(true)
          } else {
            message.error(res.data?.message || '处理失败')
          }
        })
        .catch(() => message.error('处理失败'))
        .finally(() => {
          this.loadingMsg?.()
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
