<template>
    <TableHeader area datePicker nextFlag theCurrentTime ref="TableHeaderRef">
        <template #select>
            <el-form-item label="搜索">
                <el-input v-model="tableStore.table.params.searchValue" placeholder="输入变电站、终端名称"
                clearable maxlength="32"  show-word-limit style="width: 180px"></el-input>
            </el-form-item>
            <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>
        </template>
        <template #operation>
            <el-button icon="el-icon-Plus" type="primary" @click="addFormModel">新增</el-button>
            <el-button icon="el-icon-Delete" type="primary" @click="deleteEven">删除</el-button>
            <el-button icon="el-icon-Download" type="primary" @click="exportExcelTemplate"
                :loading="loading">模版下载</el-button>
            <el-button icon="el-icon-Upload" type="primary" @click="importUserData">批量导入</el-button>
        </template>
    </TableHeader>
    <Table ref="tableRef" :checkbox-config="checkboxConfig" />

    <!-- 新增弹框 -->
    <addForm ref="addForms" @onSubmit="tableStore.index()"></addForm>
    <!-- 上传模版 -->
    <uploadATemplate ref="uploadATemplateRef" />

    <!-- 上传模版 详情 -->
    <el-dialog title="详情" width="80%" v-model="dialogShow" v-if="dialogShow">
        <DetailInfo :id="userId"></DetailInfo>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, watch } 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 { downloadDevTemplate } from '@/api/supervision-boot/userReport/form'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus/es'
import DetailInfo from '@/views/pqs/supervise/terminalNetworkDetection/components/terminainal/detail.vue'
import { cancelTerminalFormData, getTerminalDetailsById } from '@/api/supervision-boot/terminal/index'
import uploadATemplate from './uploadATemplate.vue'
import addForm from './addForm.vue'
import { useAdminInfo } from '@/stores/adminInfo'
import { deleteDevReport } from '@/api/supervision-boot/delete/index'
import { getUserReportById } from "@/api/supervision-boot/interfere";
//获取登陆用户姓名和部门
const adminInfo = useAdminInfo()
const dictData = useDictData()
const { push, options, currentRoute } = useRouter()
const TableHeaderRef = ref()
const userId = ref()
const loading = ref(false)
const tableRef = ref()
const areaOptionList = dictData.getBasicData('jibei_area')
const statusSelect = dictData.statusSelect()
const ruleFormRef = ref()
const uploadATemplateRef = ref()
const show: any = ref(false)
const fileList = ref([])
const dialogShow = ref(false)
const flag = ref(false)
const tableStore = new TableStore({
    url: '/supervision-boot/deVReport/list',
    publicHeight: 65,
    method: 'POST',
    column: [
        {
            width: '60',
            type: 'checkbox'
        },
        { title: '序号', width: 80,formatter: (row: any) => {
        return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
      } },
        {
            field: 'orgName',
            title: '填报部门名称',
            minWidth: 170,
            formatter: (row: any) => {
                row.cellValue = row.cellValue ? row.cellValue : ''
                return row.cellValue
            }
        },
        {
            field: 'substationName',
            title: '所属变电站',
            minWidth: 170,
            formatter: (row: any) => {
                row.cellValue = row.cellValue ? row.cellValue : '/'
                return row.cellValue
            }
        },
        { field: 'monitoringTerminalName', title: '终端名称', minWidth: 170 },
        { field: 'monitoringTerminalCode', title: '终端编号', minWidth: 170 },
        { field: 'reportDate', title: '填报日期', minWidth: 170 },
        {
            field: 'createBy',
            title: '填报人',
            minWidth: 80,
            formatter: (row: any) => {
                return dictData.state.userList.filter(item => item.id == row.cellValue)[0]?.name
            }
        },
        {
            field: 'status',
            title: '流程状态',
            minWidth: 100,
            render: 'tag',
            custom: {
                0: 'warning',
                1: 'primary',
                2: 'success',
                3: 'danger',
                4: 'warning'
            },
            replaceValue: {
                0: '待提交审批',
                1: '审批中',
                2: '审批通过',
                3: '审批不通过',
                4: '已取消'
            }
        },
        {
            title: '操作',
            minWidth: 150,
            fixed: 'right',
            render: 'buttons',
            buttons: [
                {
                    name: 'productSetting',
                    title: '流程详情',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    disabled: row => {
                        return row.importType != 0 || !row.processInstanceId
                    },
                    click: row => {
                        flag.value = true
                        handleAudit(row.processInstanceId, row.historyInstanceId)
                    }
                },

                {
                    name: 'productSetting',
                    title: '详情',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    disabled: row => {
                        return row.importType != 1
                    },
                    click: row => {
                        userId.value = row.id
                        dialogShow.value = true
                    }
                },

                {
                    name: 'edit',
                    title: '编辑',
                    type: 'primary',
                    icon: 'el-icon-Open',
                    render: 'basicButton',
                    showDisabled: row => {
                        return row.importType == 1 ? false : row.createBy != adminInfo.$state.id || !(row.status == 0)
                    },
                    disabled: row => {
                        return row.importType == 1 ? false : !(row.status == 0)
                    },
                    click: row => {
                        addForms.value.open({
                            title: '编辑',
                            row: row
                        })
                    }
                },
                {
                    name: 'edit',
                    title: '重新发起',
                    type: 'warning',
                    icon: 'el-icon-Open',
                    render: 'basicButton',
                    disabled: row => {
                        return row.createBy != adminInfo.$state.id || !(row.status == 3 || row.status == 4)
                    },
                    click: row => {
                        addForms.value.open({
                            title: '重新发起',
                            row: row
                        })
                    }
                },
                {
                    name: 'cancel',
                    title: '取消',
                    type: 'danger',
                    icon: 'el-icon-Open',
                    render: 'basicButton',
                    disabled: row => {
                        return row.createBy != adminInfo.$state.id || row.status != 1
                    },
                    click: row => {
                        cancelLeave(row)
                    }
                }
            ]
        }
    ],

    beforeSearchFun: () => {
        tableStore.table.params.orgNo = tableStore.table.params.deptIndex
        // tableStore.table.params.relationUserName = tableStore.table.params.userName
    }
})
tableStore.table.params.status = ''
tableStore.table.params.searchValue = ''
// tableStore.table.params.loadType = ''
// tableStore.table.params.userName = ''
// tableStore.table.params.fileUploadflag = ''

provide('tableStore', tableStore)

const addForms = ref()
const addFormModel = () => {
    setTimeout(() => {
        addForms.value.open({
            title: '终端信息'
        })
    }, 0)
}
/**取消流程操作*/
const cancelLeave = async (row: any) => {
    // 二次确认
    const { value } = await ElMessageBox.prompt('请输入取消原因', '取消流程', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
        inputErrorMessage: '取消原因不能为空'
    })
    // 发起取消
    let data = {
        id: row.id,
        processInstanceId: row.processInstanceId,
        reason: value
    }
    await cancelTerminalFormData(data)
    ElMessage.success('取消成功')
    // 加载数据
    tableStore.index()
}
// 禁止点击
const checkboxConfig = reactive({
    checkMethod: ({ row }) => {
        return adminInfo.roleCode.includes('delete_info')
            ? true
            : row.createBy == adminInfo.$state.id && row.status == 0
    }
})
const deleteEven = () => {
    if (tableStore.table.selection.length == 0) {
        ElMessage({
            type: 'warning',
            message: '请选择要删除的数据'
        })
    } else {
        ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                deleteDevReport(tableStore.table.selection.map(item => item.id)).then(res => {
                    ElMessage({
                        type: 'success',
                        message: '删除成功!'
                    })
                    tableStore.index()
                })
            })




    }
}

//导出模板
const exportExcelTemplate = async () => {
    loading.value = true
    downloadDevTemplate().then((res: any) => {
        let blob = new Blob([res], {
            type: 'application/vnd.ms-excel'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '终端入网检测模板'
        document.body.appendChild(link)
        link.click()
        link.remove()
    })
    await setTimeout(() => {
        loading.value = false
    }, 0)
}
//批量导入用户数据
const importUserData = () => {
    uploadATemplateRef.value.open('导入终端入网检测')
}
onMounted(() => {
    tableStore.index()
})

watch(
    () => currentRoute.value.path,
    () => {
        if (flag.value && options.history.state.forward?.split('/')[1] == 'bpm') {
            tableStore.index()
            flag.value = false
        }
    },
    {
        deep: true
    }
)
/** 处理审批按钮 */
const handleAudit = (instanceId: any, historyInstanceId: any) => {
    push({
        name: 'BpmProcessInstanceDetail',
        state: {
            id: instanceId,
            historyInstanceId
        }
    })
}

const props = defineProps({ id: { type: String, default: 'null' } })
watch(() => props.id, async (newValue, oldValue) => {
    if (newValue === 'null') return // 直接返回，避免后续逻辑执行
    const fullId = newValue.split('@')[0]
    let nowTime = Date.now()
    const routeTime = Number(newValue.split('@')[1])
    if (isNaN(routeTime) || nowTime - routeTime > import.meta.env.VITE_ROUTE_TIME_OUT) return // 路由时间超过500ms，则不执行
    await getTerminalDetailsById({ id: fullId }).then(res => {
        if (res && res.code == 'A0000') {
            addForms.value.open({
                title: '重新发起',
                row: res.data
            })
        }
    })
}, { immediate: true })

</script>

<style scoped lang="scss">
:deep(.el-upload-list__item) {
    width: 400px;
}

::v-deep .el-input__wrapper {
    // width: 200px !important;
}
</style>
