<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="status">
              <a-select v-model="form.status" placeholder="请选择状态" allow-clear>
                <a-select-option :value="1">已下发</a-select-option>
                <a-select-option :value="0">待下发</a-select-option>
                <a-select-option :value="2">下发失败</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <div :class="$style.buttonContent">
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button @click="handleReset">重置</a-button>
              <!-- 审核 -->
              <a-button type="primary" @click="handleExamine">下发</a-button>
              <!-- 删除 -->
              <a-button type="primary" @click="handleDelete">删除</a-button>
              <a-button @click="exportExcel">导出</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <div>
      <a-card>
        <sd-data-table
          ref="SJMXDataTable"
          :key="dataKey"
          :columns="columns"
          :process-req="processReq"
          form-id="iamModelMaintain"
          :scroll="{ x: 1300 }"
          data-url="api/xcoa-mobile/v1/iamquestionreform/questionExamineQueryList"
          :filter-expressions="expressions"
          show-selection
        >
          <!-- :show-selection="(item) => item.status !== 1" -->
          <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
            >
          </div>
          <template slot="status" slot-scope="text, record">
            <span v-if="record.status === 0">待下发</span>
            <span v-if="record.status === 1">已下发</span>
            <span v-if="record.status === 2">下发失败</span>
          </template>
          <template slot="failReason" slot-scope="text, record">
            <span v-if="record.status === 2">模型领域未绑定整改人及初审、复审人</span>
          </template>
        </sd-data-table>
      </a-card>
      <a-modal v-model="visible" title="问题详情" :footer="null" width="1200px" @cancel="cancel">
        <div :class="$style.detail">
          <div :class="$style.detailDelete">
            <a-button v-if="detailStatus" type="primary" @click="ondetailDelete">删除</a-button>
          </div>
          <div :class="$style.modelDetail">
            <span>模型编码：{{ modelDetail.batchCode }}</span>
            <span>模型名称：{{ modelDetail.batchName }}</span>
            <span>业务领域：{{ modelDetail.modelDomainName }}</span>
          </div>
          <a-table
            :columns="columnsDetail"
            :data-source="dataDetail"
            :row-key="(_, index) => index"
            :scroll="{ x: 1150, y: 500 }"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          >
            <!-- 详情 -->
            <template slot="action" slot-scope="text, record">
              <!-- 如果 -->
              <a-button type="link" @click="showModal(record)">详情</a-button>
            </template>
          </a-table>
        </div>
      </a-modal>
      <a-modal v-model="issueVisible" title="下发提醒" :footer="null" @cancel="cancel">
        <div>
          <p v-for="(item, i) in issueMessageList" :key="i"
            >{{ item.label + item.value
            }}<span v-if="i === 3 && issueMessageList[3].value !== ''"
              >未绑定整改人与审核、复审人，请前往<a @click="toPath">模型领域</a
              >人员关联页面完善信息后重试
            </span>
          </p>
        </div>
      </a-modal>
    </div>
    <audit-model-logic v-model="modelLogicVisible" :content="modelLogicContent" />
  </audit-form-top-banner>
</template>

<script>
import components from './_import-components/audit-shdetail-list-import'
import AuditRiskbraryService from '@product/iam/audit/riskLibrary/riskLibrary'
import { message, Modal } from 'ant-design-vue'
import auditFormTopBanner from './audit-top-banner'
import download from '@/common/services/download'
import auditModelLogic from './audit-model-logic'

export default {
  name: 'AuditShdetailList',
  metaInfo: {
    title: '问题明细审核-关注类',
  },
  components: {
    ...components,
    auditFormTopBanner,
    auditModelLogic,
  },
  data() {
    return {
      modelLogicVisible: false,
      modelLogicContent: '',
      selectedRowKeys: [],
      selectedRows: [],
      form: {
        viewFlag: null,
        status: null,
      },
      visible: false,
      ModalquestionDetail: '',
      dataKey: 0,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        // {
        //   title: '批次号',
        //   dataIndex: 'batchCode',
        // },
        // {
        //   title: '批次名称',
        //   dataIndex: 'batchCode',
        // },
        {
          title: '模型编码',
          dataIndex: 'batchCode',
        },
        {
          title: '模型名称',
          dataIndex: 'batchName',
        },
        {
          title: '业务领域',
          dataIndex: 'modelDomainName',
        },
        {
          title: '业务阶段',
          dataIndex: 'modelPhaseName',
        },
        {
          title: '关注风险',
          dataIndex: 'risk',
        },
        {
          title: '问题推送日期',
          dataIndex: 'pushDate',
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        // 失败原因
        {
          title: '失败原因',
          dataIndex: 'failReason',
          scopedSlots: { customRender: 'failReason' },
        },
        // examineUser examineTime status
        // 审核人
        {
          title: '审核人',
          dataIndex: 'examineUser',
        },
        // 审核时间
        {
          title: '审核时间',
          dataIndex: 'examineTime',
        },

        {
          title: '操作',
          dataIndex: 'sharedSetting',
          fixed: 'right',
          width: '100px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'modelType',
          op: 'eq',
          stringValue: '0',
        },
      ],
      queryData: {},
      columnsDetail: [],
      dataDetail: [],
      detailStatus: false,
      // 模型信息
      modelDetail: {},
      // 下发弹窗
      issueVisible: false,
      issueMessageList: [],
    }
  },
  created() {
    this.initQueryData()
  },
  methods: {
    // 导出
    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,
          jmEventType: item.jmEventType,
          eventTagName: item.eventTagName,
          modelTypeName: item.modelTypeName,
          pushDate: item.pushDate,
          unitCode: item.unitCode,
          modelType: item.modelType,
          bussKey: item.bussKey || null,
        }
      })
      // examineDetailExport
      AuditRiskbraryService.examineDetailExport(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
        }
      })
    },
    cancel() {
      this.visible = false
      this.selectedRowKeys = []
      this.selectedRows = []
      this.columnsDetail = []
      this.dataDetail = []
      this.issueVisible = false
      this.modelDetail = {}
    },
    toPath() {
      window.open('#/sd-frame/audit-area-list')
    },
    setMessageList(data) {
      this.issueMessageList = [
        { label: '下发总数：', value: data.questionNum },
        { label: '下发成功：', value: data.examineNum },
        { label: '下发失败：', value: data.examineFailNum },
        { label: '下发失败原因：', value: data.failReason },
      ]
      this.issueVisible = true
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    ondetailDelete() {
      Modal.confirm({
        title: '提示',
        content: '是否确认删除？',
        onOk: () => {
          const ids = this.selectedRows.map((item) => item.id).join(',')
          AuditRiskbraryService.deleteDetailInfo(ids).then((res) => {
            message.success('删除成功')
            this.visible = false
            this.cancel()
            this.handleSearch()
          })
        },
      })
    },
    // 删除
    handleDelete() {
      // 判断选中的数据,如果存在已下发数据则提示已下发数据不可删除
      const selectedRows = this.$refs.SJMXDataTable.getSelectedRows()
      const isExamine = selectedRows.some((item) => item.status === 1)
      if (isExamine) {
        message.warning('已下发数据不可删除')
        return
      }
      Modal.confirm({
        title: '提示',
        content: '是否确认删除？',
        onOk: () => {
          const selectedRows = this.$refs.SJMXDataTable.getSelectedRows()

          const params = selectedRows.map((item) => {
            return {
              modelId: item.modelId,
              detailGroupId: item.detailGroupId,
              jmEventType: item.jmEventType,
              eventTagName: item.eventTagName,
              modelTypeName: item.modelTypeName,
              pushDate: item.pushDate,
              unitCode: item.unitCode,
              modelType: item.modelType,
              bussKey: item.bussKey || null,
            }
          })
          AuditRiskbraryService.questionDetailDelete(params).then((res) => {
            message.success('删除成功')
            this.handleSearch()
          })
        },
      })
    },
    // 审核
    handleExamine() {
      const selectedRows = this.$refs.SJMXDataTable.getSelectedRows()
      // /questionExamine  问题审核
      // {"modelId":472,"detailGroupId":"1","businessCode":"null-1701238800000-1","jmEventType":"2","eventTagName":"测试风险库","modelTypeName":"定位型-整改类","pushDate":"2023-11-29","unitCode":"100000","":null,"modelType":"1","status":1}
      const params = selectedRows.map((item) => {
        return {
          modelId: item.modelId,
          detailGroupId: item.detailGroupId,
          jmEventType: item.jmEventType,
          eventTagName: item.eventTagName,
          modelTypeName: item.modelTypeName,
          pushDate: item.pushDate,
          unitCode: item.unitCode,
          modelType: item.modelType,
          status: 1,
          bussKey: item.bussKey || null,
        }
      })

      AuditRiskbraryService.questionDetailExamine(params).then((res) => {
        this.setMessageList(res.data)
        this.handleSearch()
      })
    },
    // 初始化initQueryData
    initQueryData() {
      this.queryData = this.$route.query
      this.queryData.modelType = '2'
    },
    processReq(req) {
      req.data.expressions = [
        { dataType: 'str', name: 'pushDate', op: 'eq', stringValue: this.$route.query.pushDate },
        { dataType: 'str', name: 'modelType', op: 'eq', stringValue: '2' },
        { dataType: 'str', name: 'status', op: 'eq', stringValue: this.form.status },
      ]
      Object.keys(this.queryData).map((key) => {
        req.data.expressions.push({
          dataType: 'str',
          name: key,
          op: 'eq',
          stringValue: this.queryData[key],
        })
      })
      return req
    },
    handleSearch() {
      this.dataKey++
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
      this.form.status = null
    },
    viewFlagClick(row) {
      const params = {
        ...this.queryData,
        modelId: row.modelId,
        detailGroupId: row.detailGroupId,
        viewFlag: 1,
        reformStatus: 1,
        bussKey: row.bussKey || null,
      }
      AuditRiskbraryService.saveIamQuestionReform(params).then((res) => {
        if (res) {
          message.success('提交成功')
          this.handleSearch()
        }
      })
    },

    showModal(row) {
      // 审核状态
      this.detailStatus = row.status !== 1
      const params = {
        modelId: row.modelId,
        detailGroupId: row.detailGroupId,
        status: row.status,
        bussKey: row.bussKey || null,
        ...this.queryData,
      }
      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,
      }
      // 地址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}&type=sh`
      )
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.button-content {
  button {
    margin: 0 4px;
  }
}
.no-action {
  padding: 0 15px;
  color: $text-color-secondary;
}
.detail {
  width: 100%;
  overflow-x: auto;
}
.detail-delete {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.model-detail {
  display: flex;
  margin-bottom: 10px;
  span {
    margin-right: 20px;
  }
}
</style>
