<template>
  <div :class="$style.wrap">
    <div :class="$style.rightcontent">
      <a-card :class="$style['search-result']">
        <sd-data-table
          ref="dataTable"
          :data-url="listDataUrl"
          :actions="actions"
          :columns="columns"
          show-selection
          :process-req="processReq"
          :process-res="processRes"
          @rowClick="rowClick"
        >
          <template slot="randerFirstLoginChangePwd" slot-scope="text, record">
            {{ record.firstLoginChangePwd === true ? '是' : '否' }}
          </template>
        </sd-data-table>
      </a-card>
    </div>
    <a-modal
      v-model="visible"
      title="密级"
      destroy-on-close
      v-bind="{ width: 850 }"
      :mask-closable="false"
      @ok="save"
      @cancel="$emit('closed')"
    >
      <sd-org-classify ref="detailForm" :unid="clickedRow"></sd-org-classify>
    </a-modal>
  </div>
</template>

<script>
import pickValues from '@/common/services/pick-values'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import { Modal } from '@/common/one-ui'
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-classify-category-import'

export default {
  name: 'SdOrgClassifyCategory',
  metaInfo: {
    title: 'SdOrgClassifyCategory',
  },
  components,
  data() {
    return {
      columns: [
        {
          title: '编码',
          dataIndex: 'value',
          sdClickable: true,
        },
        {
          title: '密级',
          dataIndex: 'name',
          sdClickable: true,
        },
        {
          title: '密码最少长度',
          dataIndex: 'minLength',
          sdClickable: true,
        },
        {
          title: '密码有效期（天）',
          dataIndex: 'periodOfValidity',
          sdClickable: true,
        },

        {
          title: '密码尝试次数',
          dataIndex: 'maxAllowAttempts',
          sdClickable: true,
        },
        {
          title: '锁定时长（分钟）',
          dataIndex: 'autoUnlockTime',
          sdClickable: true,
        },
        {
          title: '登录失败预警设置',
          dataIndex: 'warnAttempts',
          sdClickable: true,
        },
        {
          title: '首次登录改密码',
          dataIndex: 'firstLoginChangePwd',
          sdClickable: true,
          scopedSlots: {
            customRender: 'randerFirstLoginChangePwd',
          },
        },
      ],

      actions: [
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: () => {
            if (this.$refs.dataTable.getSelectedRowKeys().length > 1) {
              message.info('仅支持逐条删除')
              return
            }
            return this.delete(this.$refs.dataTable.getSelectedRowKeys())
          },
        },
        {
          label: '批量设置密级',
          id: 'assignUser',
          permission: null,
          type: TableActionTypes.batch,
          callback: () => {
            if (this.$refs.dataTable.getSelectedRowKeys().length > 1) {
              message.info('请选择单条数据')
              return
            }
            return this.assignUser(
              this.$refs.dataTable.getSelectedRows().map((item) => {
                return item.value
              })
            )
          },
        },
        {
          label: '新建',
          id: 'new',
          permission: null,
          type: 'primary',
          // type: TableActionTypes.ex.create,
          callback: () => {
            this.visible = true
            this.clickedRow = null
            this.depParent = this.parent
          },
        },
      ],
      listDataUrl: `api/framework/v1/user-classified/`,
      clickedRow: null,
      visible: false,
      loadingMsg: null,
    }
  },

  methods: {
    processReq(req) {
      delete req.data.expressions
      delete req.data.columns
      req.params = req.data
      req.method = 'get'
      return req
    },
    processRes(resData) {
      return {
        totalSize: resData.length,
        data: resData,
      }
    },
    rowClick(record) {
      this.clickedRow = record.id.toString()
      this.visible = true
    },
    delete(keys) {
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            OrgService.classify.deleteDocs(keys).then((res) => {
              this.$refs.dataTable.clearSelection(true)
              this.$refs.dataTable.refresh()
              resolve()
            })
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    assignUser(ids) {
      pickValues(sdUserPicker, {
        hierarchical: false,
        required: true,
      }).then((res) => {
        if (!res) return
        this.loadingMsg = message.loading({
          key: this.msgKey,
          content: '处理中...',
          duration: 0,
        })
        OrgService.classify
          .setAssignedUser({
            accounts: res
              .map((item) => {
                return item.code
              })
              .join(','),
            classified: ids.join(','),
          })
          .then((res) => {
            if (res.status === 200) {
              message.success('处理成功')
            } else {
              message.error(res.data?.message || '处理失败')
            }
          })
          .catch(() => message.error('处理失败'))
          .finally(() => {
            this.loadingMsg?.()
          })
      })
    },
    save() {
      this.$refs.detailForm.save().then((success) => {
        if (success) {
          this.$refs.dataTable.clearSelection(true)
          this.$refs.dataTable.refresh()
          this.visible = false
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap {
  display: flex;
  height: 100%;

  .rightcontent {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    // :global(.ant-card) {
    //   min-height: 100%;
    // }
  }
}
.no-action {
  :global(.ant-modal-footer) {
    display: none;
  }
}
</style>
