<template>
  <div :class="$style.wrap">
    <div :class="$style.lefttree">
      <sd-org-tree
        v-if="rootReady"
        ref="tree"
        :root-data="root"
        editable
        @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="isSecAdmin ? false : true"
          :filter-expressions="filterExpressions"
          :process-req="processReq"
          :search-fields="showfuzzySearch ? ['name'] : []"
          :class="$style.fuzzyAdvSearch"
          @rowClick="rowClick"
        >
          <!-- 高级查询 -->
          <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="isBatch ? '批量修改' : '机构'"
      destroy-on-close
      v-bind="{ width: 800 }"
      :mask-closable="false"
      @ok="save"
      @cancel="$emit('closed')"
    >
      <sd-org-dep
        ref="detailForm"
        :unid="clickedRow"
        :cur-parent="depParent"
        :editable="!isSecAdmin"
        :is-batch="isBatch"
      ></sd-org-dep>
      <template slot="footer">
        <a-button
          type="white"
          @click="
            () => {
              visible = false
            }
          "
          >取消</a-button
        >
        <a-button v-if="!isSecAdmin" type="primary" :loading="orgSaving" @click="save"
          >确定</a-button
        >
      </template>
    </a-modal>
    <sd-org-hiera
      v-if="clickedRow"
      ref="hieraForm"
      :unid="clickedRow"
      :title="title"
    ></sd-org-hiera>
    <!-- 导入部门 -->
    <sd-org-import
      ref="importForm"
      :import-form-data="importFormData"
      :req-url="importDataUrl"
      :bussiness-id="'org'"
      :process-param="
        (params) => {
          if (params.groupId) params.groupId = params.groupId[0].key
          return params
        }
      "
      @feedback="
        (res) => {
          if (res) {
            this.$refs.dataTable.clearSelection(true)
            this.$refs.dataTable.refresh()
            this.$refs.tree.refresh()
          }
        }
      "
    ></sd-org-import>
    <a-modal
      v-model="sortVisiable"
      title="排序"
      destroy-on-close
      v-bind="{ width: 800 }"
      :mask-closable="false"
      :confirm-loading="sortSaving"
      @ok="saveSort"
      @cancel="() => (sortVisiable = false)"
    >
      <sd-data-sort ref="dataSort" :columns="sortColumns" :load-data="loadData" />
    </a-modal>
  </div>
</template>

<script>
import storeMixin from '@/common/store-mixin'
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 sdOrgImport from './sd-org-import.vue'
import SdOrgCommonMixins from './sd-org-common-mixins.vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-dep-category-import'

export default {
  name: 'SdOrgDepCategory',
  metaInfo: {
    title: '组织管理',
  },
  components: { ...components, sdSearchForm, sdOrgImport, SdAvanceSearchBtn },
  mixins: [storeMixin, SdOrgCommonMixins],
  provide() {
    return {
      depInfo: this.depInfo,
    }
  },
  data() {
    return {
      title: '',
      visibleImport: false,
      loadingMsg: null,
      importConfirmLoading: false,
      importType: '',
      importFormData: [],
      fileList: [],
      depInfo: {
        id: null,
        name: null,
      },
      columns: [
        {
          title: '代码',
          dataIndex: 'code',
        },

        {
          title: '名称',
          dataIndex: 'name',
          sdClickable: true,
        },
        {
          title: '排序号',
          dataIndex: 'weight',
          defaultSortOrder: 'asc',
        },
        {
          title: 'code',
          dataIndex: 'id',
          sdHidden: true,
          defaultSortOrder: 'asc',
        },
        {
          title: '级别',
          dataIndex: 'level',
        },
        {
          title: '备注信息',
          dataIndex: 'description',
        },
      ],
      sortColumns: [
        {
          title: '代码',
          dataIndex: 'code',
        },
        {
          title: '名称',
          dataIndex: 'name',
        },
        {
          title: '排序号',
          dataIndex: 'weight',
        },
      ],
      actions: [
        {
          label: '新建子部门',
          id: 'newChild',
          permission: null,
          type: TableActionTypes.inline,
          callback: (record) => {
            this.visible = true
            this.clickedRow = null
            this.depParent = {
              ...record,
              text: record.name,
            }
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: () => {
            return this.delete(this.$refs.dataTable.getSelectedRowKeys())
          },
        },
        {
          label: '导出',
          id: 'export',
          permission: null,
          type: TableActionTypes.batch,
          children: [
            {
              label: '压缩包格式',
              id: 'exportZip',
              type: TableActionTypes.batch,
              permission: null,
              // callback: this.exportZip,
              callback: () => {
                return this.exportZip(
                  this.$refs.dataTable.getSelectedRowKeys(),
                  this.$refs.dataTable.getSelectedRows()
                )
              },
            },
            {
              label: 'Excel格式-机构',
              id: 'exportDep',
              type: TableActionTypes.batch,
              permission: null,
              callback: () => {
                return this.exportDep(
                  this.$refs.dataTable.getSelectedRowKeys(),
                  this.$refs.dataTable.getSelectedRows()
                )
              },
            },
            {
              label: 'Excel格式-用户',
              id: 'exportUser',
              type: TableActionTypes.batch,
              permission: null,
              callback: () => {
                return this.exportUser(
                  this.$refs.dataTable.getSelectedRowKeys(),
                  this.$refs.dataTable.getSelectedRows()
                )
              },
            },
          ],
          callback: () => {},
        },
        {
          label: '排序',
          id: 'sorter',
          permission: null,
          callback: () => (this.sortVisiable = true),
        },
        {
          label: '导入',
          id: 'importData',
          permission: null,
          children: [
            {
              label: '压缩包格式',
              id: 'importZip',
              // type: TableActionTypes.batch,
              permission: null,
              // callback: this.exportZip,
              callback: () => {
                this.visibleImport = true
                this.importType = 'zip'
                this.importFormData = this.getImportFormData()
                this.importDataUrl = `api/framework/v1/group-manager/import`
                this.$refs.importForm.show(`导入压缩包`)
              },
            },
            {
              label: 'Excel格式-机构',
              id: 'importDep',
              // type: TableActionTypes.batch,
              permission: null,
              callback: () => {
                this.visibleImport = true
                this.importType = 'dep'
                this.importFormData = this.getImportFormData()
                this.importDataUrl = `api/framework/v1/group-manager/import-excel`
                this.$refs.importForm.show(`Excel格式-机构`)
              },
            },
            {
              label: 'Excel格式-用户',
              id: 'importUser',
              // type: TableActionTypes.batch,
              permission: null,
              callback: () => {
                this.visibleImport = true
                this.importType = 'user'
                this.importFormData = this.getImportFormData()
                this.importDataUrl = `api/framework/v1/user-manager/import-excel`
                this.$refs.importForm.show(`Excel格式-用户`)
              },
            },
          ],
          callback: () => {},
        },
        {
          label: '分级管理',
          id: 'hiera',
          permission: null,
          type: TableActionTypes.inline,
          callback: (row) => {
            this.depInfo.id = row.id
            this.depInfo.name = row.name
            this.title = row.name + '-分级管理设置'
            return this.hiera(row.id)
          },
        },
        {
          label: '批量修改',
          id: 'batchModify',
          permission: null,
          type: TableActionTypes.batch,
          callback: this.batchModify,
        },
        {
          label: '新建',
          id: 'new',
          permission: null,
          type: 'primary',
          // type: TableActionTypes.ex.create,
          callback: () => {
            this.isBatch = false
            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,
        },
      ],
      depParent: null,
      root: null,
      searchValue: '',
      listDataUrl: `api/framework/v1/group-manager/list`,
      listData: [],
      rootReady: false,
      clickedRow: null,
      visible: false,
      hieraVisible: false,
      importDataUrl: '',
      isSecAdmin: false,
      isBatch: false,
      orgSaving: false,
      sortVisiable: false,
      sortSaving: false,
    }
  },
  methods: {
    getImportFormData() {
      const sType = this.importType
      if (sType === 'zip') {
        return [
          {
            name: 'groupId',
            dataType: 'String',
            caption: '目标机构',
            isOrgTree: true,
            readonly: false,
            required: true,
          },

          {
            name: 'tmpFileInfo',
            dataType: 'attachment',
            caption: '数据文件',
            readonly: false,
            required: true,
            value: '{"value":"' + this.filegroupid() + '"}',
            attr: {
              allowType: '.gz',
              maxLength: 1,
              uploadable: true,
            },
          },
          {
            name: 'conflictStrategy',
            dataType: 'selectlist',
            caption: '导入策略',
            readonly: false,
            required: false,
            attr: {
              defaultValue: '0',
              multiple: 'false',
              selectListItem: [
                {
                  label: '跳过已存在的机构/用户',
                  value: '0',
                },
                {
                  label: '覆盖已存在的机构/用户',
                  value: '1',
                },
                {
                  label: '停止导入',
                  value: '2',
                },
              ],
            },
          },
        ]
      } else if (sType === 'dep') {
        return [
          {
            name: 'tmpFileInfo',
            dataType: 'attachment',
            caption: '数据文件',
            readonly: false,
            required: true,
            attr: {
              allowType: '.xls',
              maxLength: 1,
              uploadable: true,
            },
          },
          {
            name: 'conflictStrategy',
            dataType: 'selectlist',
            caption: '导入策略',
            readonly: false,
            required: false,
            attr: {
              defaultValue: '0',
              multiple: 'false',
              selectListItem: [
                {
                  label: '跳过已存在的机构',
                  value: '0',
                },
                {
                  label: '覆盖已存在的机构',
                  value: '1',
                },
              ],
            },
          },
          {
            name: 'temlpate',
            dataType: 'string',
            caption: '导入模板',
            importType: 'dep',
            template: {
              name: '组织导入模板',
              url: 'api/framework/v1/group-manager/excel-template',
            },
          },
        ]
      } else if (sType === 'user') {
        return [
          {
            name: 'tmpFileInfo',
            dataType: 'attachment',
            caption: '数据文件',
            readonly: false,
            required: true,
            attr: {
              allowType: '.xls',
              maxLength: 1,
              uploadable: true,
            },
          },
          {
            name: 'conflictStrategy',
            dataType: 'selectlist',
            caption: '导入策略',
            readonly: false,
            required: false,
            attr: {
              defaultValue: '0',
              multiple: 'false',
              selectListItem: [
                {
                  label: '跳过已存在的用户',
                  value: '0',
                },
                {
                  label: '覆盖已存在的用户',
                  value: '1',
                },
              ],
            },
          },
          {
            name: 'temlpate',
            dataType: 'string',
            caption: '导入模板',
            importType: 'user',
            template: {
              name: '用户导入模板',
              url: 'api/framework/v1/user-manager/excel-template',
            },
          },
        ]
      }
    },
    rowClick(record) {
      this.clickedRow = record.id.toString()
      this.isBatch = false
      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.deleteOrgDep(keys)
              .then((res) => {
                this.$refs.dataTable.clearSelection(true)
                this.$refs.dataTable.refresh()
                this.$refs.tree.refresh()
                if (res.status === 200 && res.data !== 1) {
                  message.success('处理成功')
                } else {
                  message.error(res.data?.message || '处理失败')
                }
              })
              .catch(() => message.error('处理失败'))
              .finally(() => {
                this.loadingMsg?.()
                resolve()
              })
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    hiera(id) {
      this.clickedRow = id.toString()
      this.$nextTick(() => {
        this.$refs.hieraForm.getByStep()
        this.$refs.hieraForm.activeKey = '0'
      })
    },
    save() {
      this.orgSaving = true
      this.$refs.detailForm
        .save(this.$refs.dataTable.getSelectedRowKeys())
        .then((success) => {
          if (success) {
            this.$refs.dataTable.clearSelection(true)
            this.$refs.dataTable.refresh()
            this.$refs.tree.refresh()
            this.visible = false
          }
        })
        .finally(() => {
          this.orgSaving = false
        })
    },
    init() {
      const isSecAdmin = this.userInfo.roles.some((item) => {
        return ['SECURITYADMINISTRATOR', 'SUB_SECURITY_ADMIN'].indexOf(item.code) > -1
      })
      if (isSecAdmin) {
        this.isSecAdmin = true
        this.actions = []
      }

      OrgService.getOrgDepRoot().then((roots) => {
        this.parent = roots.data[0]
        this.rootReady = true
      })
    },
    onLoadTreeData(parentCatId, parentCatObj) {
      return new Promise((resolve) => {
        if (parentCatId) {
          return OrgService.getOrgDepTree({ id: parentCatId }).then((deps) => {
            resolve(this.parseTreeData(deps.data))
          })
        } else {
          return OrgService.getOrgDepRoot().then((roots) => {
            resolve(this.parseTreeData(roots.data))
          })
        }
      })
    },
    parseTreeData(deps) {
      return deps.map((dep) => {
        return {
          key: dep.id,
          title: dep?.props?.hierarchical === 'true' ? dep.text + '(已开启分级)' : dep.text,
          name: dep.text,
          isLeaf: dep.leaf,
          scopedSlots: {
            title: 'title',
          },
        }
      })
    },

    exportZip(ids, records) {
      OrgService.exportDep.exportZip(ids).then((res) => {
        return download(
          `api/framework/v1/tmp-file/download/${res.data.id}`,
          `${res.data.name}`,
          true
        )
      })
    },
    exportDep(ids, records) {
      OrgService.exportDep.exportDepExcel(ids).then((res) => {
        return download(
          `api/framework/v1/tmp-file/download/${res.data.id}`,
          `${res.data.name}`,
          true
        )
      })
    },
    exportUser(ids, records) {
      OrgService.exportDep
        .exportUserExcel(ids)
        .then((res) => {
          const fileId = res.data.id
          let isNotRunning = true
          const refreshFileInfo = function() {
            if (isNotRunning) {
              isNotRunning = true
              OrgService.getTmpFileInfo(fileId)
                .then((file) => {
                  if (file.data.mimeType === 'broken') {
                    window.clearInterval(refreshMonitor)
                    message.error('导出失败！')
                    return
                  }
                  if (file.data.size > 0) {
                    window.clearInterval(refreshMonitor)
                    download(
                      `api/framework/v1/tmp-file/download/${res.data.id}`,
                      `${res.data.name}`,
                      true
                    )
                  }
                  isNotRunning = true
                })
                .catch((error) => {
                  message.error(error?.response?.data?.message || '导出失败')
                })
                .finally(() => {})
            }
          }
          const refreshMonitor = window.setInterval(refreshFileInfo, 1000)
        })
        .catch(() => message.error('导出失败'))
        .finally(() => {})
    },
    filegroupid() {
      return 'app_' + new Date().getTime() + '_' + (Math.floor(Math.random() * 100) + 1)
    },
    batchModify() {
      this.isBatch = true
      this.visible = true
      this.clickedRow = null
      this.depParent = this.parent
    },
    loadData() {
      return OrgService.getOrgDepList({
        expressions: [
          {
            dataType: 'str',
            name: 'parentId',
            op: 'eq',
            stringValue: this.parent.id,
          },
        ],
        orderBy: 'weight asc,code asc',
        startPosition: 0,
        maxResults: -1,
      }).then((res) => {
        return res.data.datas.map((d) => ({ ...d, key: d.id }))
      })
    },
    saveSort() {
      const data = this.$refs.dataSort.getData()
      this.sortSaving = true
      OrgService.sortOrgDep(data.map((d) => d.id))
        .then((res) => {
          if (res.status === 200) {
            message.success('排序成功！')
            this.$refs.dataTable.refresh()
            this.sortVisiable = false
          }
        })
        .finally(() => {
          this.sortSaving = false
        })
    },
  },
}
</script>

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