<template>
  <div :class="$style.searchdiv">
    <a-spin :spinning="loading" tip="文本审核中，请耐心等待...">
      <a-card :class="$style.searchWrap">
        <a-form-model
          ref="advancedSearchForm"
          class="ant-advanced-search-form"
          :model="form"
          v-bind="formItemLayout"
        >
          <a-row :gutter="24" :class="$style.antformitem">
            <a-col :span="11">
              <a-form-model-item label="签订日期" prop="searchDate">
                <a-range-picker v-model="form.searchDate" />
              </a-form-model-item>
            </a-col>
            <a-col :span="11">
              <a-form-model-item label="合同名称" prop="contractName">
                <a-input v-model="form.contractName"> </a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="11">
              <a-form-model-item label="合同类型" prop="contractType">
                <a-select v-model="form.contractType" :options="contractType" allow-clear>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="11">
              <a-form-model-item label="合作方名称" prop="counterpartName">
                <a-input v-model="form.counterpartName"> </a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="16"> </a-col>
            <a-col :class="$style.searchbutton" :span="8">
              <div class="reportbuttonContent" style="margin-right:15%">
                <a-button type="primary" html-type="submit" @click="submitForm">查询</a-button>
                <a-button type="primary" @click="allAudit">批量审核</a-button>
                <a-button @click="handleReset">重置</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
      <a-card class="reporttablecardxm">
        <div :class="$style.title"
          ><span :class="['toptitle', $style.toptitle]">合同信息</span></div
        >
        <div v-show="!isSubmit" style="height:500px"></div>
        <sd-data-table-ex
          v-show="isSubmit"
          :key="tableKey"
          ref="dataTable"
          show-selection
          :filter-expressions="filterExpressions"
          form-id="iamCubeContract"
          :columns="columns"
          :row-key="(record, index) => index"
          :defultpagination-pagesize="10"
          @dataLoaded="dataLoaded"
        >
          <div slot="islink" slot-scope="text, record">
            <a :title="text" @click="rowClick(record)">{{ text }}</a>
          </div>
        </sd-data-table-ex>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import loginService from '@/login/login-service'
import axios from '@/common/services/axios-instance'
import TableColumnTypes from '@/common/services/table-column-types'
import { sdLocalStorage } from '@/common/services/storage-service'
import { message, Modal } from '@/common/one-ui'
import cubeServices from '@product/iam/cube/cube-services'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import moment from 'moment'
import components from './_import-components/cube-contract-search-import'

export default {
  name: 'CubeContractSearch',
  metaInfo: {
    title: '文本智能审核',
  },
  components: {
    ...components,
  },
  data() {
    return {
      pagination: {
        pageSize: 10,
        total: 100,
      },
      loading: false, // 列表加载中
      tableData: [], // 列表数据
      isSubmit: false, // 是否点了查询
      showTable: false, // 是否显示查询结果
      tableKey: 0,
      contractType: [], // 合同类型
      data: [],
      filterExpressions: [], // 过滤条件
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '签订日期',
          dataIndex: 'signDate',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '合同名称',
          dataIndex: 'contractName',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '合同编号',
          dataIndex: 'contractCode',
        },
        {
          title: '合同金额',
          dataIndex: 'contractAmount',
        },
        {
          title: '合同类型',
          dataIndex: 'contractType',
        },
        {
          title: '合作方名称',
          dataIndex: 'partnerName',
        },
      ],
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 12 },
      },
      dateFormat: 'YYYY',
      form: {
        contractName: '',
        searchDate: [],
        contractType: '',
        counterpartName: '',
      },
      params: {},
    }
  },

  mounted() {
    // 初始化数据字典信息
    this.initDictionaryInfo()
  },
  methods: {
    // 详情打开新页面
    rowClick(record) {
      const url = '/cube-contract-form?record=' + record.id // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.flush()
        }
      })
    },
    fnonloadsum() {
      if (!this.flag) {
        if (document.getElementsByClassName('ant-pagination')) {
          document.getElementsByClassName('ant-pagination')[0].style.display = 'none'
        }
        this.flag = true
      } else {
        if (document.getElementsByClassName('ant-pagination')) {
          document.getElementsByClassName('ant-pagination')[0].style.display = ''
        }
      }
    },
    initDictionaryInfo() {
      // 获取合同类型
      cubeServices.checkCubeToken('review').then((res) => {
        if (!res) {
          Modal.warning({
            title: '提示',
            content: '未开启CUBE集成功能参数或单点认证失败，请联系管理员',
          })
          return false
        }
        const cubeJson = JSON.parse(sdLocalStorage.getItem('cube') || '{}')
        axios({
          url:
            'api/xcoa-mobile/v1/iamcubecontract/findFileCode?accessToken=' + cubeJson.review_token,
        }).then((res) => {
          this.contractType = res.data.map((item) => {
            return {
              value: item.code,
              label: item.text,
            }
          })
        })
      })
    },
    dataLoaded(eventData) {
      this.showTable = true
      return eventData
    },

    submitForm() {
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          this.isSubmit = true
          this.params.startPosition = 0
          this.params.maxResults = 10
          this.filterExpressions = []
          // 合同签订时间
          if (this.form.searchDate.length > 0) {
            this.filterExpressions.push({
              dataType: 'long',
              name: 'signDate',
              op: 'between',
              longValues: [
                moment(moment(this.form.searchDate[0]).startOf('day')).valueOf(),
                moment(moment(this.form.searchDate[1]).endOf('day')).valueOf(),
              ],
            })
          }
          // 合同名称
          if (this.form.contractName !== '') {
            this.filterExpressions.push({
              dataType: 'str',
              name: 'contractName',
              op: 'like',
              stringValue: `%${this.form.contractName}%`,
            })
          }
          // 合同类型
          if (this.form.contractType && this.form.contractType !== '') {
            this.filterExpressions.push({
              dataType: 'str',
              name: 'contractTypeCode',
              op: 'eq',
              stringValue: this.form.contractType,
            })
          }
          // 合同合作方
          if (this.form.counterpartName !== '') {
            this.filterExpressions.push({
              dataType: 'str',
              name: 'partnerName',
              op: 'like',
              stringValue: `%${this.form.counterpartName}%`,
            })
          }

          this.tableKey++
        }
      })
    },
    handleReset() {
      // this.isSubmit = false
      this.$refs.advancedSearchForm.resetFields()
      // 特殊处理，清空字段值
      // this.handlesearch()
    },
    // 批量审核
    allAudit() {
      const ids = this.$refs.dataTable.getSelectedRowKeys()
      if (ids.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择需要智能审核的合同信息',
        })
        return
      }
      this.loading = true
      cubeServices.checkCubeToken('review').then((res) => {
        if (!res) {
          Modal.warning({
            title: '提示',
            content: '未开启CUBE集成功能参数或单点认证失败，请联系管理员',
          })
          return false
        }
        const cubeJson = JSON.parse(sdLocalStorage.getItem('cube') || '{}')
        // 获取本地token
        loginService.updateAccessToken().then(() => {
          axios({
            url: 'api/xcoa-mobile/v1/iamcubeexamine/fineContractReview',
            params: {
              accessToken: 'Bearer ' + cubeJson.review_token,
              ids: this.$refs.dataTable.getSelectedRowKeys().join(','),
              localToken: loginService.getTokens().access_token,
            },
          })
            .then((res) => {
              this.loading = false
              Modal.success({
                title: '提示',
                content: '文本审核完成，点击确认跳转审核结果页面',
                okText: '确认',
                okType: 'primary',
                onOk: () => {
                  const url = '/cube-count-list' // 新页面要打开的路由地址
                  crossWindowWatcher.waitForChanged(url)
                },
              })
            })
            .catch((err) => {
              this.loading = false
              message.error('文本智能审核接口调用失败，请联系管理员')
              console.log(err)
            })
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.title {
  text-align: center;
  .toptitle {
    color: #404040;
    font-weight: bold;
    font-size: 22px;
  }
}

.search-wrap {
  margin-bottom: $padding-lg;
  :global(.ant-advanced-search-form) {
    padding: 0;
    background: transparent;
    border: none;
  }
  :global .ant-divider-horizontal {
    margin: 10px 0;
  }
}
.searchdiv {
  height: 100%;
  background-color: #f0f2f5;
  :global(.sd-has-table.ant-card) {
    min-height: 50%;
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      overflow: auto;
      min-height: auto !important;
    }
  }
  :global(.ant-table-placeholder) {
    height: auto !important;
  }
}
:global(.statistics) {
  :global(.ant-table-wrapper) {
    margin-top: 40px;
  }
}
</style>
