<template>
  <audit-form-top-banner :form-data="'readonly'">
    <a-spin :spinning="isshowLoading" tip="正在导出请稍等……" size="large">
      <a-card :class="$style.conditions">
        <a-form-model
          ref="advancedSearchForm"
          class="ant-advanced-search-form"
          :model="form"
          v-bind="formItemLayout"
          :layout="'inline'"
        >
          <div :class="$style.buttonContent">
            <a-button type="primary" :loading="exportLoading" @click="DecideClick"
              >判定问题</a-button
            >
            <a-button @click="exportExcel">导出</a-button>
          </div>
        </a-form-model>
      </a-card>
      <div>
        <a-card>
          <sd-data-table
            ref="SJMXDataTable"
            :key="dataKey"
            :row-key="(record, index) => index"
            :columns="columns"
            :process-req="processReq"
            form-id="iamModelMaintain"
            :scroll="{ x: '100%' }"
            :data-url="dataUrl"
            :hide-pagination="true"
          >
            <div slot="questionFlag" slot-scope="text, record">
              <span v-if="record.questionFlag === 0">否</span>
              <span v-if="record.questionFlag === 1">是</span>
              <span v-else></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="action" slot-scope="text, record">
              <!-- 如果 -->
              <a-button type="link" @click="showModal(record)">详情</a-button>
              <a-button
                type="link"
                @click="
                  () => {
                    modelLogicContent = record.configIdea
                    modelLogicVisible = true
                  }
                "
                >模型逻辑</a-button
              >
              <!-- :disabled="record.questionFlag === 0" -->
              <a-button type="link" @click="exportClick(record)">下载</a-button>
              <a-button
                v-if="ifSaveShow(record)"
                type="link"
                :disabled="record.endType === 1 || record.endType === 5"
                @click="openTJSH(record)"
                >提交</a-button
              >
              <a-button type="link" @click="askClick(record)">整改要求</a-button>
            </div>
          </sd-data-table>
        </a-card>

        <a-modal
          v-model="visibleDecide"
          class="ant-advanced-search-form"
          title="问题判定"
          width="700px"
          @ok="DecideFormhandleOk"
          @cancel="DecideFormhandleCancel"
        >
          <a-form-model
            ref="DecideForm"
            :model="DecideForm"
            v-bind="formItemLayout"
            :rules="{
              nonQuestionDesc: [{ required: true, message: '请填写问题说明', trigger: 'blur' }],
            }"
          >
            <a-form-model-item label="问题判定" prop="questionFlag">
              <a-select
                v-model="DecideForm.questionFlag"
                placeholder="请选择问题判定"
                @change="decFormChange"
              >
                <a-select-option :value="1">是</a-select-option>
                <a-select-option :value="0">否</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-if="DecideForm.questionFlag !== 1"
              prop="nonQuestionTag"
              label="问题标签"
            >
              <a-select
                v-model="DecideForm.problemStatementId"
                placeholder="请选择问题标签"
                @change="questionChange"
              >
                <a-select-option
                  v-for="(item, index) in nonQuestionList"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-if="DecideForm.questionFlag !== 1"
              prop="nonQuestionDesc"
              label="问题说明"
            >
              <a-input
                v-model="DecideForm.nonQuestionDesc"
                placeholder="请填写问题说明"
                :auto-size="{ minRows: 5, maxRows: 5 }"
                type="textarea"
                :disabled="isDescStatus"
              />
            </a-form-model-item>
          </a-form-model>
        </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-model-logic v-model="modelLogicVisible" :content="modelLogicContent" />
    </a-spin>
  </audit-form-top-banner>
</template>

<script>
import components from './_import-components/audit-summarry-list-import'
import axios from '@/common/services/axios-instance'
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 sdDataTable from '@/common/components/sd-data-table.vue'
import auditFormTopBanner from './audit-top-banner'
import auditModelLogic from './audit-model-logic'
import { sdSessionStorage } from '@/common/services/storage-service'

export default {
  name: 'AuditSummarryRectificationList',
  metaInfo: {
    title: '审计问题明细-整改类',
  },
  components: {
    ...components,
    auditModelLogic,
    sdDataTable,
    auditFormTopBanner,
  },
  mixins: [storeMixin],
  data() {
    return {
      dataUrl: 'api/xcoa-mobile/v1/iamquestionreform/iamQuestionReformSummary',
      modelLogicVisible: false,
      modelLogicContent: '',
      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: '风险描述',
          width: '100px',
          dataIndex: 'risk',
        },
        {
          title: '判定问题',
          width: '100px',
          dataIndex: 'questionFlag',
          scopedSlots: { customRender: 'questionFlag' },
        },
        {
          title: '非问题标签',
          width: '100px',
          dataIndex: 'nonQuestionTag',
        },
        {
          title: '非问题说明',
          width: '100px',
          dataIndex: 'nonQuestionDesc',
        },
        {
          title: '提交说明',
          width: '100px',
          dataIndex: 'reformDesc',
        },
        {
          dataIndex: 'fileName',
          sdHidden: true,
        },
        {
          width: '100px',
          title: '提交人',
          dataIndex: 'reformUserAccount',
        },

        {
          title: '初审人',
          width: '100px',
          dataIndex: 'checker',
        },
        {
          width: '100px',
          title: '初审时间',
          dataIndex: 'checkDate',
        },
        {
          title: '复审人',
          width: '100px',
          dataIndex: 'reviewer',
        },
        {
          title: '复审时间',
          width: '100px',
          dataIndex: 'reviewDate',
        },
        {
          title: '问题性质',
          width: '240px',
          dataIndex: 'questionNature',
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'modelType',
          op: 'eq',
          stringValue: '1',
        },
      ],
      startFlowList: {},
      detailList: [],
      isshowLoading: false,
    }
  },

  created() {
    this.initColumns()
    this.initQueryData()
  },
  methods: {
    //
    // 初始化initQueryData
    initQueryData() {
      this.queryData = this.$route.query
      this.queryData.modelType = '1'
    },
    // 导出
    exportExcel() {
      this.isshowLoading = true
      const data = this.$refs.SJMXDataTable.data[0]
      const params = [
        {
          modelId: data.modelId,
          detailGroupId: data.detailGroupId,
          unitCode: data.unitCode,
          bussKey: data.bussKey || null,
          businessCode: data.businessCode,
          jmEventType: data.jmEventType,
          pushDate: data.pushDate,
        },
      ]
      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
          }
        })
        .finally(() => {
          this.isshowLoading = false
        })
    },

    ifSaveShow(record) {
      return record.reformAuth === 1 || record.reformAuth === '1'
    },

    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' },
      })
    },
    decFormChange(val) {
      // 如果是是 则清空 问题标签和问题说明
      if (val === 1) {
        this.DecideForm.nonQuestionTag = null
        this.DecideForm.nonQuestionDesc = null
        this.DecideForm.nonQuestionTagId = null
      }
    },
    // 问题标签数据变化
    questionChange(val) {
      // 如果问题标签说明为空，则清空问题说明比需要填写
      // 如果不为空，则填入问题说明详情，并且不允许修改
      const onDesc = this.nonQuestionList.find((item) => item.id === val)
      const { description, name } = onDesc
      this.DecideForm.nonQuestionDesc = description
      this.DecideForm.nonQuestionTag = name
      // 如果详情为空或者null则 isDescStatus ==false
      if (description === '' || description === null) {
        this.isDescStatus = false
      } else {
        this.isDescStatus = true
      }
    },
    processReq(req) {
      // 获取缓存数据
      const cacheData = sdSessionStorage.getItem('riskDetail')
      req.data.maxResults = this.$route.query.maxResults * 1 || 10
      req.data.startPosition = this.$route.query.startPosition * 1 || 0
      req.data.expressions = [
        { dataType: 'str', name: 'id', op: 'eq', stringValue: this.$route.query.recordId },
        ...JSON.parse(cacheData),
      ]
      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++
    },
    // 判断点击
    DecideClick() {
      const selectedRows = this.$refs.SJMXDataTable.data
      if (selectedRows[0].endType === 1 || selectedRows[0].endType === 5) {
        message.warning('该模型跑批数据已提交整改')
        return
      }
      this.visibleDecide = true
      axios({ url: 'api/xcoa-mobile/v1/problem-statement/all', method: 'get' }).then((res) => {
        res.data.length ? (this.nonQuestionList = res.data) : (this.nonQuestionList = [])
      })
    },
    // 判断提交
    DecideFormhandleOk() {
      // 获取选中列 modelId detailGroupId
      this.$refs.DecideForm.validate((valid) => {
        if (valid) {
          const data = this.$refs.SJMXDataTable.data[0]
          const params = {
            detailGroupId: data.detailGroupId,
            modelId: data.modelId,
            unitCode: data.unitCode,
            bussKey: data.bussKey || null,
            pushDate: data.pushDate,
            businessCode: data.businessCode,
            questionFlag: this.DecideForm.questionFlag,
            nonQuestionTag: this.DecideForm.nonQuestionTag,
            nonQuestionDesc: this.DecideForm.nonQuestionDesc,
            nonQuestionTagId: this.DecideForm.problemStatementId,
          }

          AuditRiskbraryService.batchDecide(params).then((res) => {
            if (res) {
              message.success('提交成功')
              this.DecideFormhandleCancel()
              this.handleSearch()
              this.$refs.SJMXDataTable.refresh()
              // this.$refs.DecideForm.resetFields()
            }
          })
        }
      })
    },
    // 判断取消
    DecideFormhandleCancel() {
      this.$refs.DecideForm.resetFields()
      this.visibleDecide = false
      this.DecideForm = {
        questionFlag: null,
        nonQuestionTag: null,
        nonQuestionDesc: null,
        nonQuestionTagId: null,
        problemStatementId: null,
        // ids: [],
      }
    },
    // 附件自定义上传
    customRequest(data, catnum = 0, item) {
      if (data.file.size === 0) {
        message.warn(`不能上传大小为0的文件`)
        return
      }
      const file = {
        FileName: data.file.name,
        Completed: 0,
        CatNum: catnum,
      }
      this.RectificationForm.fileName = data.file.name
      if (catnum === -1) {
        this.attachments.unshift(file)
      } else {
        this.attachments.push(file)
      }
      this.attachments = [...this.attachments]
      const strTime = moment().format('YYYY-MM-DD HH:mm:ss')
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('FileName', data.file.name)
      formData.append('lockId', this.lockId)
      formData.append('groupId', this.groupId)
      Object.keys(this.infoProperties).forEach((key) => {
        formData.append(key, this.infoProperties[key])
      })

      formData.append(
        'querystring',
        `<file_unid></file_unid><file_name>${data.file.name}</file_name><file_size>${data.file.size}</file_size><completed>1</completed><file_create>${strTime}</file_create><file_update>${strTime}</file_update><file_editmodel>0</file_editmodel><file_lockuser>0</file_lockuser><CreateInfo>${this.userInfo.account} ${strTime}</CreateInfo><filetype></filetype><user_name>${this.userInfo.account}</user_name><UpdateInfo>${this.userInfo.account}于${strTime}创建.</UpdateInfo><TaodaInfo></TaodaInfo><CatNum>${catnum}</CatNum><Ext></Ext>`
      )
      const url = 'api/xcoa-mobile/v1/iam-attachment-extend/attachments-upload/indi'
      axios
        .post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        .then((_) => {
          if (_.data.startsWith('false')) {
            message.error(`${data.file.name} 上传失败`)
          } else {
            data.onSuccess(_, data.file)
          }
        })
        .catch((e) => {
          throw e
        })
    },
    // 跳转提交流程
    openTJSH(data) {
      //  判断问题是否有值
      if (data.questionFlag === null) {
        message.warning('请对此风险数据判定是否是问题')
        return
      }
      const query = {
        // batchCode: data.batchCode,
        // batchName: data.batchName,
        risk: data.risk,
        businessCode: data.businessCode,
        eventTagName: data.eventTagName,
        modelTypeName: data.modelTypeName,
        batchName: data.modelName,
        batchCode: data.modelCode,
        detailGroupId: data.detailGroupId,
        modelId: data.modelId,
        unitCode: data.unitCode,
        pushDate: data.pushDate,
        jmEventType: data.jmEventType,
        bussKey: data.bussKey || null,
        // 非问题
        nonQuestionTag: data.nonQuestionTag,
        nonQuestionDesc: data.nonQuestionDesc,
      }
      const queryUrl = Object.keys(query)
        .map((key) => {
          return key + '=' + query[key]
        })
        .join('&')
      const url = '#/sd-flow-guide?code=PRODUCT_IAM_FXSJ&' + queryUrl
      window.open(url)
    },
    // 附件上传
    handleChange(info) {
      const status = info.file.status
      let fileList = [...info.fileList]
      fileList = fileList.slice(-1)
      fileList = fileList.map((file) => {
        if (file.response) {
          file.url = file.response.data
        }
        return file
      })
      this.fileList = fileList
      if (status === 'done') {
        message.success(`${info.file.name} 上传成功.`)
      } else if (status === 'error') {
        message.error(`${info.file.name} 上传失败.`)
      }
    },
    // 下载
    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]
        )
      }
    },
    // 提交点击
    rectificationClick(row) {
      this.visibleRectification = true
      this.RectificationForm.id = row.id
      AuditRiskbraryService.startProcessPages({
        extParams: [{ name: 'code', value: 'PRODUCT_IAM_FXSJ' }],
        businessTypeId: 200362,
      }).then((res) => {
        this.startFlowList = {
          actionId: this.findActionId(res.data.pushButtons), // start已有获取
          activeStepId: res.data.activeStepId, // start已有获取
          auditElement: [],
          flowCallbackBeanName: 'subflowDataBinderCallback',
          flowFormModelRelationId: res.data.flowFormModelRelationId, // start已有获取
          flowId: res.data.processId, // start已有获取
          formId: res.data.processFormData.formId, // start已有获取
          inputs: this.mapProcessFormData(row),
          instId: res.data.instId, // start已有获取
          lockId: res.data.lockId, // start已有获取
          participantInfos: [], // 下一步提交获取
          props: { sendNotify: '', source: 'WE.OFFICE' },
          timer: null,
        }
      })
    },
    findActionId(list) {
      const arr = list.find((item) => item.buttonName === '提交')
      return arr.buttonId
    },
    mapProcessFormData(row) {
      return [
        { name: 'id' },
        { name: 'questionId', value: row.id },
        { name: 'title', value: '风险审核' },
        { name: 'businessTypeId', value: '200362' },
        { name: 'businessTypeName', value: '风险问题审计' },
        { name: 'batchCode', value: row.batchCode },
        { name: 'batchName', value: row.batchName },
        { name: 'businessCode', value: row.businessCode },
        { name: 'eventTagName', value: row.eventTagName },
        { name: 'modelTypeName', value: row.modelTypeName },
        { name: 'viewAccount', value: row.viewAccount },
        { name: 'risk', value: row.risk },
        { name: 'questionNature' },
        { name: 'personResponsible', value: row.personResponsible },
        { name: 'belongedOrgId', value: '-1' },
      ]
    },
    // 提交确认
    RectificationhandleOk() {
      const attachment = this.fileList.length ? this.fileList[0].url : ''
      const fileName = this.fileList.length
        ? this.fileList[0].url
          ? this.RectificationForm.fileName
          : ''
        : ''
      const param = {
        reformStatus: 1,
        reformDesc: this.RectificationForm.reformDesc,
        id: this.RectificationForm.id,
        attachment: attachment,
        fileName: fileName,
      }
      AuditRiskbraryService.saveIamQuestionReform(param).then((res) => {
        if (res) {
          message.success('提交成功')
          this.startFlowList.inputs.push(
            { name: 'attachment', value: attachment },
            { name: 'fileName', value: fileName },
            { name: 'reformDesc', value: this.RectificationForm.reformDesc }
          )
          // this.visibleRectification = false
          // this.handleSearch()
          setTimeout(() => {
            this.$refs.pRelSelect.openPicker()
          }, 0)
        }
      })
    },
    // 提交关闭
    RectificationCancel() {
      this.visibleRectification = false
    },
    // 整改说明点击弹框
    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.detailStatus = row.status !== 1
      const params = {
        modelId: row.modelId,
        detailGroupId: row.detailGroupId,
        jmEventType: row.jmEventType,
        businessCode: row.businessCode,
        bussKey: row.bussKey || null,
        pushDate: row.pushDate,
        unitCode: row.unitCode,
      }
      const formData = new FormData()
      Object.keys(params).forEach((key) => {
        formData.append(key, params[key])
      })
      this.modelDetail = {
        modelDomainName: row.modelDomainName,
        batchName: row.modelName,
        batchCode: row.modelCode,
        riskData: row.risk,
      }
      // 地址audit-risk-detail 参数params
      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>
