<template>
  <a-spin :spinning="isshowLoading" :tip="istip" 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 label="模型编码" prop="modelCode">
              <a-input v-model="form.modelCode" placeholder="请输入模型编码" />
            </a-form-model-item>
            <a-form-model-item 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>
            <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 :label="'下发状态'" prop="status">
              <div style="width: 200px">
                <a-select v-model="form.status" placeholder="请选择下发状态" allow-clear>
                  <!-- 增加下发状态 待下发0， 已下发1，，下发失败 2 -->
                  <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>
            <a-form-model-item :label="'问题类型'" prop="distributeType">
              <div style="width: 200px">
                <a-select v-model="form.distributeType" 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="业务领域" prop="secondUnit">
              <audit-select-area v-model="form.modelDomain" />
            </a-form-model-item>
            <a-form-model-item :label="'删除状态'" prop="deleted">
              <div style="width: 200px">
                <a-select v-model="form.deleted" placeholder="请选择删除状态">
                  <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="timeRange">
              <div style="width: 245px">
                <a-range-picker
                  v-model="time"
                  :format="'YYYY-MM-DD'"
                  @change="changeStartTimeChange"
                />
              </div>
            </a-form-model-item>
            <a-form-model-item label="业务时间">
              <div style="width: 245px">
                <a-range-picker v-model="time3" :format="'YYYY-MM-DD'" @change="changeTimeRange" />
              </div>
            </a-form-model-item>

            <a-form-model-item>
              <div :class="$style.buttonContent">
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button @click="handleReset">重置</a-button>
                <!-- 导出 -->
                <a-button :loading="exportLoading" type="primary" @click="fnexport">导出</a-button>
                <!-- 下发 -->
                <a-dropdown>
                  <a-menu slot="overlay">
                    <a-menu-item key="1">
                      <a-button
                        size="large"
                        :block="true"
                        type="primary"
                        :disabled="form.distributeType === '1'"
                        @click="handleIssue"
                        >下发</a-button
                      >
                    </a-menu-item>
                    <a-menu-item v-if="deleteIssue" key="2">
                      <!-- 删除 -->
                      <a-button
                        v-if="deleteIssue"
                        size="large"
                        :block="true"
                        type="primary"
                        @click="handleDelete"
                        >删除</a-button
                      >
                    </a-menu-item>
                    <a-menu-item key="3">
                      <a-button @click="dataViewRw = true">下发任务管理</a-button>
                    </a-menu-item>
                  </a-menu>
                  <a-button> 更多操作 <a-icon type="down" /> </a-button>
                </a-dropdown>
              </div>
            </a-form-model-item>
          </a-form-model>
        </a-card>
        <div>
          <a-card>
            <sd-data-table
              ref="SJMXDataTable"
              :key="dataKey"
              :columns="columns"
              :process-req="processReq"
              form-id="iamModelMaintain"
              :show-selection="(record) => record.status !== 1 && record.deleted === 0"
              :scroll="{ x: '100%' }"
              :pagination="{
                // 每页数量
                pageSizeOptions: ['10', '30', '50', '100', '500'],
              }"
              data-url="api/xcoa-mobile/v1/iamquestionreform/questionExamineSummaryQueryList"
            >
              <div slot="action" slot-scope="text, record">
                <a-button type="link" @click="openRiskDetail(record)">明细</a-button>
                <!-- handleRecover 已删除的显示恢复 -->
                <a-button v-if="record.deleted === 1" type="link" @click="handleRecover(record)"
                  >恢复</a-button
                >
                <!-- 模型逻辑 -->
                <a-button type="link" @click="showModelLogic(record)">模型逻辑</a-button>
              </div>
            </sd-data-table>
          </a-card>
        </div>
        <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>
        <audit-model-logic v-model="modelLogicVisible" :content="modelLogicContent" />
        <!-- 下发任务管理 -->
        <a-modal v-model="dataViewRw" title="下发任务列表" :footer="null" width="800px">
          <a-form-model v-bind="formItemLayout" style="margin-bottom: 15px">
            <a-form-model-item label="任务创建时间">
              <div style="width: 245px">
                <a-range-picker v-model="taskForm.time" :format="'YYYY-MM-DD'" />
              </div>
            </a-form-model-item>
            <!-- 任务名称 -->
            <a-form-model-item label="任务名称">
              <a-input v-model="taskForm.taskName" placeholder="请输入任务名称" />
            </a-form-model-item>
            <!-- 下发状态 -->
            <a-form-model-item label="下发状态">
              <div style="width: 200px">
                <a-select v-model="taskForm.status" placeholder="请选择下发状态">
                  <a-select-option value="">全部</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>
              <div style="width: 200px;margin-left: 20px;">
                <a-button type="primary" @click="handleTaskSearch">查询</a-button>
                <a-button @click="restTaskForm">重置</a-button>
              </div>
            </a-form-model-item>
          </a-form-model>

          <SdDataTableEx
            :key="dataTaskKey"
            ref="taskTable"
            style="margin-top: 20px;"
            form-id="iamQuestionTask"
            :show-selection="false"
            :scroll="{ x: '100%' }"
            :process-req="processReqTask"
            :columns="columnsTask"
          ></SdDataTableEx>
        </a-modal>
      </div>
    </div>
  </a-spin>
</template>

<script>
import components from './_import-components/audit-shsum-list-import'
import moment from 'moment'
import AuditRiskbraryService from '@product/iam/audit/riskLibrary/riskLibrary'
import { message, Modal } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import download from '@/common/services/download'
import auditModelLogic from './audit-model-logic'
import auditSelectArea from './audit-select-area'
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'
import TableColumnTypes from '@/common/services/table-column-types'

export default {
  name: 'AuditShsumList',
  metaInfo: {
    title: '审计问题总汇审核',
  },
  components: {
    ...components,
    auditModelLogic,
    auditSelectArea,
    SdDataTableEx,
  },
  data() {
    return {
      // 导出按钮状态
      exportLoading: false,
      // 下发弹窗
      // 下发删除按钮权限
      deleteIssue: false,
      issueVisible: false,
      isshowLoading: false,
      istip: '正在导出请稍等……',
      issueMessageList: [
        { label: '下发总数：', value: 0 },
        { label: '下发成功：', value: 0 },
        { label: '下发失败：', value: 0 },
        { label: '下发失败原因：', value: '' },
      ],

      // 搜索筛选
      form: {
        modelCode: '',
        modelName: '',
        modelType: undefined,
        // 单位
        unit: '',
        // 二级单位简称
        secondUnit: '',
        // 下发状态，问题类型
        status: '0',
        // 问题类型
        distributeType: '',
        // 问题推送日期
        // 领域
        // model_domain
        modelDomain: '',
        pushDateSt: '',
        pushDateEd: '',
        bussTimeSt: '',
        bussTimeEd: '',
        deleted: '0',
      },
      time: [],
      time3: [],
      formItemLayout: {
        layout: 'inline',
        labelCol: { span: 8 },
        wrapperCol: { span: 14 },
      },
      dataKey: 0,
      dataTaskKey: 0,
      taskForm: {
        // 创建时间
        // 任务名称
        // 下发状态
        time: [],
        taskName: '',
        status: '',
      },
      dataViewRw: false,
      columnsTask: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '任务名称',
          dataIndex: 'taskName',
          width: '150px',
        },
        {
          title: '任务创建时间',
          dataIndex: 'creationTime',
          width: '150px',
          sdRender: TableColumnTypes.dateTime,
        },
        // 创建人，下发状态 成功条数，失败条数，失败原因
        {
          title: '创建人',
          dataIndex: 'creatorName',
          width: '100px',
        },
        {
          title: '下发状态',
          dataIndex: 'status',
          width: '100px',
          customRender: (text) => {
            // 执行状态 0执行者  1执行成功  2失败
            switch (text) {
              case 0:
                return '下发中'
              case 1:
                return '下发成功'
              case 2:
                return '下发失败'
              default:
                return ''
            }
          },
        },
        {
          title: '成功条数',
          dataIndex: 'successNum',
          width: '100px',
        },
        {
          title: '失败条数',
          dataIndex: 'failNum',
          width: '100px',
        },
        {
          title: '失败原因',
          dataIndex: 'failReason',
          width: '100px',
        },
        //
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        // 模型编码， 模型名称 业务领域， 业务阶段， 模型类型 ，问题推送日期，
        // 二级单位简称 单位， 下发状态， 失败原因 审核人 审核时间
        {
          title: '模型编码',
          dataIndex: 'modelCode',
          width: '150px',
        },
        // 模型名称
        {
          title: '模型名称',
          dataIndex: 'modelName',
          width: '100px',
        },
        // 业务领域
        {
          title: '业务领域',
          dataIndex: 'modelDomainName',
          width: '100px',
        },
        // 业务阶段
        {
          title: '业务阶段',
          dataIndex: 'modelPhaseName',
          width: '100px',
        },
        // 模型类型
        {
          title: '模型类型',
          dataIndex: 'modelTypeName',
          width: '100px',
        },
        // 问题推送日期
        {
          title: '问题推送日期',
          dataIndex: 'pushDate',
          width: '100px',
        },
        // 二级单位简称
        {
          title: '二级单位简称',
          dataIndex: 'secondUnit',
          width: '100px',
        },
        // 单位
        {
          title: '单位',
          dataIndex: 'unit',
          width: '100px',
        },
        // 下发状态
        {
          title: '下发状态',
          dataIndex: 'status',
          width: '100px',
          customRender: (text) => {
            if (text === 0) {
              return '待下发'
            }
            if (text === 1) {
              return '已下发'
            }
            if (text === 2) {
              return '下发失败'
            }
          },
        },
        // 失败原因
        {
          title: '失败原因',
          dataIndex: 'failReason',
          width: '100px',
        },
        // 删除状态
        // deleted 0 1
        {
          title: '删除状态',
          dataIndex: 'deleted',
          width: '100px',
          customRender: (text) => {
            if (text === 0) {
              return '未删除'
            }
            if (text === 1) {
              return '已删除'
            }
          },
        },
        // 审核人
        {
          title: '审核人',
          dataIndex: 'examineUser',
          width: '100px',
        },
        // 审核时间
        {
          title: '审核时间',
          dataIndex: 'examineTime',
          width: '340px',
        },
        // configIdea
        {
          title: '模型逻辑',
          dataIndex: 'configIdea',
          width: '100px',
          sdHidden: true,
        },
        {
          dataIndex: 'unitCode',
          sdHidden: true,
        },
        {
          title: '操作',
          dataIndex: 'sharedSetting',
          fixed: 'right',
          width: '100px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      selectedRowKeys: [],
      selectedRows: [],
      modelLogicContent: '',
      modelLogicVisible: false,
    }
  },
  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

    this.form.modelType = '1'
  },
  mounted() {
    // G-1_FENGXIAN_SHANCHU
    const roles = this.$store.state.sd.common.userInfo.default.roles
    this.deleteIssue = roles.map((val) => val.code).includes('G-1_FENGXIAN_SHANCHU')
  },

  methods: {
    /**
     * 搜索部分
     */
    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')
    },
    // 处理请求参数
    setExpressions() {
      const expressions = []
      const filter = [
        'bussTimeSt',
        'bussTimeEd',
        'pushDateSt',
        'pushDateEd',
        'modelType',
        'distributeType',
        'status',
        'modelDomain',
        'deleted',
        'modelCode',
      ]

      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) {
      req.data.expressions = []
      req.data.expressions = this.setExpressions()
      return req
    },
    processReqTask(req) {
      req.data.expressions = []
      if (this.taskForm.taskName) {
        req.data.expressions.push({
          dataType: 'str',
          name: 'taskName',
          op: 'like',
          stringValue: '%' + this.taskForm.taskName + '%',
        })
      }
      if (this.taskForm.time.length > 0) {
        req.data.expressions.push({
          dataType: 'long',
          name: 'creationTime',
          op: 'ge',
          longValue: moment(this.taskForm.time[0]._d).valueOf(),
        })
        req.data.expressions.push({
          dataType: 'long',
          name: 'creationTime',
          op: 'lt',
          longValue: moment(this.taskForm.time[1]._d).valueOf() + 60 * 60 * 24 * 1000,
        })
      }
      if (this.taskForm.status) {
        req.data.expressions.push({
          dataType: 'str',
          name: 'status',
          op: 'eq',
          stringValue: this.taskForm.status,
        })
      }
      return req
    },
    // 查询
    handleSearch() {
      this.dataKey++
    },
    // 重置
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
      this.form.bussTimeEd = null
      this.form.bussTimeSt = null
      this.form.pushDateSt = null
      this.form.pushDateEd = null
      this.form.deleted = '0'
      this.time3 = []
      this.form.distributeType = '0'
      this.form.status = '0'
      this.time = []
      this.handleSearch()
    },
    // 下发
    handleIssue() {
      this.istip = '下发中……'

      const selectedRows = this.$refs.SJMXDataTable.getSelectedRows()
      // 如果没有选中数据
      if (selectedRows.length !== 0) {
        const params = selectedRows.map((item) => {
          return {
            modelTypeName: item.modelTypeName,
            pushDate: item.pushDate,
            unitCode: item.unitCode,
            modelId: item.modelId,
            detailGroupId: item.detailGroupId,
            status: item.status,
            bussKey: item.bussKey || null,
          }
        })
        this.isshowLoading = true
        AuditRiskbraryService.questionSummaryExamine(params)

          .then((res) => {
            this.setMessageList(res.data)
            this.handleSearch()
          }) // 下发成功
          .finally(() => {
            this.isshowLoading = false
          })
      } else {
        // 如果
        if (this.form.deleted !== '0') {
          message.warning('请选择删除状态为未删除数据进行下发')
          return
        }
        // 请选择下发状态为待下发与下发失败数据进行下发
        if (this.form.status === '1') {
          message.warning('请选择下发状态为待下发与下发失败数据进行下发')
          this.isshowLoading = false
          return
        }
        this.isshowLoading = true

        const exportExpressions = this.setExpressions() // 导出表达式

        const params = {
          columns:
            'sortNumber,modelCode,modelName,modelDomainName,modelPhaseName,modelTypeName,pushDate,secondUnit,unit,status,failReason,examineUser,examineTime,configIdea,unitCode,sharedSetting',
          maxResults: -1,
          expressions: exportExpressions,
          buttonExpressions: [],
        }
        AuditRiskbraryService.questionSummaryQueryExamine(params)
          .then((res) => {
            if (res.data) {
              const that = this
              Modal.info({
                title: '提示',
                content: '已创建下发任务',
                okText: '关闭',
                okType: 'danger',
                cancelText: '查看',
                onOk() {
                  // console.log('OK')
                },
                onCancel() {
                  that.dataViewRw = true
                },
              })
            } else {
              this.setMessageList(res.data)
              this.handleSearch()
            }
          }) // 下发成功
          .finally(() => {
            this.isshowLoading = false
          })
      }
    },
    restTaskForm() {
      this.taskForm = {
        time: [],
        status: '',
        taskName: '',
      }
      this.handleTaskSearch()
    },
    // 搜索
    handleTaskSearch() {
      this.dataTaskKey++
    },
    // 开始时间 结束时间
    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
    },
    // 删除
    handleDelete() {
      Modal.confirm({
        title: '提示',
        content: '仅支持删除待下发及下发有误的数据，是否确认删除？',
        onOk: () => {
          const selectedRows = this.$refs.SJMXDataTable.getSelectedRows()
          const params = selectedRows.map((item) => {
            return {
              modelTypeName: item.modelTypeName,
              pushDate: item.pushDate,
              unitCode: item.unitCode,
              modelId: item.modelId,
              detailGroupId: item.detailGroupId,
              status: item.status,
              bussKey: item.bussKey || null,
            }
          })
          AuditRiskbraryService.questionSummaryDelete(params).then((res) => {
            if (res?.data) {
              message.success('删除成功')
              this.handleSearch()
            } else {
              message.warning('删除失败')
            }
          })
        },
      })
    },
    // 恢复删除
    handleRecover(item) {
      Modal.confirm({
        title: '提示',
        content: '是否确认恢复？',
        onOk: () => {
          const params = [
            {
              modelTypeName: item.modelTypeName,
              pushDate: item.pushDate,
              unitCode: item.unitCode,
              modelId: item.modelId,
              detailGroupId: item.detailGroupId,
              status: item.status,
              bussKey: item.bussKey || null,
            },
          ]
          AuditRiskbraryService.restoreQuestion(params).then((res) => {
            if (res?.data) {
              message.success('恢复成功')
              this.handleSearch()
            } else {
              message.warning('恢复失败')
            }
          })
        },
      })
    },

    // 导出
    fnexport() {
      this.istip = '正在导出请稍等……'

      this.isshowLoading = true
      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.examineSummaryExport(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
          })
      })
    },
    // 下发回馈
    setMessageList(data) {
      this.issueMessageList = [
        { label: '下发总数：', value: data.questionNum },
        { label: '下发成功：', value: data.examineNum },
        { label: '下发失败：', value: data.examineFailNum },
        { label: '下发失败原因：', value: data.failReason },
      ]
      this.issueVisible = true
    },
    // 前往领域
    toPath() {
      window.open('#/sd-frame/audit-area-list')
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 关闭
    cancel() {
      this.issueVisible = false
      this.selectedRowKeys = []
      this.selectedRows = []
    },
    /**
     * 操作部分
     */
    // 模型逻辑
    showModelLogic(record) {
      this.modelLogicContent = record.configIdea
      this.modelLogicVisible = true
    },
    openRiskDetail(row) {
      // 审核状态
      this.detailStatus = row.status !== 1
      const params = {
        modelId: row.modelId,
        detailGroupId: row.detailGroupId,
        status: row.status,
        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)

      const openUrl = `queryJson=${encodeURIComponent(queryJson)}&modelDetail=${encodeURIComponent(
        detailJson
      )}&detailStatus=${encodeURIComponent(this.detailStatus)}&type=sh`

      window.open('#/audit-risk-detail?' + openUrl)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;

  .button-content {
    width: 400px;
    margin-left: 25px;
    button {
      margin: 0 4px;
    }
  }
}
</style>
