<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <km-tree-async
        ref="tree"
        :load-tree-data="loadTreeData"
        option-count="count"
        @treeSelectd="treeSelectd"
      />
      <div :class="$style.rightcard">
        <a-card>
          <sd-oa-table
            v-if="expressions.length > 0"
            ref="oaTable"
            :form-id="formId"
            :page-id="pageId"
            :columns="columns"
            :actions="actions"
            :filter-expressions="expressions"
            :show-selection="showDeleteBtn"
            :search-fields="['title']"
            :row-selection="{ type: 'radio' }"
            @formBtnClick="formBtnClick"
            @recordsDeleted="onRecordsDeleted"
          >
            <a
              slot="fldSubject"
              slot-scope="text, record"
              :title="text"
              @click="knowledageView(record)"
              >{{ text }}</a
            >

            <template v-slot:form="{ model }">
              <km-atom-table ref="atomTable" :model="model" :default-category="defaultCategory" />
            </template>
          </sd-oa-table>

          <!-- 导入文件 -->
          <a-modal
            :footer="null"
            :title="modalImport.title"
            :visible="modalImport.visible"
            :width="650"
            destroy-on-close
            :mask-closable="false"
            @cancel="() => (modalImport.visible = false)"
          >
            <a-form>
              <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
                <sd-attachment
                  :max="1"
                  :group-id="filegroupid"
                  accept=".xls,.xlsx"
                  @change="importfromfile"
                >
                </sd-attachment>
              </a-form-item>
              <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
                <a-button type="link" @click="fnDownloadTemplate">
                  点此下载模板
                </a-button>
              </a-form-item>
            </a-form>
          </a-modal>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { Message, Modal } from 'ant-design-vue'
import { getUserPerms } from '@/common/store-mixin'
import download from '@/common/services/download'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import KmKnowledageService from '../km-knowledage-service'
import components from './_import-components/km-atom-knowledage-import'

const formData = new FormData()
export default {
  name: 'KmAtomKnowledage',
  metaInfo: {
    title: '原子知识',
  },
  components,
  data() {
    return {
      formId: 'kmKnowledge',
      pageId: 'knowledge/kmAtom/kmAtom',
      expressions: [],
      formHomeId: '',
      columns: [
        {
          title: '标题',
          dataIndex: 'title',
          scopedSlots: { customRender: 'fldSubject' },
        },
        {
          title: '贡献者',
          dataIndex: 'creatorName',
        },
        {
          title: '所属分类',
          dataIndex: 'categoryName',
        },
        {
          title: '分类id',
          dataIndex: 'categoryId',
          sdHidden: true,
        },
        {
          title: '阅读次数',
          dataIndex: 'readTimes',
        },
        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.dateTime,
        },
      ],

      modalImport: {
        title: '导入原子知识',
        visible: false,
        formData,
      },

      groupid: Math.floor(Math.random()) * 10 + 1,
      filegroupid: 'atom_' + new Date().getTime().toString(16) + '_' + this.groupid,
      defaultCategory: '',

      showCreateBtn: false,
      showDeleteBtn: false,
      showImportBtn: false,
      showEditBtn: false,
    }
  },
  computed: {
    actions() {
      const actions = []
      if (this.showCreateBtn) {
        actions.push({
          label: '新建',
          id: 'creat',
          type: TableActionTypes.oa.create,
        })
      }

      if (this.showDeleteBtn) {
        actions.push({
          label: '删除',
          id: 'delete',
          type: TableActionTypes.oa.delete,
        })
      }

      if (this.showImportBtn) {
        actions.push({
          label: '导入',
          id: 'export',
          permission: null,
          callback: () => {
            this.modalImport.visible = true
            this.groupid = Math.floor(Math.random() * 100) + 1
            this.filegroupid = 'atom_' + new Date().getTime().toString(16) + '_' + this.groupid
          },
        })
      }

      if (this.showEditBtn) {
        actions.push({
          label: '编辑',
          id: 'edit',
          type: TableActionTypes.inline,
          callback: (record) => {
            this.$refs.oaTable.showDetailModal(record.id, this.pageId)
          },
        })
      }

      return actions
    },
  },
  created() {
    // 判断权限
    const userPerms = getUserPerms()
    if ('kmAtomKnowledge-create' in userPerms) {
      this.showCreateBtn = true
    }
    if ('kmAtomKnowledge-delete' in userPerms) {
      this.showDeleteBtn = true
    }
    if ('kmAtomKnowledge-import' in userPerms) {
      this.showImportBtn = true
    }
    if ('kmAtomKnowledge-update' in userPerms) {
      this.showEditBtn = true
    }
  },
  methods: {
    // 获取分类树
    loadTreeData(parentCatId) {
      const params = {
        pageId: 'atomKnowledge',
        categoryId: parentCatId || 0,
      }
      return KmKnowledageService.getKnowledgeTree(params).then((res) => {
        return res.data
      })
    },

    onRecordsDeleted() {
      this.$refs.tree.refresh() // 刷新树
    },

    // 查看数据
    knowledageView(record) {
      setTimeout(() => {
        this.$refs.oaTable.refresh()
      }, 5000)
      window.open(
        `#/km-knowledage-view?id=${record.id}&title=${record.title}&typeId=${record.categoryId}&typeName=${record.categoryName}`,
        '_blank'
      )
    },

    // 树选择节点后获取列表数据
    treeSelectd(item) {
      this.num++
      let parentId = ''
      let parentName = ''
      if (item.id !== undefined) {
        parentId = item.id
        parentName = item.text
      } else {
        parentId = item.selectedNodes[0].data.props.id
        parentName = item.selectedNodes[0].data.props.text
      }
      const obj = {
        id: parentId,
        name: parentName,
      }
      this.defaultCategory = [obj]

      this.selectdParentId = parseInt(parentId)
      this.selectdParentName = parentName
      const filter = [
        {
          dataType: 'str',
          name: 'categoryId',
          op: 'eq',
          stringValue: this.selectdParentId,
        },
        {
          dataType: 'str',
          name: 'type',
          op: 'eq',
          stringValue: '1',
        },
        {
          dataType: 'int',
          name: 'atomState',
          op: 'gt',
          stringValue: 0, // 1：已发布，0：草稿
        },
      ]

      this.expressions = filter
    },

    // 保存和发布
    formBtnClick(evt, btn, { form, recordId }) {
      switch (btn.buttonId) {
        case 'save': {
          evt.waitUntil(
            new Promise((resolve, reject) => {
              form.setFieldValue('atomState', 1)
              resolve()
            })
          )
          break
        }

        case 'keep': {
          evt.waitUntil(
            new Promise((resolve, reject) => {
              if (form.getFieldValue('atomState') === undefined) {
                form.setFieldValue('atomState', 0)
              }
              form.saveBtnClick()
              resolve()
            })
          )
          break
        }

        default:
          break
      }
    },

    // Excel导入原子知识
    importfromfile(data) {
      const key = Symbol.for()
      const hide = Message.loading({ content: '处理中...', key })

      KmKnowledageService.importAtom(data[0])
        .then((res) => {
          hide()
          const h = this.$createElement
          const reverseArray = res.data.reverse()
          const content = reverseArray.map((item) => {
            return h('p', {}, item)
          })
          Modal.info({
            title: '上传成功',
            content: h('div', {}, content),
          })
          this.$refs.oaTable.refresh()
        })
        .catch((err) => {
          Message.error(err)
        })
      this.modalImport.visible = false
    },

    // 下载原子知识模板
    fnDownloadTemplate() {
      KmKnowledageService.downloadAtomTemplateExcel().then((res) => {
        const url = URL.createObjectURL(res.data)
        const fname = '原子知识模板.xlsx'
        download(url, fname)
      })
    },
  },
}
</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>
