<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="isSysAdmin ? true : false"
          :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-user
        ref="detailForm"
        :unid="clickedRow"
        :cur-parent="depParent"
        :editable="isSysAdmin"
        :is-batch="isBatch"
      ></sd-org-user>
      <template slot="footer">
        <a-button
          type="white"
          @click="
            () => {
              visible = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" :loading="userSaving" @click="save">确定</a-button>
      </template>
    </a-modal>

    <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 SdOrgCommonMixins from './sd-org-common-mixins.vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-user-category-import'

export default {
  name: 'SdOrgUserCategory',
  metaInfo: {
    title: '用户管理',
  },
  components: { ...components, sdSearchForm, SdAvanceSearchBtn },
  mixins: [storeMixin, SdOrgCommonMixins],
  data() {
    return {
      loadingMsg: null,
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          sdClickable: true,
        },
        {
          title: '部门',
          dataIndex: 'parentPathName',
        },
        {
          title: '职务',
          dataIndex: 'levelName',
        },
        {
          title: '手机号',
          dataIndex: 'mobile',
        },
        {
          title: '账号',
          dataIndex: 'account',
        },
        {
          title: '排序号',
          dataIndex: 'weight',
        },

        {
          title: '账号状态',
          dataIndex: 'statusName',
        },
        {
          title: '排序号',
          dataIndex: 'weight',
          sdHidden: true,
          defaultSortOrder: 'asc',
        },
      ],
      sortColumns: [
        {
          title: '名称',
          dataIndex: 'name',
        },
        {
          title: '部门',
          dataIndex: 'parentPathName',
        },
        {
          title: '职务',
          dataIndex: 'levelName',
        },
        {
          title: '排序号',
          dataIndex: 'weight',
        },
      ],
      actions: [
        {
          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: '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: '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: 'account',
          fieldName: '账号',
          fieldType: 'string',
          dataType: 'string',
          search: true,
        },
        {
          fieldId: 'status',
          fieldName: '账号状态',
          fieldType: 'number',
          dataType: 'number',
          attr: {
            selectListItem: [
              {
                value: '0',
                label: '未激活',
              },
              {
                value: '1',
                label: '正常',
              },
              { value: '2', label: '注销' },
              { value: '4', label: '账户已过期' },
              { value: '8', label: '密码已过期' },
              { value: '17', label: '已锁定' },
              { value: '32', label: '停用' },
              { value: '64', label: '禁止登录' },
            ],
          },
          search: true,
        },
      ],
      depParent: null,
      root: null,
      searchValue: '',
      listDataUrl: `api/framework/v1/user-manager/all/users_query`,
      listData: [],
      rootReady: false,
      clickedRow: null,
      visible: false,
      hieraVisible: false,
      isSysAdmin: false,
      isBatch: false,
      userSaving: false,
      sortVisiable: false,
      sortSaving: 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) => {
        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)
      })
    },
    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.deleteOrgUser(keys)
              .then((res) => {
                this.$refs.dataTable.clearSelection(true)
                this.$refs.dataTable.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.hieraVisible = true
    },
    save() {
      this.userSaving = true
      this.$refs.detailForm
        .save(this.$refs.dataTable.getSelectedRowKeys())
        .then((success) => {
          if (success) {
            this.$refs.dataTable.clearSelection(true)
            this.$refs.dataTable.refresh()
            this.visible = false
          }
        })
        .finally(() => {
          this.userSaving = false
        })
    },
    init() {
      this.isSysAdmin = this.userInfo.roles.some((item) => {
        return ['ADMINISTRATOR', 'SUB_ADMIN'].indexOf(item.code) > -1
      })
      if (!this.isSysAdmin) {
        this.actions = []
      }
      OrgService.getOrgDepRoot().then((roots) => {
        this.parent = roots.data[0]
        this.rootReady = true
      })
    },
    batchModify() {
      this.isBatch = true
      this.visible = true
      this.clickedRow = null
      this.depParent = this.parent
    },
    loadData() {
      return OrgService.getOrgUserList({
        expressions: [
          {
            dataType: 'str',
            name: 'parentId',
            op: 'eq',
            stringValue: this.parent.id,
          },
        ],
        orderBy: 'weight 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.sortOrgUser(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>
