<template>
  <div>
    <div :class="$style['model-table-button']">
      <a-space>
        <a-button type="primary" @click="addMgr">添加</a-button>
        <a-button :disabled="mgrSelectedRowKeys.length === 0" @click="deleteMgr">删除</a-button>
      </a-space>
    </div>
    <sd-table
      ref="mgrDataTable"
      row-key="id"
      :columns="mgrColumn"
      :actions="mgrAction"
      sortable
      :data-source.sync="mgrData"
      :row-selection="{
        onChange: (keys) => {
          onMgrSelectChange(keys)
        },
        selectedRowKeys: mgrSelectedRowKeys,
      }"
      :pagination="false"
    />
    <a-modal
      v-model="mgrVisible"
      title="选择用户"
      :class="$style['no-action']"
      destroy-on-close
      v-bind="{ width: 800 }"
      :mask-closable="false"
      @ok="save"
      @cancel="$emit('closed')"
    >
      <sd-form ref="form" :init-values="values">
        <template v-slot="{ model }">
          <sd-form-item name="managerType" />
          <sd-form-item name="assigners">
            <sd-user-picker
              v-model="model.assigners"
              :hierarchical="false"
              :disabled-keys="disabledKeys"
              :read-only="false"
            />
          </sd-form-item>
        </template>
      </sd-form>
    </a-modal>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import { sdLocalStorage } from '@/common/services/storage-service'
import OrgService from './org-service'
import components from './_import-components/sd-org-hiera-mgr-import'

export default {
  name: 'SdOrgHieraMgr',
  metaInfo: {
    title: 'SdOrgHieraMgr',
  },
  components,
  props: {
    unid: {
      type: String,
      default: function() {
        return null
      },
    },
  },
  data() {
    return {
      mgrDataUrl: `api/framework/manage/v1/hiera-manage/manager/${this.unid}`,
      mgrColumn: [
        {
          title: '姓名',
          dataIndex: 'assignerName',
          sdClickable: true,
        },
        {
          title: '账户',
          dataIndex: 'assigner',
          sdClickable: true,
        },
        {
          title: '管理员类型',
          dataIndex: 'managerTypeName',
          sdClickable: true,
          defaultSortOrder: 'asc',
        },
        {
          title: '所属机构',
          dataIndex: 'assignerGroupName',
          sdHidden: true,
          defaultSortOrder: 'asc',
        },
      ],
      mgrAction: [
        {
          label: '新建',
          id: 'new',
          permission: null,
          // type: TableActionTypes.ex.create,
          callback: () => {
            this.visible = true
            this.clickedRow = null
            this.depParent = this.parent
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: () => {
            return this.delete(this.$refs.dataTable.getSelectedRowKeys())
          },
        },
      ],
      mgrData: [],
      mgrVisible: false,
      mgrSelectedRowKeys: [],
      parentInfo: null,
      updateKey: 0,
      disabledKeys: ['hdadmin', 'secadmin', 'audit'],
      values: [
        {
          name: 'assigners',
          caption: '用户',
          dataType: 'selectuser',
          required: true,
        },
        {
          name: 'managerType',
          caption: '管理员类型',
          dataType: 'selectlist',
          value: 'SUBADMIN',
          attr: {
            selectListItem: [{ value: 'SUBADMIN', label: '下级系统管理员' }],
          },
        },
      ],
    }
  },
  created() {
    if (JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').openSecret === true) {
      this.values[1].attr.selectListItem.push({
        value: 'SUBSECURITYADMIN',
        label: '下级安全管理员',
      })
    }
  },
  methods: {
    init() {
      this.mgrVisible = false
      this.mgrSelectedRowKeys = []
      this.getHieraManager()
    },
    onMgrSelectChange(keys) {
      this.mgrSelectedRowKeys = keys
    },
    getHieraManager() {
      OrgService.getHieraManager({ id: this.unid }).then((res) => {
        this.mgrData = res.data.datas
      })
    },
    save() {
      return new Promise((resolve) => {
        this.$refs.form.validateFields().then((success) => {
          if (success) {
            const params = {}
            this.$refs.form.getBackendValues().forEach((item) => {
              params[item.name] = item.value
              if (item.name === 'assigners') {
                params[item.name] = JSON.parse(item.value).map((user) => {
                  return user.code
                })
              }
            })

            params.groupId = parseInt(this.unid, 10)
            return OrgService.addHieraManager(params)
              .then((res) => {
                if (res.status === 200) {
                  message.success('保存成功')
                  this.init()
                  resolve(true)
                } else {
                  message.error(res.data?.message || '保存失败')
                }
              })
              .catch((res) => {
                message.error(res?.response?.data?.message || '保存失败')
              })
              .finally(() => {})
          }
        })
      })
    },
    close() {
      this.$emit('cancel')
    },
    addMgr() {
      this.mgrVisible = true
      if (this.$refs.form) this.$refs.form.setFieldValue('assigners', undefined)
    },
    deleteMgr() {
      const params = this.mgrSelectedRowKeys
      OrgService.deleteHieraManager(params)
        .then((res) => {
          if (res.status === 200) {
            message.success('删除成功')
            this.init()
          } else {
            message.error(res.data?.message || '删除失败')
          }
        })
        .catch(() => message.error('删除失败'))
        .finally(() => {})
    },
  },
}
</script>

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

.model-bottom-button {
  text-align: center;
}
</style>
