<template>
  <div :class="$style.wrapper">
    <div
      v-if="
        !flowData.processFormData.processFormPropertyValues.find(
          (item) => item.name === 'LAW_CASE_RELATED' || item.name === 'LAW_APPLY_RELATED'
        ).readonly
      "
      :class="$style.header"
    >
      <a-space>
        <a-button
          type="primary"
          @click="
            () => {
              visible = true
            }
          "
          >关联案件</a-button
        >
        <a-button :disabled="selectedRows.length === 0" @click="deleteRelateDoc">删除</a-button>
      </a-space>
    </div>
    <div :class="$style.childTableDiv">
      <sd-data-table
        ref="childDataTable"
        data-url="api/framework/v1/page/businessList"
        :columns="columns"
        :process-res="processRes"
        :process-req="processReq"
        :show-selection="
          !flowData.processFormData.processFormPropertyValues.find(
            (item) => item.name === 'LAW_CASE_RELATED' || item.name === 'LAW_APPLY_RELATED'
          ).readonly
        "
        :selected-datas.sync="selectedRows"
      >
        <div slot="link" slot-scope="text, record">
          <!-- 有阅读权限 -->
          <span v-if="record.READ_ONLY.toString() === '0'">
            <a
              target="_blank"
              rel="opener"
              :href="
                `#/sd-webflow/done-pages/${record.RELATED_INST_ID}?openAuthType=relatedDoc&openAuthParameter=${record.RELATED_INST_ID},${relateDocId},${flowData.instId}`
              "
              >{{ text }}</a
            >
          </span>
          <!-- 无阅读权限 -->
          <span v-else>{{ text }}</span>
        </div>
        <div slot="read" slot-scope="text, record">
          <span
            v-if="
              !flowData.processFormData.processFormPropertyValues.find(
                (item) => item.name === 'LAW_CASE_RELATED' || item.name === 'LAW_APPLY_RELATED'
              ).readonly
            "
          >
            <a-switch
              :checked="record.READ_ONLY.toString() === '0'"
              @click="readChange($event, record)"
          /></span>
          <span v-else>
            <a-badge
              v-if="record.READ_ONLY.toString() === '0'"
              status="success"
              text="启用"
            ></a-badge>
            <a-badge v-else status="error" text="停用"></a-badge>
          </span>
        </div>
      </sd-data-table>
    </div>
    <!-- 选择关联文件列表 -->
    <a-modal
      title="关联案件"
      width="50%"
      destroy-on-close
      :visible="visible"
      :body-style="{
        padding: '0px 20px',
      }"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <!-- 高级搜索 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        ref-name="searchform"
        :search-style="{ height: '135px', top: '105px !important' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item label="案件名称">
              <a-input v-model="formData.CASE_NAME" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="案件编号">
              <a-input v-model="formData.currentNumber" allow-clear />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <!-- 查询列表 -->
      <sd-data-table-ex
        ref="dataTable"
        :filter-expressions="expressions"
        :show-advance-query="true"
        :search-fields="['CASE_NAME', 'currentNumber']"
        data-url="api/framework/v1/page/businessList"
        :columns="modalColumns"
        form-id="onlhead:d0bb8202233c48f0b5148776754461e1"
        show-selection
        @searchbtnClick="searchbtnClick"
      >
        <div slot="link" slot-scope="text, record">
          <a rel="opener" target="_blank" :href="`#/sd-webflow/done-pages/${record.instId}`">{{
            text
          }}</a>
        </div>
      </sd-data-table-ex>
    </a-modal>
  </div>
</template>

<script>
import pageService from '@/common/services/page-service.js'
import { message } from '@/common/one-ui'
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import components from './_import-components/law-case-report-relate-doc-import'

export default {
  name: 'LawCaseReportRelateDoc',
  components: {
    auditAdvancedQuery,
    ...components,
  },
  mixins: [auditAdvancedQueryMixins],
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      },
    },
    fields: {
      type: Array,
      default: () => {
        return []
      },
    },
    flowData: {
      type: Object,
      default: () => {
        return {}
      },
    },
    relatedDoc: {
      type: Object,
      default: function() {
        return this.flowData.processFormData.processFormPropertyValues.find(
          (e) => e.dataType === 'relateddoc'
        )
      },
    },
  },
  data() {
    return {
      expressions: [
        {
          dataType: 'int',
          name: 'FLOW_STATUS',
          op: 'eq',
          intValue: 5,
        },
      ],
      formData: {
        CASE_NAME: '',
        currentNumber: '',
      },
      selectedRows: [], // 列表选中内容
      visible: false, // 是否显示选择列表
      columns: [
        {
          title: '标题',
          dataIndex: 'CASE_NAME',
          scopedSlots: { customRender: 'link' },
        },
        {
          title: '阅读权限',
          width: '200px',
          dataIndex: 'READ_ONLY',
          scopedSlots: { customRender: 'read' },
        },
        { title: '案件ID', dataIndex: 'RELATED_CASE_ID', sdCandidate: true, sdHidden: true },
      ],
      modalColumns: [
        {
          title: '案件名称',
          sorter: true,
          dataIndex: 'CASE_NAME',
          scopedSlots: { customRender: 'link' },
        },
        { title: '案件类型', sorter: true, dataIndex: 'CASE_TYPE' },
        { title: '案件编号', sorter: true, dataIndex: 'currentNumber' },
      ],
    }
  },
  computed: {
    relateDocId() {
      return this.relatedDoc?.value
    },
  },
  metaInfo: {
    title: '关联案件',
  },
  methods: {
    emitValue(val) {
      val.forEach((e) => {
        e.id = e.id || 'fakeId_' + Math.random()
      })
      this.$emit('update:related', val)
      this.$refs.childDataTable.refresh(false)
    },
    // 删除关联文件
    deleteRelateDoc() {
      const selectId = this.selectedRows.map((item) => item.id)
      // 删除关联文件
      this.delete(this.selectedRows.map((item) => item.RELATED_ID))
      this.selectedRows = []
      this.emitValue(this.value.filter((t) => !selectId.includes(t.id)))
    },
    readChange() {
      if (!arguments[0]) {
        arguments[1].READ_ONLY = 1
      } else {
        arguments[1].READ_ONLY = 0
      }
    },
    processReq(req) {
      req.data.formId = 'onlhead:d0bb8202233c48f0b5148776754461e1'
      return req
    },
    processRes(res) {
      res.data = this.value
      res.totalSize = this.value.length
      return res
    },
    handleCancel() {
      this.visible = false
    },
    handleOk() {
      if (this.$refs.dataTable.getSelectedRows().length) {
        const relateData = this.value || []
        let resData =
          relateData.length === 0
            ? this.$refs.dataTable.getSelectedRows()
            : this.$refs.dataTable.getSelectedRows().filter((item) => {
                return (
                  relateData.filter((doc) => {
                    return doc.RELATED_CASE_ID === item.id
                  }).length === 0
                )
              })
        // 选择过的文件不做处理
        resData = resData.map((item) => {
          return {
            RELATED_CASE_ID: item.id,
            CASE_NAME: item.CASE_NAME,
            CASE_TYPE: item.CASE_TYPE,
            RELATED_INST_ID: item.instId,
            READ_ONLY: 0,
          }
        })
        const allPromist = []
        resData.forEach((item) => {
          allPromist.push(this.save(item))
        })
        Promise.all(allPromist).then((res) => {
          // 根据返回值记录关联文档ID
          resData.forEach((item, index) => {
            item.RELATED_ID = res[index].data.pageFormData.beanId
          })
          const endData = relateData.concat(resData)
          this.emitValue(endData)
          this.handleCancel()
        })
      } else {
        message.warning('您未选择任何文档，请至少选择一项！')
      }
    },
    save(e) {
      const t = {
        eventId: 'save',
        inputs: [
          { name: 'srcFlowId', value: this.flowData.processId },
          { name: 'targetInstId', value: e.RELATED_INST_ID },
          { name: 'targetTitle', value: e.CASE_NAME },
          { name: 'targetFlowId', value: e.flowId ? '' : '' },
          { name: 'readAuth', value: 1 },
          { name: 'uuid', value: this.relateDocId },
        ],
        pageFlowId: 'string',
        pagePath: '/doc/relate/oaRelatedDoc',
      }
      return pageService.save(t)
    },
    delete(e) {
      const t = { ids: e.join() }
      pageService.delete(t, 'oaRelatedDoc').then((e) => {
        message.success('删除成功')
      })
    },

    // 查询
    handleSearch() {
      this.expressions = []
      this.expressions.push({
        dataType: 'int',
        name: 'FLOW_STATUS',
        op: 'eq',
        intValue: 5,
      })
      // 案件名称
      if (this.formData.CASE_NAME) {
        this.expressions.push({
          dataType: 'str',
          name: 'CASE_NAME',
          op: 'like',
          stringValue: `%${this.formData.CASE_NAME}%`,
        })
      }

      // 案件编号
      if (this.formData.currentNumber) {
        this.expressions.push({
          dataType: 'str',
          name: 'currentNumber',
          op: 'like',
          stringValue: `%${this.formData.currentNumber}%`,
        })
      }
    },
    resetForm() {
      this.formData = {
        CASE_NAME: '',
        currentNumber: '',
      }
      this.expressions = [
        {
          dataType: 'int',
          name: 'FLOW_STATUS',
          op: 'eq',
          intValue: 5,
        },
      ]
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.header {
  background: #fff;
  padding: 20px 20px 0px 20px;
  text-align: right;
}
.wrapper {
  table {
    th:nth-child(4) {
      display: none;
    }
    td:nth-child(4) {
      display: none;
    }
  }
  background: #fff;
  :global(.ant-table-tbody) {
    .clickable-cell {
      color: $primary-color;
      cursor: pointer;
      &:hover {
        color: $primary-5;
      }
      &:active {
        color: $primary-7;
      }
    }
  }
  .child-table-div {
    background: #fff;
    padding: 0 20px;
  }
  :global .caption_sd-child-table_common {
    display: none;
  }
}
</style>
