<template>
  <div v-if="relatedDoc">
    <sd-data-table-ex
      ref="dataTable"
      form-id="oaRelatedDoc"
      page-id="doc/relate/oaRelatedDoc"
      :columns="columns"
      :show-selection="!isReadOnly && showselection"
      :actions="isReadOnly ? [] : actions"
      :pagination="{ pageSize: totalSize }"
      :hide-pagination="isPrint"
      :filter-expressions="filterExpressions"
      @tableDataLoaded="tableDataLoaded"
    >
      <a
        v-if="record.readAuth === 1"
        slot="bt"
        slot-scope="text, record"
        rel="opener"
        :href="
          `#/sd-webflow/done-pages/${record.targetInstId}?openAuthType=relatedDoc&openAuthParameter=${record.targetInstId},${relateDocId},${webflow.FlowData.instId}`
        "
        target="_blank"
        >{{ text }}
      </a>
      <span v-else>{{ text }}</span>
    </sd-data-table-ex>
    <!-- 关联文档列表 -->
    <a-modal
      title="关联文档"
      width="900px"
      destroy-on-close
      :visible="relateddocvisible"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <sd-data-table
        ref="dataTable2"
        data-url="api/framework/v1/flow-list/oarelateddoc"
        :columns="columns2"
        :row-key="'instId'"
        :search-fields="['title']"
        show-selection
        @rowClick="rowClick"
      >
      </sd-data-table>
    </a-modal> </div
  ><a-empty v-else />
</template>

<script>
import pageService from '@/common/services/page-service.js'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import { Message } from 'ant-design-vue'
import eventBus from '@/common/services/event-bus'
import components from './_import-components/sd-relate-doc-import'
const columns = [
  {
    title: '标题',
    dataIndex: 'targetTitle',
    scopedSlots: { customRender: 'bt' },
  },

  {
    title: 'targetInstId',
    dataIndex: 'targetInstId',
    sdHidden: true,
  },
  {
    title: 'targetFlowId',
    dataIndex: 'targetFlowId',
    sdHidden: true,
  },
  {
    title: 'instId',
    dataIndex: 'instId',
    sdHidden: true,
  },
  {
    title: 'deleteAuth',
    dataIndex: 'deleteAuth',
    sdHidden: true,
  },
]

const columns2 = [
  {
    title: '标题',
    dataIndex: 'title',
    sdClickable: true,
  },
  {
    title: '业务类型',
    dataIndex: 'appCat',
    width: '150px',
  },
  {
    title: '拟稿人',
    dataIndex: 'creatorName',
    width: '120px',
  },
  {
    title: '拟稿部门',
    dataIndex: 'creatorDept',
    width: '120px',
  },
  {
    title: '创建日期',
    dataIndex: 'startDate',
    sdRender: TableColumnTypes.dateTime,
    width: '170px',
  },
]

export default {
  name: 'SdRelateDoc',
  metaInfo: {
    title: '关联文件',
  },
  components: components,
  props: {
    relatedDoc: {
      type: Object,
      default: function() {
        return this.webflow.FlowData.processFormData.processFormPropertyValues.find(
          (item) => item.dataType === 'relateddoc'
        )
      },
    },
    flowId: {
      type: String,
      default: function() {
        return this.webflow.FlowData.processId
      },
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    // 数据应该直接从属性里取，这先是假的
    return {
      totalSize: 5,
      isPrint: false,
      columns2, // 关联文档列表
      relateddocvisible: false,

      count: 0, // 推荐数量
      showlabel: false,
      visible: false,
      columns: columns.concat([
        {
          title: '阅读权限',
          width: '200px',
          dataIndex: 'readAuth',
          sdRender:
            this.readOnly || this.relatedDoc?.readonly
              ? TableColumnTypes.statusBadge
              : TableColumnTypes.ex.switch,
        },
      ]),
      recomandColumns: columns,
      actions: [
        {
          label: '关联文档',
          id: 'add',
          type: TableActionTypes.primary,
          permission: null,
          callback: () => {
            this.relateddocvisible = true
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: (keys) => {
            const params = {
              ids: keys.join(),
            }
            pageService.delete(params, 'oaRelatedDoc').then((res) => {
              Message.success('删除成功')
              this.$refs.dataTable.refresh(true)
              this.$refs.dataTable.clearSelection()
            })
          },
        },
      ],
    }
  },
  computed: {
    relateDocId() {
      return this.relatedDoc?.value
    },
    isReadOnly() {
      return this.readOnly || this.relatedDoc?.readonly || false
    },
    belongedOrgId() {
      return this.webflow.FlowData.processFormData.processFormPropertyValues.find(
        (item) => item.name === 'belongedOrgId'
      )?.value
    },
    filterExpressions() {
      const expressions = [
        {
          dataType: 'str',
          name: 'uuid',
          op: 'eq',
          stringValue: this.relateDocId,
        },
      ]
      if (this.belongedOrgId) {
        expressions.push({
          dataType: 'long',
          name: 'belongedOrgId',
          op: 'eq',
          longValue: Number(this.belongedOrgId),
        })
      }
      return expressions
    },
  },
  created() {
    eventBus.on('refreshData', () => {
      this.$refs.dataTable.refresh(true)
    })
    this.isPrint = document.body.classList.contains('sd-printing')
  },
  methods: {
    tableDataLoaded(data) {
      if (this.isPrint) this.totalSize = data.total
      this.$emit('update', data.total)
    },
    // 关联文档模态框关闭
    handleCancel() {
      this.relateddocvisible = false
    },
    handleOk() {
      if (this.$refs.dataTable2.getSelectedRows().length) {
        this.$refs.dataTable2.getSelectedRows().forEach((item) => {
          this.save(item)
        })
      } else {
        Message.warning('您未选择任何文档，请至少选择一项！')
      }
    },
    onChange() {},
    save(item) {
      const data = {
        eventId: 'save',
        inputs: [
          {
            name: 'srcFlowId',
            value: this.flowId,
          },
          {
            name: 'targetInstId',
            value: item.instId,
          },
          {
            name: 'targetTitle',
            value: item.title,
          },
          {
            name: 'targetFlowId',
            value: item.flowId,
          },
          {
            name: 'readAuth',
            value: 1,
          },
          {
            name: 'uuid',
            value: this.relateDocId,
          },
        ],
        pageFlowId: 'string',
        pagePath: '/doc/relate/oaRelatedDoc',
      }

      return pageService.save(data).then((res) => {
        this.$refs.dataTable.refresh(true)
        this.handleCancel()
      })
    },
    showselection(record) {
      // 如果返回 deleteAuth===0 说明 没有删除权限
      return record.deleteAuth !== 0
    },
    rowClick(record) {
      window.open(
        `#/sd-webflow/done-pages/${record.instId}?openAuthType=relatedDoc&openAuthParameter=${record.instId},${this.relateDocId},${this.webflow.FlowData.instId}`
      )
    },
  },
  inject: {
    webflow: { default: () => {} },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.theme-color {
  color: $primary-color;
}
.relate {
  margin-top: 10px;
  margin-bottom: 10px;
}
.recommend {
  font-weight: 600;
  a {
    float: right;
    font-weight: normal;
    text-decoration: underline;
  }
}
</style>
