<template>
  <audit-form-top-banner>
    <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" allow-clear>
              <a-select v-model="form.status" 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>
            </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="8">
            <div :class="$style.buttonContent">
              <a-button type="primary" @click="handleAction('serach')">查询</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-ex
          ref="SJMXDataTable"
          :key="dataKey"
          :columns="columns"
          :process-req="processReq"
          form-id="iamModelMaintain"
          :scroll="{ x: 2800 }"
          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>
            <!-- 下发失败 2 -->
            <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-ex>
      </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 }"
          >
          </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-shchange-list-import'
import AuditRiskbraryService from './riskLibrary'
import moment from 'moment/moment'
import sdDataTableEx from '@/common/components/sd-data-table-ex.vue'
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: 'AuditShchangeList',
  metaInfo: {
    title: '问题明细审核-整改类',
  },
  components: {
    ...components,
    sdDataTableEx,
    auditModelLogic,
    auditFormTopBanner,
  },
  data() {
    return {
      modelLogicVisible: false,
      modelLogicContent: '',
      selectedRowKeys: [],
      selectedRows: [],
      // 问题标签
      visible: false,
      dataKey: 0,
      form: {
        reformStatus: null,
        status: null,
      },
      reformDeadline: [],
      pushDate: [],

      reqData: {
        reformDeadlineSt: '',
        reformDeadlineEd: '',
        pushDateSt: '',
        pushDateEd: '',
      },
      queryData: {},
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      // 详情信息
      columnsDetail: [],
      dataDetail: [],
      // 模型信息
      modelDetail: {},
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        // 模型逻辑
        {
          title: '模型逻辑',
          dataIndex: 'configIdea',
          sdHidden: true,
        },
        {
          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: 'status',
          scopedSlots: { customRender: 'status' },
        },
        // 失败原因
        {
          title: '失败原因',
          dataIndex: 'failReason',
          scopedSlots: { customRender: 'failReason' },
        },

        // examineUser examineTime status
        // 审核人
        {
          title: '审核人',
          dataIndex: 'examineUser',
        },
        // 审核时间
        {
          title: '审核时间',
          dataIndex: 'examineTime',
          width: '300px',
        },

        {
          title: '操作',
          dataIndex: 'sharedSetting',
          fixed: 'right',
          width: '100px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'modelType',
          op: 'eq',
          stringValue: '1',
        },
      ],
      detailStatus: false,
      // 下发弹窗
      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,
          status: item.status,
          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: item.status,
          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 = '1'
    },
    // 时间变化
    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')
    },

    processReq(req) {
      req.data.expressions = [
        { dataType: 'str', name: 'reformStatus', op: 'eq', stringValue: this.form.reformStatus },
        { dataType: 'str', name: 'status', op: 'eq', stringValue: this.form.status },
        {
          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++
    },

    // 查看详情
    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.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}&type=sh`
      )
    },
  },
}
</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;
}
.detail-delete {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.model-detail {
  display: flex;
  margin-bottom: 10px;

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