<template>
  <a-spin :spinning="isshowLoading" tip="正在导出请稍等……" size="large">
    <div :class="$style.wrapHeight">
      <div>
        <a-card :class="$style.conditions">
          <a-form-model
            ref="advancedSearchForm"
            class="ant-advanced-search-form"
            :model="form"
            v-bind="formItemLayout"
          >
            <a-form-model-item v-if="!rolesType" label="模型编码" prop="modelCode">
              <a-input v-model="form.modelCode" placeholder="请输入模型编码" />
            </a-form-model-item>
            <!-- 业务编码 -->
            <a-form-model-item :label="'业务编码'" prop="businessCode">
              <a-input v-model="form.businessCode" placeholder="请输入业务编码" allow-clear />
            </a-form-model-item>
            <a-form-model-item v-if="rolesType" :label="'事件标签分类'" prop="eventTagName">
              <a-input v-model="form.eventTagName" placeholder="事件标签分类" allow-clear />
            </a-form-model-item>
            <a-form-model-item v-if="rolesType" label="事件标签">
              <a-input v-model="form.jmEventType"></a-input>
            </a-form-model-item>
            <a-form-model-item v-if="rolesType" label="模型名称" prop="modelName">
              <a-input v-model="form.modelName" placeholder="请输入模型名称" />
            </a-form-model-item>
            <a-form-model-item :label="'模型类型'" prop="modelType">
              <div style="width: 200px">
                <a-select v-model="form.modelType" 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>
              </div>
            </a-form-model-item>
            <!-- endType null 全部 0未整改 1已整改 -->
            <a-form-model-item v-if="rolesType" :label="'审核状态'" prop="endType">
              <div style="width: 200px">
                <a-select v-model="form.endType" placeholder="请选择审核状态" allow-clear>
                  <!-- <a-select-option value="0">分析型</a-select-option> -->
                  <a-select-option value="0">未整改</a-select-option>
                  <a-select-option value="1">已整改</a-select-option>
                </a-select>
              </div>
            </a-form-model-item>
            <a-form-model-item :label="'单位'" prop="unit">
              <a-input v-model="form.unit" placeholder="请输入单位" />
            </a-form-model-item>
            <!-- <a-form-model-item :label="'二级单位'" prop="secondUnit">
              <a-input v-model="form.secondUnit" placeholder="请输入二级单位" />
            </a-form-model-item> -->

            <!-- 审核状态 -->
            <a-form-model-item v-if="!rolesType" label="审核状态" placeholder="请选择审核状态">
              <div style="width: 200px">
                <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>
              </div>
            </a-form-model-item>
            <!-- 整改状态 -->
            <a-form-model-item v-if="!rolesType" label="整改状态" placeholder="请选择整改状态">
              <div style="width: 200px">
                <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>
              </div>
            </a-form-model-item>
            <!-- 查看状态 -->
            <a-form-model-item v-if="!rolesType" label="查看状态" placeholder="请选择查看状态">
              <div style="width: 200px">
                <a-select v-model="form.viewFlag" placeholder="请选择查看状态" allow-clear>
                  <a-select-option value="0">未查看</a-select-option>
                  <a-select-option value="1">已查看</a-select-option>
                </a-select>
              </div>
            </a-form-model-item>
            <a-form-model-item :label="'二级单位简称'">
              <a-input v-model="form.secondUnit" placeholder="请输入二级单位简称" allow-clear />
            </a-form-model-item>
            <a-form-model-item v-if="!rolesType" label="业务领域">
              <audit-select-area v-model="form.modelDomain" />
            </a-form-model-item>
            <a-form-model-item label="业务时间" style="margin-left: 10px">
              <div style="width: 230px">
                <a-range-picker v-model="time3" :format="'YYYY-MM-DD'" @change="changeTimeRange" />
              </div>
            </a-form-model-item>
            <a-form-model-item label="问题推送时间" prop="pushDate" style="margin-left: 10px">
              <div style="width: 230px">
                <a-range-picker
                  v-model="time1"
                  :format="'YYYY-MM-DD'"
                  @change="changeStartTimeChange"
                />
              </div>
            </a-form-model-item>
            <!-- 整改截至时间 -->
            <a-form-model-item
              v-if="!rolesType"
              label="整改截至时间"
              prop="reformTime"
              style="margin-left: 10px"
            >
              <div style="width: 230px">
                <a-range-picker
                  v-model="time4"
                  :format="'YYYY-MM-DD'"
                  @change="changeStartTimeChange2"
                />
              </div>
              <!-- reformDeadlineSt reformDeadlineEd -->
            </a-form-model-item>
            <!-- 业务领域 -->

            <a-form-model-item>
              <div :class="$style.buttonContent">
                <a-button type="primary" @click="handleSearch">搜索</a-button>
                <a-button type="primary" @click="handleReset">重置</a-button>
                <a-button type="primary" @click="fnexport">导出</a-button>
              </div>
            </a-form-model-item>
          </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: 1300 }"
              :data-url="dataUrl"
            >
              <div slot="action" slot-scope="text, record">
                <a-button type="link" @click="detailClick(record)">明细</a-button>
              </div>
            </sd-data-table>
          </a-card>
          <audit-advanced-export
            ref="export"
            :v-if="false"
            :exclebxh="false"
            table-id="iamModelMaintain"
            :expressions="exportExpressions"
            :config-id="121"
          />
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script>
// import AuditRangeDatePicker from '../../components/picker/audit-range-date-picker.vue'
import components from './_import-components/audit-summarry-list-import'
import auditAdvancedExport from '../../components/audit-advanced-export.vue'
import { getUserInfo } from '@/common/store-mixin'
import AuditRiskbraryService from './riskLibrary'
import download from '@/common/services/download'
import { message, Modal } from 'ant-design-vue'
import moment from 'moment'
import auditSelectArea from './audit-select-area'
import { sdSessionStorage } from '@/common/services/storage-service'

export default {
  name: 'AuditSummarryList',
  metaInfo: {
    title: '审计问题总汇',
  },
  components: {
    ...components,
    // AuditRangeDatePicker,
    auditAdvancedExport,
    auditSelectArea,
  },
  data() {
    return {
      exportLoading: false,
      isshowLoading: false,
      dataUrl: 'api/xcoa-mobile/v1/iamquestionreform/iamQuestionReformSummary',
      exportExpressions: [],
      form: {
        businessCode: null,
        eventTagName: null,
        viewFlag: undefined,
        secondUnit: null,
        risk: null,
        modelType: '1',
        // timeRange: [],
        belongedSecondUnit: null,
        unit: null,
        // buss_time
        bussTime: null,
        abbreviation: null,
        modelDomain: undefined,
        endType: undefined,
        reformStatus: undefined,
        //  bussTimeSt bussTimeEd 业务时间
        bussTimeSt: null,
        bussTimeEd: null,
        pushDateSt: null,
        pushDateEd: null,
        reformDeadlineEd: null,
        jmEventType: '',
        reformDeadlineSt: null,
      },
      time1: [],
      time2: [],
      time3: [],
      time4: [],
      formItemLayout: {
        layout: 'inline',
        labelCol: { span: 10 },
        wrapperCol: { span: 14 },
      },
      dataKey: 0,
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '业务编码',
          dataIndex: 'businessCode',
        },
        {
          title: '模型编码',
          dataIndex: 'modelCode',
        },
        {
          title: '模型名称',
          dataIndex: 'modelName',
        },
        {
          title: '业务领域',
          dataIndex: 'modelDomainName',
        },
        {
          title: '业务阶段',
          dataIndex: 'modelPhaseName',
        },
        {
          title: '模型类型',
          dataIndex: 'modelTypeName',
        },
        {
          title: '二级单位简称',
          dataIndex: 'secondUnit',
          width: '100px',
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: '100px',
        },

        {
          title: '问题推送日期',
          dataIndex: 'pushDate',
        },

        // 整改截至日期reformDeadline
        {
          title: '整改截至日期',
          dataIndex: 'reformDeadline',
        },
        // 整改期限 reformTime
        {
          title: '整改期限',
          dataIndex: 'reformTime',
          customRender: (text, record) => {
            if (record.modelTypeName.includes('关注类')) {
              return '--'
            } else {
              return text
            }
          },
        },
        // 整改状态rectStatus
        {
          title: '整改状态',
          dataIndex: 'reformStatus',
          customRender: (text, record) => {
            if (record.modelTypeName.includes('关注类')) {
              return '--'
            }
            if (text === 0) {
              return '期限内已整改'
            } else if (text === 1) {
              return '逾期已整改'
            } else if (text === 2) {
              return '期限内未整改完成'
            } else if (text === 3) {
              return '逾期未整改完成'
            }
          },
        },
        // 查看状态
        {
          title: '查看状态',
          dataIndex: 'viewFlag',
          customRender: (text, record) => {
            if (record.modelTypeName.includes('整改类')) {
              return '--'
            }
            // <span>{{ record.viewFlag === 1 ? '已查看' : '未查看' }}</span>
            if (text === 0 || text === null) {
              return '未查看'
            } else if (text === 1) {
              return '已查看'
            }
          },
        },
        //  审核状态status
        {
          title: '审核状态',
          dataIndex: 'endType',
          customRender: (text, record) => {
            if (record.modelTypeName.includes('关注类')) {
              return '--'
            }
            if (text === 2) {
              return '未提交审核'
            } else if (text === 1) {
              return '待整改'
            } else if (text === 5) {
              return '审核通过'
            } else if (text === 0) {
              return '审核驳回'
            }
          },
        },
        {
          title: '操作',
          dataIndex: 'sharedSetting',
          fixed: 'right',
          width: '100px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      rolesType: false,
      pageData: {},
      oldSearch: null,
    }
  },
  created() {
    this.time3 = [moment('2024-01-01', 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')]
    const timeList = this.time3.map((item) => {
      // 转化成时间戳 并忽略时分秒
      return moment(item._d)
        .startOf('day')
        .valueOf()
    })
    this.form.bussTimeSt = timeList[0]
    this.form.bussTimeEd = timeList[1] + 60 * 60 * 24 * 1000
    const roles = this.$store.state.sd.common.userInfo.default.roles
    this.rolesType = roles.map((val) => val.code).includes('G-1_SITUATION_LEADER')
    if (this.rolesType) {
      this.dataUrl = 'api/xcoa-mobile/v1/iamquestionreform/iamQuestionReformSummaryQueryListNew'
      this.columns = [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '业务编码',
          dataIndex: 'businessCode',
        },
        // 业务时间
        // {
        //   title: '业务时间',
        //   dataIndex: 'bussTime',
        // },
        // todo 事件标签
        {
          title: '事件标签',
          dataIndex: 'jmEventType',
        },
        {
          title: '事件标签分类',
          dataIndex: 'eventTagName',
        },
        {
          title: '模型类型',
          dataIndex: 'modelTypeName',
        },
        {
          dataIndex: 'modelType',
          sdHidden: true,
        },
        {
          title: '问题推送日期',
          dataIndex: 'pushDate',
        },
        // {
        //   title: '关注风险',
        //   dataIndex: 'risk',
        // },
        // todo 改为二级单位简称
        // {
        //   title: '管理归属二级单位',
        //   dataIndex: 'belongedSecondUnit',
        // },
        // todo二级单位简称 字段需确认

        {
          title: '二级单位简称',
          dataIndex: 'secondUnit',
        },
        {
          dataIndex: 'secondUnitCode',
          sdHidden: true,
        },
        {
          dataIndex: 'unitCode',
          sdHidden: true,
        },
        {
          title: '单位',
          dataIndex: 'unit',
        },
        // 风险问题数量 total
        {
          title: '风险问题数量',
          dataIndex: 'total',
        },
        {
          title: '问题数量',
          dataIndex: 'questionNum',
        },
        {
          title: '非问题数量',
          dataIndex: 'nonQuestionNum',
        },
        {
          title: '已整改数量',
          dataIndex: 'reformNum',
        },
        {
          title: '未整改数量',
          dataIndex: 'nonReformNum',
        },

        {
          title: '操作',
          dataIndex: 'sharedSetting',
          fixed: 'right',
          width: '100px',
          scopedSlots: { customRender: 'action' },
        },
      ]
      // 初始化 业务默认时间
      // 2024.01.01-至今
    }
  },
  mounted() {
    this.oldSearch = this.setExpressions()
  },
  methods: {
    filterColumns() {
      // 过滤 问题 非问题 已整改 未整改
      this.columns = this.columns.filter((item) => {
        return (
          item.dataIndex !== 'questionNum' &&
          item.dataIndex !== 'reformNum' &&
          item.dataIndex !== 'nonReformNum' &&
          item.dataIndex !== 'nonQuestionNum' &&
          item.dataIndex !== 'nonViewNum' &&
          item.dataIndex !== 'viewNum'
        )
      })
    },

    selectModelTypeChange(val) {
      // 如果是领导
      if (this.rolesType) {
        this.filterColumns()
        if (val === '1') {
          // 从倒数第二位开始插入
          this.columns.splice(
            this.columns.length - 1,
            0,
            ...[
              {
                title: '问题数量',
                dataIndex: 'questionNum',
              },
              {
                title: '非问题数量',
                dataIndex: 'nonQuestionNum',
              },
              {
                title: '已整改数量',
                dataIndex: 'reformNum',
              },
              {
                title: '未整改数量',
                dataIndex: 'nonReformNum',
              },
            ]
          )
        }
        if (val === '2') {
          // 从倒数第二位开始插入
          this.columns.splice(
            this.columns.length - 1,
            0,
            ...[
              {
                title: '已查看数量',
                dataIndex: 'viewNum',
              },
              {
                title: '未查看数量',
                dataIndex: 'nonViewNum',
              },
            ]
          )
        }
      }
    },
    // 开始时间 结束时间
    changeTimeRange(val) {
      // 开始天的 00:00:00 结束天的 23:59:59 时间戳
      const timeList = val.map((item) => {
        // 转化成时间戳 并忽略时分秒
        return moment(item._d)
          .startOf('day')
          .valueOf()
      })
      // 结束时间加一天的时间戳
      this.form.bussTimeSt = timeList[0]
      this.form.bussTimeEd = timeList[1] + 60 * 60 * 24 * 1000
    },
    changeStartTimeChange(val) {
      // "stringValue": "2023-12-16" 转换成这个格式
      this.form.pushDateSt = moment(val[0]._d).format('YYYY-MM-DD')
      this.form.pushDateEd = moment(val[1]._d).format('YYYY-MM-DD')
    },
    changeStartTimeChange2(val) {
      // reformDeadlineSt reformDeadlineEd
      this.form.reformDeadlineSt = moment(val[0]._d).format('YYYY-MM-DD')
      this.form.reformDeadlineEd = moment(val[1]._d).format('YYYY-MM-DD')
    },
    // 处理请求参数
    setExpressions() {
      const expressions = []

      const filter = [
        'bussTimeSt',
        'bussTimeEd',
        'pushDateSt',
        'pushDateEd',
        'modelType',
        'endType',
        'reformStatus',
        'reformDeadline',
        'modelDomain',
        'reformDeadlineEd',
        'reformDeadlineSt',
        'viewFlag',
        'jmEventType'
      ]

      for (const key in this.form) {
        if (this.form[key] && !filter.includes(key)) {
          expressions.push({
            dataType: 'str',
            name: key,
            op: 'like',
            stringValue: '%' + this.form[key] + '%',
          })
        }
        if (this.form[key] && filter.includes(key)) {
          expressions.push({
            dataType: 'str',
            name: key,
            op: 'eq',
            stringValue: this.form[key],
          })
        }
      }
      return expressions
    },
    processReq(req) {
      this.pageData.maxResults = req.data.maxResults
      this.pageData.startPosition = req.data.startPosition
      req.data.expressions = []

      req.data.expressions = this.setExpressions()
      return req
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
      this.form.bussTimeEd = null
      this.form.bussTimeSt = null
      this.form.pushDateSt = null
      this.form.pushDateEd = null
      this.form.reformDeadline = null
      this.form.modelType = '1'
      this.form.modelName = null
      this.form.endType = undefined
      this.form.reformStatus = undefined
      this.form.modelDomain = undefined
      this.form.belongedSecondUnit = null
      this.form.businessCode = null
      this.form.eventTagName = null
      this.form.secondUnit = null
      this.form.risk = null
      this.form.jmEventType = ''
      this.form.unit = null
      this.form.abbreviation = null
      this.form.reformDeadlineEd = null
      this.form.reformDeadlineSt = null
      this.viewFlag = undefined
      this.time1 = []
      this.time2 = []
      this.time3 = []
      this.time4 = []
      this.filterColumns()
      this.handleSearch()
    },

    handleSearch() {
      this.selectModelTypeChange(this.form.modelType)
      this.oldSearch = this.setExpressions()
      this.dataKey++
    },

    detailClick(record) {
      if (!this.rolesType) {
        // 如果是关注类
        // setUpdateViewFlag
        if (record.modelTypeName.includes('关注')) {
          AuditRiskbraryService.setUpdateViewFlag(record.instId).then((res) => {
            window.open('#/sd-webflow/done-pages/' + record.instId)
            this.dataKey++
          })
        } else {
          window.open('#/sd-webflow/done-pages/' + record.instId)
        }
        return
      }
      let url = '#/audit-summarry-rectification-list?'
      url = '#/audit-view-change?'
      const riskDetail = this.oldSearch
      // 存到缓存里
      sdSessionStorage.setItem('riskDetail', JSON.stringify(riskDetail))
      if (record.modelTypeName !== '整改类' && record.modelTypeName !== '定位型-整改类') {
        url = '#/audit-summarry-interest-list?'
        if (this.rolesType) {
          url = '#/audit-view-detail?'
        }
      }

      if (this.rolesType) {
        const allQueryData = {
          businessCode: record.businessCode,
          jmEventType: record.jmEventType,
          eventTagName: record.eventTagName,
          modelTypeName: record.modelTypeName,
          pushDate: record.pushDate,
          unitCode: record.unitCode,
          modelId: record.modelId,
        }
        for (const key in allQueryData) {
          if (allQueryData[key]) {
            url += `${key}=${allQueryData[key]}&`
          }
        }
      } else {
        url += 'recordId=' + record.id
        url += '&maxResults=' + this.pageData.maxResults
        url += '&startPosition=' + this.pageData.startPosition
      }
      // url 编码
      url = url.replace(/\+/g, '%2B')
      window.open(url)
    },
    fnexport() {
      this.isshowLoading = true
      if (this.rolesType) {
        this.fnexportNew()
        return
      }
      this.exportExpressions = this.setExpressions()
      const account = getUserInfo().account
      AuditRiskbraryService.getUserInfo(account).then((res) => {
        const params = {
          columns:
            'sortNumber,jmEventType,eventTagName,modelTypeName,modelType,pushDate,secondUnit,secondUnitCode,unitCode,unit,questionNum,examineNum,nonExamineNum,examineFailNum,sharedSetting',
          maxResults: 10,
          startPosition: 0,
          expressions: this.exportExpressions,
          buttonExpressions: [],
        }
        AuditRiskbraryService.export(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
          })
      })
    },
    fnexportNew() {
      this.exportExpressions = this.setExpressions()
      const account = getUserInfo().account
      AuditRiskbraryService.getUserInfo(account).then((res) => {
        const params = {
          columns:
            'sortNumber,jmEventType,eventTagName,modelTypeName,modelType,pushDate,secondUnit,secondUnitCode,unitCode,unit,questionNum,examineNum,nonExamineNum,examineFailNum,sharedSetting',
          maxResults: 10,
          startPosition: 0,
          expressions: this.exportExpressions,
          buttonExpressions: [],
        }
        AuditRiskbraryService.exportNew(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
          })
      })
    },
  },
}
</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 {
  width: 260px;
  margin-left: 25px;
  button {
    margin: 0 4px;
  }
}
.no-action {
  padding: 0 15px;
  color: $text-color-secondary;
}
</style>
