<template>
  <a-modal
    v-model="hieraVisible"
    :class="$style['no-action']"
    v-bind="{ width: 930 }"
    :mask-closable="false"
    :force-render="true"
    @cancel="$emit('closed')"
  >
    <template slot="title">
      {{ title }}
      <a-tooltip title="菜单个性化调整后需手动清理菜单缓存，才能使调整后的菜单生效">
        <a-icon type="exclamation-circle" :class="$style.titleicon" />
      </a-tooltip>
    </template>
    <div>
      <a-tabs v-model="activeKey" @change="tabsChange">
        <a-tab-pane key="0" tab="开关设置">
          <sd-form ref="form" :init-values="switchValues">
            <template v-slot="{ model }">
              <sd-form-item
                v-for="item in switchValues"
                :key="item.name"
                :name="item.name"
                @change="(e) => valueChange(e, item.name)"
              >
                <template v-if="item.name === 'toolEnabled'" v-slot:read-and-edit>
                  <a-radio-group v-model="model[item.name]" :options="item.attr.selectListItem" />
                  <a-tooltip v-if="item.attr.helpTips" :title="item.attr.helpTips">
                    <a-icon type="question-circle-o" />
                  </a-tooltip>
                </template>
              </sd-form-item>
              <div :class="$style['model-bottom-button']">
                <a-space>
                  <a-button type="primary" @click="saveSwitch">保存</a-button>
                  <a-button @click="close">取消</a-button>
                </a-space>
              </div>
            </template>
          </sd-form>
        </a-tab-pane>
        <a-tab-pane v-if="curSwitchValues.status === 1" key="mgrTab" tab="管理员设置" force-render>
          <sd-org-hiera-mgr ref="mgrTab" :unid="unid"></sd-org-hiera-mgr>
        </a-tab-pane>
        <a-tab-pane v-if="curSwitchValues.roleEnabled" key="roleTab" tab="角色个性化" force-render>
          <sd-org-hiera-role ref="roleTab" :unid="unid"></sd-org-hiera-role>
        </a-tab-pane>
        <a-tab-pane v-if="curSwitchValues.menuEnabled" key="menuTab" tab="菜单个性化" force-render>
          <sd-org-hiera-menu ref="menuTab" :unid="unid"> </sd-org-hiera-menu>
        </a-tab-pane>
        <a-tab-pane v-if="curSwitchValues.toolEnabled" key="flowTab" tab="流程个性化" force-render>
          <sd-org-hiera-flow ref="flowTab" :unid="unid"> </sd-org-hiera-flow>
        </a-tab-pane>
        <a-tab-pane v-if="curSwitchValues.status === 1" key="appTab" force-render>
          <template slot="tab">
            应用个性化
            <a-tooltip
              title="开启分级后即开启应用个性化，允许下级创建个性应用，公共应用可选择性下放，应用菜单通过菜单个性化下放，不随应用下放。"
            >
              <a-icon type="question-circle-o" />
            </a-tooltip>
          </template>
          <sd-org-hiera-app ref="appTab" :unid="unid" />
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>

<script>
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-hiera-import'

export default {
  name: 'SdOrgHiera',
  metaInfo: {
    title: 'SdOrgHiera',
  },
  components: { ...components },
  props: {
    unid: {
      type: String,
      default: function() {
        return null
      },
    },
    title: {
      type: String,
      default: '',
    },
  },
  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: [],

      switchValues: [
        {
          name: 'status',
          caption: '分级管理',
          dataType: 'selectlist',
          value: '0',
          attr: {
            selectListItem: [
              { value: '1', label: '启用' },
              { value: '0', label: '禁用' },
            ],
          },
        },
        {
          name: 'roleEnabled',
          caption: '角色个性化',
          dataType: 'selectlist',
          value: 'false',
          attr: {
            selectListItem: [
              { value: 'true', label: '启用' },
              { value: 'false', label: '禁用' },
            ],
          },
        },
        {
          name: 'menuEnabled',
          caption: '菜单个性化',
          dataType: 'selectlist',
          value: 'false',
          attr: {
            selectListItem: [
              { value: 'true', label: '启用' },
              { value: 'false', label: '禁用' },
            ],
          },
        },
        {
          name: 'toolEnabled',
          caption: '流程个性化',
          dataType: 'selectlist',
          value: 'false',
          attr: {
            selectListItem: [
              { value: 'true', label: '启用' },
              { value: 'false', label: '禁用' },
            ],
            helpTips: '流程个性化仅适用于非模块化及27历史版本使用',
          },
        },
      ],
      curSwitchValues: {},
      hieraVisible: false,
      activeKey: '0',
    }
  },
  methods: {
    tabsChange(key) {
      if (key !== '0') {
        this.$refs[key]?.init?.()
      }
    },
    onRoleSelectChange(keys) {
      this.roleSelectedRowKeys = keys
    },
    getHieraManager() {
      OrgService.getHieraManager({ id: this.unid }).then((res) => {
        this.mgrData = res.data.datas
      })
    },
    getByStep() {
      OrgService.getHieraSwitch({ id: this.unid }).then((res) => {
        if (res.data) {
          this.switchValues.forEach((item) => {
            this.$refs.form.setFieldValue(item.name, res.data[item.name]?.toString() || item.value)
          })
        } else {
          this.$refs.form.resetFields()
        }
        this.curSwitchValues = res.data
        this.$nextTick(() => {
          this.hieraVisible = true
        })
      })
    },
    saveSwitch() {
      const params = {
        id: parseInt(this.unid, 10),
      }
      this.$refs.form.getBackendValues().forEach((item) => {
        if (item.name === 'status') {
          params[item.name] = item.value === '1' ? 1 : 0
        } else {
          params[item.name] = item.value === 'true'
        }
      })
      OrgService.saveHieraSwitch(params)
        .then((res) => {
          if (res.status === 200) {
            message.success('保存成功')
            this.getByStep()
          } else {
            message.error(res.data?.message || '保存失败')
          }
        })
        .catch(() => message.error('保存失败'))
        .finally(() => {})
    },
    close() {
      this.hieraVisible = false
    },
    addMgr() {
      this.mgrVisible = true
    },
    addMgrCallBack(success) {
      if (success) {
        this.mgrVisible = false
        this.getHieraManager()
      }
    },
    deleteMgr() {
      const params = this.mgrSelectedRowKeys
      OrgService.deleteHieraManager(params)
        .then((res) => {
          if (res.status === 200) {
            message.success('删除成功')
            this.getHieraManager()
          } else {
            message.error(res.data?.message || '删除失败')
          }
        })
        .catch(() => message.error('删除失败'))
        .finally(() => {})
    },
    valueChange(e, field) {
      const value = e.target.value
      // 修改分级管理开关
      if (field === 'status') {
        // 开启
        if (value === '1') {
          // 如果原本分级为关闭，将菜单个性化修改为开启
          if (this.curSwitchValues.status !== 1) {
            this.$refs.form.setFieldValue('menuEnabled', 'true')
          }
        }
      }
    },
  },
}
</script>

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

.model-bottom-button {
  text-align: center;
}
.model-table-button {
  text-align: right;
}
.no-action {
  :global(.ant-modal-footer) {
    display: none;
  }
}
.titleicon {
  position: relative;
  z-index: 1;
}
</style>
