<!---试运行列表-->
<template>
  <div>
    <TableHeader area datePicker nextFlag theCurrentTime ref="TableHeaderRef">
      <template #select>
        <el-form-item label="流程状态">
          <el-select v-model="tableStore.table.params.status" clearable placeholder="请选择流程状态">
            <el-option v-for="item in statusSelect" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否解决">
          <el-select v-model="tableStore.table.params.dealState" clearable placeholder="请选择是否解决">
            <el-option v-for="item in dealStateList" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </template>
    </TableHeader>
    <Table ref="tableRef" :checkbox-config="checkboxConfig" />
    <!-- 详情 -->
    <detail ref="detailRef" />
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, reactive } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { useRouter } from 'vue-router'
import { useDictData } from '@/stores/dictData'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addRunTest, initiateWarningLeaflet } from '@/api/supervision-boot/lineRunTest'
import { formatDate } from '@/utils/formatTime'
import { VxeTablePropTypes } from 'vxe-table'
import { useAdminInfo } from '@/stores/adminInfo'
import { getFileNameAndFilePath } from '@/api/system-boot/file'
import detail from './testRunDetail.vue'

const dictData = useDictData()
const statusSelect = dictData.statusSelect()
const { push } = useRouter()
const adminInfo = useAdminInfo()
const TableHeaderRef = ref()
const tableRef = ref()
const detailRef = ref()
const dealStateList = ref([
  {
    label: '未解决',
    value: '0'
  },

])
const tableStore = new TableStore({
  url: '/supervision-boot/lineRunTestProblem/pageProblem',
  method: 'POST',
  publicHeight: 65,
  column: [
    {
      title: '序号', width: 80, formatter: (row: any) => {
        return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
      }
    },
    { field: 'lineName', title: '监测点名称', minWidth: 160 },
    { field: 'connectedBus', title: '接入母线', minWidth: 160 },
    // { field: 'monitoringTerminalCode', title: '终端编号', minWidth: 140 },
    { field: 'monitoringTerminalName', title: '终端名称', minWidth: 140, },
    {
      field: 'powerSubstationName', title: '变电站', minWidth: 160, formatter: row => {
        return row.cellValue ? row.cellValue : '/'
      }
    },
    { field: 'reason', title: '调试原因', minWidth: 160 },

    {
      field: 'testRunState',
      title: '试运行状态',
      minWidth: 100,
      render: 'tag',  
      custom: {
        0: 'primary',
        2: 'success',
        3: 'danger',
        1: 'warning'
      },
      replaceValue: {
        0: '待试运行',
        1: '试运行中',
        2: '试运行成功',
        3: '试运行失败',
        null: '待试运行'
      }
    },
    {
      field: 'testRunTime',
      title: '试运行时间范围',
      minWidth: 200,
      formatter: row => {
        return row.cellValue ? row.cellValue : '/'
      }
    },
    { field: 'problemReason', title: '试运行评估问题', minWidth: 200 },
    {
      field: 'createBy',
      title: '填报人',
      minWidth: 100,
      formatter: (row: any) => {
        return dictData.state.userList.filter(item => item.id == row.cellValue)[0]?.name
      }
    },
    {
      field: 'dealState',
      title: '是否解决',
      minWidth: 100,
      render: 'tag',
      custom: {
        0: 'warning',
        1: 'primary',
        null: 'info'
      },
      replaceValue: {
        0: '未解决',
        1: '已解决',
        null: '/'
      }
    },
    {
       title: '操作',fixed: 'right',
      minWidth: 230,
     
      render: 'buttons',
      buttons: [
        // {
        //     name: 'productSetting',
        //     title: '流程详情',
        //     type: 'primary',
        //     icon: 'el-icon-EditPen',
        //     render: 'basicButton',
        //     click: row => {
        //         handleAudit(row.processInstanceId, row.historyInstanceId)
        //     },
        //     disabled: row => {
        //         return row.testRunState != 2 || !row.processInstanceId
        //     }
        // },
        {
          name: 'productSetting',
          title: '下载报告',
          type: 'primary',
          icon: 'el-icon-EditPen',
          render: 'basicButton',
          click: row => {
            downloadTheReport(row.testRunReport)
          },
          disabled: row => {
            return row.testRunReport == null || row.testRunReport.length == 0
          }
        },

        {
          name: 'edit',
          title: '发起告警单',
          type: 'warning',
          icon: 'el-icon-Open',
          render: 'basicButton',
          disabled: row => {
            return row.dealState != 0
          },

          click: async row => {
            const { value } = await ElMessageBox.prompt('', '整改意见', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',

              inputType: 'textarea',
              inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
              inputErrorMessage: '请输入整改意见'
            })
            initiateWarningLeaflet({
              id: row.id,
              problemId: row.problemId,
              reformAdvice: value,
              type: 2,
              issueDetail: row.problemReason
            }).then(res => {
              ElMessage.success('发起告警单成功！')
              tableStore.index()
            })
          }
        },
        {
          name: 'edit',
          title: '详情',
          type: 'primary',
          icon: 'el-icon-Open',
          render: 'basicButton',
          disabled: row => {
            return row.dealState == 0
          },

          click: row => {
            detailRef.value.open({
              row: row,
              title: '详情',

            })

          }
        },
        {
          name: 'edit',
          title: '查看告警单',
          type: 'primary',
          icon: 'el-icon-Open',
          render: 'basicButton',
          disabled: row => {
            return row.problemType == null
          },
          click: row => {
            push({
              name: 'supervision/supervision/manage',
              query: {
                type: 1,
                t: Date.now()
              }
            })
          }
        }
      ]
    }
  ],

  beforeSearchFun: () => {
    tableStore.table.params.orgNo = tableStore.table.params.deptIndex
    tableStore.table.params.statveList = [2]
    // tableStore.table.params.relationUserName = tableStore.table.params.userName
  }
})
tableStore.table.params.status = ''
tableStore.table.params.dealState = ''
provide('tableStore', tableStore)

onMounted(() => {
  tableStore.index()
})
const checkboxConfig = reactive<VxeTablePropTypes.CheckboxConfig>({
  labelField: '',
  checkMethod: ({ row }) => {
    return !(row.testRunState == 1 || row.testRunState == 2)
  }
})
/** 处理审批按钮 */
const handleAudit = (instanceId: any, historyInstanceId: any) => {
  push({
    name: 'BpmProcessInstanceDetail',
    state: {
      id: instanceId,
      historyInstanceId
    }
  })
}

// 下载报告
const downloadTheReport = (url: string) => {
  getFileNameAndFilePath({ filePath: url }).then((res: any) => {
    const link = document.createElement('a')
    link.href = res.data.url
    link.download = res.data.name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  })
}

const runTestSubmit = (type: number) => {
  const start = new Date()
  start.setDate(start.getDate() + 1)
  start.setHours(0, 0, 0)

  const end = new Date()
  end.setDate(end.getDate() + 3)
  end.setHours(23, 59, 59)
  const startString = formatDate(start, 'YYYY-MM-DD') // 转换为 YYYY-MM-DD  格式
  const endString = formatDate(end, 'YYYY-MM-DD')
  const data = {
    startTime: startString,
    endTime: endString,
    lineIds: monitorIds,
    operateType: type
  }
  addRunTest(data).then((res: any) => {
    if (res.code === 'A0000') {
      ElMessage({
        message: '发起试运行成功',
        type: 'success'
      })
      tableStore.index()
    }
  })
}
</script>

<style scoped lang="scss"></style>
