<template>
  <div :class="$style.wrap">
    <div :class="$style.lefttree">
      <sd-org-tree v-if="rootReady" ref="tree" :root-data="root" @treeSelect="treeSelect" />
    </div>
    <div v-if="parent" :class="$style.rightcontent">
      <sdSearchForm
        v-show="advSearchBtnActived"
        ref="searchForm"
        :class="$style['search-form']"
        :onl-list-column-defs="searchFields"
        @search="search"
        @close="() => (advSearchBtnActived = false)"
      />
      <a-card :class="$style['search-result']">
        <sd-data-table
          v-if="rootReady"
          ref="dataTable"
          :data-url="listDataUrl"
          :actions="actions"
          :columns="columns"
          show-selection
          :filter-expressions="filterExpressions"
          :process-req="(req) => processReq(req, 'orgGroupCategory')"
          :search-fields="showfuzzySearch ? ['name'] : []"
          :class="$style.fuzzyAdvSearch"
          @rowClick="rowClick"
        >
          <template slot="randerEnabled" slot-scope="text, record">
            {{ record.enabled === 1 ? '正常' : '停用' }}
          </template>
          <!-- 高级查询 -->
          <template slot="headerPrefix">
            <SdAvanceSearchBtn
              :actived="advSearchBtnActived"
              :class="$style.advsearchbtn"
              @click="switchSearch"
            />
          </template>
        </sd-data-table>
      </a-card>
    </div>
    <a-card v-else :class="$style.rightcontent" />
    <a-modal
      v-model="visible"
      title="用户组"
      destroy-on-close
      v-bind="{ width: 800 }"
      :mask-closable="false"
      @ok="save"
      @cancel="$emit('closed')"
    >
      <sd-org-group ref="detailForm" :unid="clickedRow" :cur-parent="depParent"></sd-org-group>
    </a-modal>
  </div>
</template>

<script>
import download from '@/common/services/download'
import { Modal } from '@/common/one-ui'
import { message } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import SdAvanceSearchBtn from '@/application-manage/sd-advance-search-btn.vue'
import sdSearchForm from './sd-org-list-search.vue'
import SdOrgCommonMixins from './sd-org-common-mixins.vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-group-category-import'

export default {
  name: 'SdOrgGroupCategory',
  metaInfo: {
    title: '群组管理',
  },
  components: { ...components, sdSearchForm, SdAvanceSearchBtn },
  mixins: [SdOrgCommonMixins],
  data() {
    return {
      loadingMsg: null,
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          sdClickable: true,
        },
        {
          title: '所属组织',
          dataIndex: 'groupName',
        },
        {
          title: '状态',
          dataIndex: 'enabled',
          scopedSlots: {
            customRender: 'randerEnabled',
          },
        },
        {
          title: '代码',
          dataIndex: 'code',
        },

        {
          title: '排序号',
          dataIndex: 'sortNumber',
          defaultSortOrder: 'asc',
        },
        {
          title: '备注',
          dataIndex: 'description',
        },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: () => {
            return this.delete(this.$refs.dataTable.getSelectedRowKeys())
          },
        },

        {
          label: '新建',
          id: 'new',
          permission: null,
          type: 'primary',
          callback: () => {
            this.visible = true
            this.clickedRow = null
            this.depParent = this.parent
          },
        },
      ],
      searchFields: [
        {
          fieldId: 'name',
          fieldName: '名称',
          fieldType: 'string',
          dataType: 'string',
          search: true,
        },
        {
          fieldId: 'code',
          fieldName: '代码',
          fieldType: 'string',
          dataType: 'string',
          search: true,
        },
        {
          fieldId: 'enabled',
          fieldName: '状态',
          fieldType: 'number',
          dataType: 'number',
          attr: {
            selectListItem: [
              {
                value: '1',
                label: '正常',
              },
              {
                value: '0',
                label: '停用',
              },
            ],
          },
          search: true,
        },
      ],
      depParent: null,
      root: null,
      searchValue: '',
      listDataUrl: `api/framework/v1/usergroup-manager/query/usergroups`,
      listData: [],
      rootReady: false,
      clickedRow: null,
      visible: false,
      hieraVisible: false,
    }
  },
  methods: {
    exportZip(ids, records) {
      OrgService.exportUser.exportZip(ids).then((res) => {
        return download(
          `api/framework/v1/tmp-file/download/${res.data.id}`,
          `${res.data.name}`,
          true
        )
      })
    },
    exportUser(ids, records) {
      OrgService.exportUser.exportUserExcel(ids).then((res) => {
        return download(
          `api/framework/v1/tmp-file/download/${res.data.id}`,
          `${res.data.name}`,
          true
        )
      })
    },
    rowClick(record) {
      this.clickedRow = record.id.toString()
      this.visible = true
    },
    delete(keys) {
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })
            OrgService.group
              .deleteDocs(keys)
              .then((res) => {
                this.$refs.dataTable.clearSelection(true)
                this.$refs.dataTable.refresh()
                if (res.status === 200) {
                  message.success('处理成功')
                } else {
                  message.error(res.data?.message || '处理失败')
                }
              })
              .catch(() => message.error('处理失败'))
              .finally(() => {
                this.loadingMsg?.()
                resolve()
              })
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    hiera(id) {
      this.clickedRow = id.toString()
      this.hieraVisible = true
    },
    save() {
      this.$refs.detailForm.save().then((success) => {
        if (success) {
          this.$refs.dataTable.clearSelection(true)
          this.$refs.dataTable.refresh()
          this.visible = false
        }
      })
    },
    init() {
      OrgService.getOrgDepRoot().then((roots) => {
        this.parent = roots.data[0]
        this.rootReady = true
      })
    },
  },
}
</script>

<style module lang="scss">
@import './org-manager.scss';
</style>
