<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <km-worktree
        ref="worktree"
        :data-type="activeKey"
        @treeSelectd="treeSelectd"
        @treeSelectValue="treeSelectValue"
      ></km-worktree>
      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table
            v-if="treeId.draft !== ''"
            ref="draft"
            data-url="api/flow-mobile/v1/user-tasks/draft-with-trustor"
            :columns="columns"
            :actions="actions"
            :row-key="'instId'"
            show-selection
            :search-fields="['title']"
            :filter-expressions="expressions.draft"
            @rowClick="rowClick"
            @dataLoaded="tableDataLoaded"
          >
            <a slot="listTitle" slot-scope="text, record">
              {{ record.title }}
              <a-tooltip>
                <template slot="title">
                  {{ record.groupPath }}
                </template>
                <a-tag v-if="record.srcTrustId" color="blue">兼</a-tag>
              </a-tooltip>
            </a>
          </sd-data-table>
          <sd-oa-table
            v-else
            form-id="kmKnowledge"
            page-id="knowledge/kmAtom/kmAtom"
            :columns="columns2"
            :actions="actions"
            :filter-expressions="atomExpressions"
            show-selection
            :search-fields="['redheadName']"
            @formBtnClick="formBtnClick"
          >
            <template v-slot:form="{ model }">
              <km-atom-table ref="atomTable" :model="model" />
            </template>
          </sd-oa-table>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import { Modal } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import FlowcenterService from '@/flowcenter/flowcenter-service'
import flowcenter from '@/flowcenter/sd-flowcenter-mixins'
import KmWorktree from '../../components/km-knowledge-draftstree'
import KmAtomTable from '../knowledge-base/km-atom-table'
import components from './_import-components/km-knowledge-drafts-import'

const columns = [
  {
    title: '业务类型',
    dataIndex: 'appCat',
    sdCandidate: true,
  },
  {
    title: '标题',
    dataIndex: 'title',
    sdClickable: true,
    scopedSlots: { customRender: 'listTitle' },
  },

  {
    title: '创建时间',
    dataIndex: 'draftDate',
    sdRender: TableColumnTypes.dateTime,
    sorter: true,
  },
]
const columns2 = [
  {
    title: '标题',
    dataIndex: 'title',
    sdClickable: true,
  },
  {
    title: '业务类型',
    dataIndex: 'categoryName',
    scopedSlots: { customRender: 'listTitle' },
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sdRender: TableColumnTypes.dateTime,
    sorter: true,
  },
]
export default {
  name: 'KmKnowledgeDrafts',
  metaInfo: {
    title: '草稿箱',
  },
  components: {
    ...components,
    'km-worktree': KmWorktree,
    'km-atom-table': KmAtomTable,
  },
  mixins: [storeMixin, flowcenter],
  data() {
    return {
      show: false,
      activeKey: 'draft',
      columns,
      columns2,
      expressions: { draft: [] },
      treeId: { draft: '' },
      defaultFilter: {
        draft: { dataType: 'str', name: 'status', op: 'ne', stringValue: '2' },
      },
      actions: [
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
          permission: null,
          callback: (keys) => {
            this.deleteRows(keys)
          },
        },
      ],
    }
  },
  computed: {
    atomExpressions() {
      return [
        {
          dataType: 'str',
          name: 'creatorAccount',
          op: 'eq',
          stringValue: this.userInfo.account,
        },
        {
          dataType: 'int',
          name: 'type',
          op: 'eq',
          intValue: 1,
        },
        {
          dataType: 'int',
          name: 'atomState',
          op: 'eq',
          intValue: 0, // 1：已发布，0：草稿
        },
      ]
    },
  },
  methods: {
    // 保存和发布
    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
      }
    },

    // 删除数据
    deleteRows(selectedRowKeys) {
      Modal.confirm({
        title: '你确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          const params = {
            flowCallbackBeanName: 'formBeanCleanerCallBack',
            processInstanceIds: selectedRowKeys.join(','),
          }
          FlowcenterService.fnDarftsDelete(params).then((res) => {
            if (res.status === 200) {
              this.$refs.draft.clearSelection(true)
              this.refresh()
            }
          })
        },
      })
    },
    treeSelectValue(k, v) {
      if (k.node !== undefined) {
        if (k.node.dataRef.id === '0atom') {
          this.treeId.draft = ''
        }
      }
    },
    knowledageView(record) {
      // window.open(`#/km-knowledage-view?id=${record.id}&title=${record.title}`, '_blank')
    },
  },
}
</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%;
    }
  }
}
.editor {
  margin: 0 auto;
  :global(.ql-editor) {
    min-height: 300px;
    line-height: 1.5;
  }
}
</style>
