<template>
  <audit-form-top-banner :form-data="'readonly'">
    <a-card :class="$style.conditions">
      <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="8">
            <a-form-model-item :label="'整改状态'" prop="reformStatus">
              <a-select v-model="form.reformStatus" placeholder="请选择整改状态" allow-clear>
                <a-select-option value="0">期限内已整改</a-select-option>
                <a-select-option value="1">逾期已整改</a-select-option>
                <a-select-option value="2">期限内未整改完成</a-select-option>
                <a-select-option value="3">逾期未整改完成</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item :label="'审核状态'" prop="endType">
              <a-select v-model="form.endType" placeholder="请选择审核状态" allow-clear>
                <a-select-option value="2">未提交审核</a-select-option>
                <a-select-option value="1">待整改</a-select-option>
                <a-select-option value="5">审核通过</a-select-option>
                <a-select-option value="0">审核驳回</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="整改截止时间" prop="timeRange">
              <a-range-picker
                v-model="reformDeadline"
                :format="'YYYY-MM-DD'"
                @change="changeReformDeadline"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="问题推送时间" prop="timeRange">
              <a-range-picker v-model="pushDate" :format="'YYYY-MM-DD'" @change="changePushDate" />
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <div :class="$style.buttonContent">
              <a-button type="primary" @click="handleAction('serach')">查询</a-button>
              <a-button @click="handleReset">重置</a-button>
              <!-- 导出 -->
              <a-button @click="exportExcel">导出</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <div>
      <a-card>
        <sd-data-table-ex
          ref="SJMXDataTable"
          :key="dataKey"
          :columns="columns"
          :process-req="processReq"
          form-id="iamModelMaintain"
          :scroll="{ x: 2800 }"
          data-url="api/xcoa-mobile/v1/iamquestionreform/iamQuestionReformListNew"
          :filter-expressions="expressions"
          show-selection
        >
          <div slot="questionFlag" slot-scope="text, record">
            <span>{{
              record.questionFlag === null ? '' : record.questionFlag === 0 ? '否' : '是'
            }}</span>
          </div>
          <div slot="reformStatus" slot-scope="text, record">
            <span v-if="record.reformStatus === 0" title="期限内已整改">期限内已整改</span>
            <span v-if="record.reformStatus === 1" title="逾期已整改">逾期已整改</span>
            <span v-if="record.reformStatus === 2" title="期限内未整改完成">期限内未整改完成</span>
            <span v-if="record.reformStatus === 3" title="逾期未整改完成">逾期未整改完成</span>
          </div>
          <div slot="endType" slot-scope="text, record">
            <span v-if="record.endType === null" title="未提交审核">未提交审核</span>
            <span v-if="record.endType === 1" title="待整改">待整改</span>
            <span v-if="record.endType === 5" title="审核通过">审核通过</span>
            <span v-if="record.endType === 0" title="审核驳回">审核驳回</span>
          </div>
          <div slot="action" slot-scope="text, record">
            <!-- 如果 -->
            <a-button type="link" @click="showModal(record)">详情</a-button>
            <a-button type="link" @click="exportClick(record)">下载</a-button>
            <a-button type="link" @click="askClick(record)">整改要求</a-button>
          </div>
        </sd-data-table-ex>
      </a-card>
      <a-modal v-model="visible" title="问题详情" :footer="null" width="1200px" @cancel="cancel">
        <div :class="$style.modelDetail">
          <span>模型编码：{{ modelDetail.batchCode }}</span>
          <span>模型名称：{{ modelDetail.batchName }}</span>
          <span>业务领域：{{ modelDetail.modelDomainName }}</span>
        </div>
        <div :class="$style.detail">
          <a-table
            :columns="columnsDetail"
            :data-source="dataDetail"
            :row-key="(_, index) => index"
            :scroll="{ x: 1150, y: 500 }"
          >
          </a-table>
        </div>
      </a-modal>

      <a-modal
        v-model="askvisible"
        class="ant-advanced-search-form"
        title="整改要求"
        :footer="null"
        width="700px"
        @ok="askFormhandleOk"
        @cancel="askFormCancel"
      >
        <a-form-model ref="askForm" :model="askForm" v-bind="formItemLayout">
          <a-form-model-item prop="reformAsk" label="整改要求说明">
            <a-input
              v-model="askForm.reformAsk"
              placeholder="暂无整改要求说明"
              read-only
              :auto-size="{ minRows: 5, maxRows: 5 }"
              type="textarea"
            />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>
  </audit-form-top-banner>
</template>

<script>
import components from './_import-components/audit-view-change-import'
import { message, Modal } from 'ant-design-vue'
import AuditRiskbraryService from './riskLibrary'
import moment from 'moment/moment'
import storeMixin, { getUserInfo } from '@/common/store-mixin'
import download from '@/common/services/download'
import sdDataTableEx from '@/common/components/sd-data-table-ex.vue'
import auditFormTopBanner from './audit-top-banner'
export default {
  name: 'AuditViewChange',
  metaInfo: {
    title: '审计问题明细-整改类',
  },
  components: {
    ...components,
    sdDataTableEx,
    auditFormTopBanner,
  },
  mixins: [storeMixin],
  data() {
    return {
      exportExpressions: [],
      modelDetail: {},
      // 问题标签
      isDescStatus: false,
      mainSendPersonal: [],
      visible: false,
      visibleDecide: false,
      visibleRectification: false,
      askvisible: false,
      exportLoading: false,
      dataKey: 0,
      ModalquestionDetail: '',
      form: {
        reformStatus: null,
        endType: null,
      },
      reformDeadline: [],
      pushDate: [],
      DecideForm: {
        questionFlag: null,
        nonQuestionTag: null,
        nonQuestionDesc: null,
        nonQuestionTagId: null,
        problemStatementId: null,
        // ids: [],
      },
      lockId: '',
      attachments: [],
      fileList: [],
      infoProperties: {},
      RectificationForm: {
        reformDesc: undefined,
        attachment: undefined,
        id: '',
        fileName: '',
      },
      askForm: {
        reformAsk: undefined,
        id: '',
      },
      nonQuestionList: [],
      reqData: {
        reformDeadlineSt: '',
        reformDeadlineEd: '',
        pushDateSt: '',
        pushDateEd: '',
      },
      queryData: {},
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      // 详情信息
      columnsDetail: [],
      dataDetail: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },

        {
          title: '模型编码',
          dataIndex: 'batchCode',
        },
        {
          title: '模型名称',
          dataIndex: 'batchName',
        },
        {
          title: '业务领域',
          dataIndex: 'modelDomainName',
        },
        {
          title: '业务阶段',
          dataIndex: 'modelPhaseName',
        },
        // 模型编码 模型名称

        {
          title: '风险描述',
          dataIndex: 'risk',
        },
        {
          title: '问题推送日期',
          dataIndex: 'pushDate',
        },
        {
          title: '整改截止日期',
          dataIndex: 'reformDeadline',
        },
        {
          title: '整改期限',
          dataIndex: 'reformTime',
        },
        {
          title: '判定问题',
          dataIndex: 'questionFlag',
          scopedSlots: { customRender: 'questionFlag' },
        },
        {
          title: '非问题标签',
          dataIndex: 'nonQuestionTag',
        },
        {
          title: '非问题说明',
          dataIndex: 'nonQuestionDesc',
        },
        {
          title: '提交说明',
          dataIndex: 'reformDesc',
        },
        {
          dataIndex: 'fileName',
          sdHidden: true,
        },
        // {
        //   title: '提交人',
        //   dataIndex: 'viewAccount',
        // },
        {
          title: '整改人',
          dataIndex: 'reformUserAccount',
        },
        {
          title: '整改状态',
          dataIndex: 'reformStatus',
          scopedSlots: { customRender: 'reformStatus' },
        },
        {
          title: '审核状态',
          dataIndex: 'endType',
          scopedSlots: { customRender: 'endType' },
        },
        {
          title: '审核说明',
          dataIndex: 'examineDesc',
        },
        {
          title: '初审人',
          dataIndex: 'checker',
        },
        {
          title: '初审时间',
          dataIndex: 'checkDate',
        },
        {
          title: '复审人',
          dataIndex: 'reviewer',
        },
        {
          title: '复审时间',
          dataIndex: 'reviewDate',
        },
        {
          title: '问题性质',
          dataIndex: 'questionNature',
        },
        // reformUserAccount

        // modelId,  detailGroupId,隐藏
        { title: '模型ID', dataIndex: 'modelId', sdHidden: true },
        { title: '明细组ID', dataIndex: 'detailGroupId', sdHidden: true },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'modelType',
          op: 'eq',
          stringValue: '1',
        },
      ],
      startFlowList: {},
      detailList: [],
    }
  },

  created() {
    this.initColumns()
    this.initQueryData()
  },
  methods: {
    //
    // 初始化initQueryData
    initQueryData() {
      this.queryData = this.$route.query
      // 解码URL
      this.queryData.modelType = '1'
    },
    // 导出
    exportExcel() {
      // 判断选中的数据，至少选中一条数据
      const selectedRows = this.$refs.SJMXDataTable.getSelectedRows()
      if (selectedRows.length === 0) {
        message.warning('请至少选择一条数据')
        return
      }
      // 调用导出
      // 导出参数
      const params = selectedRows.map((item) => {
        return {
          modelId: item.modelId,
          detailGroupId: item.detailGroupId,
          businessCode: item.businessCode,
          jmEventType: item.jmEventType,
          eventTagName: item.eventTagName,
          modelTypeName: item.modelTypeName,
          pushDate: item.pushDate,
          unitCode: item.unitCode,
          modelType: item.modelType,
          bussKey: item.bussKey || null,
        }
      })
      // exportQuestionDetail
      AuditRiskbraryService.exportQuestionDetail(params).then((res) => {
        if (res.status === 200) {
          const url = URL.createObjectURL(res.data)
          const filename = res.headers['content-disposition']
          const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
          download(url, decodeURI(fname))
          message.success('导出成功')
        } else {
          Modal.warning({
            title: '提示',
            content: '导出报错，请联系管理员!',
          })
          return false
        }
      })
    },
    // 时间变化
    changeReformDeadline(val) {
      this.reqData.reformDeadlineSt = moment(val[0]._d).format('YYYY-MM-DD')
      this.reqData.reformDeadlineEd = moment(val[1]._d).format('YYYY-MM-DD')
    },
    changePushDate(val) {
      this.reqData.pushDateSt = moment(val[0]._d).format('YYYY-MM-DD')
      this.reqData.pushDateEd = moment(val[1]._d).format('YYYY-MM-DD')
    },

    ifSaveShow(record) {
      const userInfo = getUserInfo()
      const userAccount = record.reformUserAccount.split(',')
      // // account是否是整改人userInfo.account
      return userAccount.includes(userInfo.account)
    },
    initColumns() {
      // resp_person
      const userInfo = getUserInfo()
      // account
      const roles = this.$store.state.sd.common.userInfo.default.roles
      const isExport = roles.map((val) => val.code).includes('G-1_RESPONSIBLE_PERSON')

      if (isExport) {
        this.columns.push({
          title: '责任人',
          dataIndex: 'respPerson',
        })
      }
      this.columns.push({
        title: '操作',
        dataIndex: 'sharedSetting',
        fixed: 'right',
        width: '300px',
        scopedSlots: { customRender: 'action' },
      })
    },

    processReq(req) {
      req.data.expressions = [
        { dataType: 'str', name: 'reformStatus', op: 'eq', stringValue: this.form.reformStatus },
        { dataType: 'str', name: 'endType', op: 'eq', stringValue: this.form.endType },
        {
          dataType: 'str',
          name: 'reformDeadlineSt',
          op: 'eq',
          stringValue: this.reqData.reformDeadlineSt,
        },
        {
          dataType: 'str',
          name: 'reformDeadlineEd',
          op: 'eq',
          stringValue: this.reqData.reformDeadlineEd,
        },
        { dataType: 'str', name: 'pushDateSt', op: 'eq', stringValue: this.reqData.pushDateSt },
        { dataType: 'str', name: 'pushDateEd', op: 'eq', stringValue: this.reqData.pushDateEd },
      ]
      Object.keys(this.queryData).map((key) => {
        req.data.expressions.push({
          dataType: 'str',
          name: key,
          op: 'eq',
          stringValue: this.queryData[key],
        })
      })
      // 过滤没有stringvalue的对象
      req.data.expressions = req.data.expressions.filter(
        (item) => item?.stringValue !== undefined || item.stringValue === ''
      )
      return req
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
      this.reqData = {
        reformDeadlineSt: '',
        reformDeadlineEd: '',
        pushDateSt: '',
        pushDateEd: '',
      }
      this.reformDeadline = []
      this.pushDate = []
      this.handleSearch()
    },
    // 查询
    handleAction(type) {
      switch (type) {
        case 'serach':
          this.handleSearch()
          break
      }
    },
    handleSearch() {
      this.dataKey++
    },

    // 下载
    exportClick(row) {
      if (!row.attachment) {
        message.warning('未上传附件无法下载')
        return
      }
      const attachmentList = row.attachment.split(',')
      const fileNameList = row.fileName.split(',')
      for (let i = 0; i < attachmentList.length; i++) {
        const spliceIndex = attachmentList[i].lastIndexOf('|')
        const destStep = attachmentList[i].substring(spliceIndex + 1, attachmentList[i].length)
        download(
          'api/framework/v1/task-form-process/download-attachments/' + destStep,
          fileNameList[i]
        )
      }
    },

    // 整改说明点击弹框
    askClick(row) {
      this.askvisible = true
      this.askForm.id = row.id
      this.askForm.reformAsk = row.reformAsk
    },
    // 整改说明提交
    askFormhandleOk() {
      const param = {
        reformDesc: this.askForm.reformAsk,
        id: this.askForm.id,
      }
      AuditRiskbraryService.saveIamQuestionReform(param).then((res) => {
        if (res) {
          message.success('提交成功')
          this.$refs.askForm.resetFields()
          this.askvisible = false
          this.handleSearch()
        }
      })
    },
    // 整改说明关闭
    askFormCancel() {
      this.$refs.askForm.resetFields()
      this.askvisible = false
    },
    changep(values) {
      const arr = values.map((item) => {
        return {
          attrs: { we_expanded: 'false', we_selected: 'false' },
          checkable: true,
          code: item.code,
          key: item.code,
          name: item.name,
          title: item.name,
          type: item.type,
        }
      })
      const spliceIndex = this.startFlowList.actionId.indexOf('.')
      const destStep = this.startFlowList.actionId.substring(0, spliceIndex) + '.2'
      this.startFlowList.participantInfos.push({ destStepId: destStep, participants: arr })
      AuditRiskbraryService.startDispatch(this.startFlowList).then((res) => {
        if (res.data.flowInstanceResult.length) {
          message.success('提交成功')
          this.RectificationForm.reformDesc = undefined
          this.RectificationForm.attachment = undefined
          this.RectificationForm.id = ''
          this.RectificationForm.fileName = ''
          this.fileList = []
          this.visibleRectification = false
          this.handleSearch()
        }
      })
    },
    showModal(row) {
      // this.ModalquestionDetail = JSON.parse(row.questionDetail)
      const params = {
        modelId: row.modelId,
        detailGroupId: row.detailGroupId,
        ...this.queryData,
        bussKey: row.bussKey || null,
      }
      const formData = new FormData()
      Object.keys(params).forEach((key) => {
        formData.append(key, params[key])
      })
      this.modelDetail = {
        modelDomainName: row.modelDomainName,
        batchName: row.batchName,
        batchCode: row.batchCode,
        riskData: row.risk,
      }
      const detailJson = JSON.stringify(this.modelDetail)
      const queryJson = JSON.stringify(params)

      window.open(
        `#/audit-risk-detail?queryJson=${queryJson}&modelDetail=${detailJson}&detailStatus=${this.detailStatus}`
      )
    },
    cancel() {
      this.visible = false
      this.dataDetail = []
      this.columnsDetail = []
      this.modelDetail = {}
    },
  },
}
</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%;
    }
  }
}
.button-content {
  button {
    margin: 0 4px;
  }
}
.no-action {
  padding: 0 15px;
  color: $text-color-secondary;
}
.detail {
  width: 100%;
  overflow-x: auto;
}
.model-detail {
  display: flex;
  margin-bottom: 10px;

  span {
    margin-right: 20px;
  }
}
</style>
