<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <sd-category-tree
        ref="categoryTree"
        :load-tree-data="loadTreeData"
        @treeSelect="treeSelect"
      />
      <div :class="$style.rightcard">
        <sd-data-table-ex
          v-if="category.id"
          :key="category.id"
          ref="dataTable"
          form-id="weAppModuleMenu"
          page-id="app/appmodulemenu/weAppModuleMenu"
          :columns="columns"
          show-selection
          :actions="actions"
          :filter-expressions="expressions"
          :search-fields="['text']"
          @formBtnClick="formBtnClick"
          @recordSaved="recordSaved"
          @recordsDeleted="recordsDeleted"
        >
          <sd-menu-form
            slot="form"
            slot-scope="scope"
            v-bind="{ ...scope, appId, category, appNodeId }"
            @formCreated="formCreated(scope)"
          />
        </sd-data-table-ex>
      </div>
    </div>
    <a-modal
      v-model="hieraVisible"
      title="权限设置"
      destroy-on-close
      v-bind="{ width: 800 }"
      :mask-closable="false"
      @ok="
        () => {
          this.$refs.hieraForm.save().then((res) => {
            if (res) hieraVisible = false
          })
        }
      "
      @cancel="$emit('closed')"
    >
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="权限">
          <sd-nav-hiera
            ref="hieraForm"
            :cur-parent="belongedOrg"
            :unid="clickedRow"
            :hiera-info="hieraInfo"
            :menu-permission="menuPermission"
          ></sd-nav-hiera>
        </a-tab-pane>
        <a-tab-pane key="2" tab="所有者">
          <sd-nav-owner
            :cur-parent="belongedOrg"
            :hiera-info="hieraInfo"
            :unid="clickedRow"
            :menu-permission="menuPermission"
          />
        </a-tab-pane>
        <a-tab-pane key="3" tab="有效权限">
          <sd-nav-permission-query :unid="clickedRow" />
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script>
import cloneDeep from 'lodash.clonedeep'
import { message } from 'ant-design-vue'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import NavService from '@/nav-manage/nav-service'
import SdNavHiera from '@/nav-manage/sd-nav-hiera.vue'
import sdNavOwner from '@/nav-manage/sd-nav-owner.vue'
import sdNavPermissionQuery from '@/nav-manage/sd-nav-permission-query.vue'
import ApplicationService from './application-service'
import components from './_import-components/sd-menu-manage-import'

export default {
  name: 'SdMenuManage',
  metaInfo() {
    return {
      title: decodeURIComponent((location.hash + '&').split('&appName=')[1]?.split('&')[0] || ''),
    }
  },
  components: {
    ...components,
    'sd-nav-hiera': SdNavHiera,
    'sd-nav-owner': sdNavOwner,
    'sd-nav-permission-query': sdNavPermissionQuery,
  },
  props: {
    appId: {
      type: String,
      default: '',
    },
    appName: {
      type: String,
      default: '',
    },
    appNodeId: {
      type: String,
      default: undefined,
    },
  },
  data() {
    return {
      category: {},
      parentSel: [],
      columns: [
        {
          title: '菜单名称',
          dataIndex: 'text',
          sdClickable: true, // 列内容是否可点击
        },
        {
          title: '菜单链接',
          dataIndex: 'url',
        },
        {
          title: '排序号',
          dataIndex: 'index',
          defaultSortOrder: 'asc',
          width: '100px',
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '150px',
          sdRender: TableColumnTypes.ex.switch,
        },
        {
          title: 'id',
          dataIndex: 'id',
          defaultSortOrder: 'descend', // 排序用(菜单没有创建时间，用id降序排)
          sdHidden: true,
        },
      ],
      actions: [
        {
          label: '清缓存',
          id: 'clear',
          permission: null,
          callback: this.clearCache,
        },
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete,
        },
        {
          label: '授权',
          id: 'setHiera',
          permission: null,
          type: TableActionTypes.inline,
          callback: (record) => {
            this.clickedRow = record.id
            NavService.getPermission({
              params: {
                id: this.clickedRow,
              },
            }).then((res) => {
              this.menuPermission = res.data
              this.hieraVisible = true
            })
          },
        },
        {
          label: '根节点授权',
          id: 'setHiera',
          permission: null,
          callback: () => {
            this.clickedRow = this.rootCatId
            this.hieraVisible = true
          },
        },
      ],
      formData: {}, // 记录菜单文档的数据（修改前）
      needRefresh: false, // 标记菜单文档保存后是否需要刷新左侧树,
      hieraVisible: false,
      belongedOrg: null,
      clickedRow: null,
      hieraInfo: {},
      rootCatId: null,
      menuPermission: null,
    }
  },
  computed: {
    expressions() {
      return [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: this.category.id,
        },
      ]
    },
    computedColumns() {
      return this.columns.filter((col) => col.dataIndex !== 'status')
    },
  },
  created() {
    this.init()
  },
  methods: {
    loadTreeData(parentCatId) {
      const params = { appId: this.appId }
      if (parentCatId) {
        // 非根节点
        params.parentId = parentCatId
      }
      if (!this.rootCatId) {
        this.rootCatId = parentCatId
      }
      if (this.appNodeId) {
        params.appNodeId = this.appNodeId
      }
      return ApplicationService.getAppMenuCategoryTree(params).then((res) => {
        // 当前取的是根节点，获取对应的分级机构id
        if (!parentCatId) {
          this.belongedOrg = { groupId: res.data[0]?.props?.belongedOrgId }
        }
        return res.data
      })
    },
    treeSelect(node) {
      this.category = node
    },
    formCreated({ model }) {
      // 记录当前表单的数据
      this.formData = cloneDeep(model)
    },
    formBtnClick(evt, btn, { form, recordId }) {
      // 当前是新建：标记左侧树需刷新
      if (!recordId) {
        this.needRefresh = true
      } else {
        // 修改，判断点击的是保存按钮
        if (btn.buttonId === 'save') {
          // 判断关键内容是否有更新：菜单名称
          if (this.formData.text !== this.$refs.dataTable.getDetailModal().getFieldValue('text')) {
            // 菜单名称有变化，标记需更新
            this.needRefresh = true
          }
        }
      }
    },
    recordSaved() {
      // 数据保存成功，判断是否需刷新左侧树
      if (this.needRefresh) {
        this.$refs.categoryTree.refresh()
        this.needRefresh = false
      }
    },
    recordsDeleted() {
      this.$refs.categoryTree.refresh()
    },
    clearCache() {
      return ApplicationService.clearMenuCache().then((res) => {
        if (res.status === 200) {
          message.success('缓存已清理！')
        }
      })
    },
    init() {
      NavService.getMenuHiera().then((res) => {
        this.hieraInfo = res.data
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
</style>
