<template>
    <el-dialog
        v-model="dialogFormVisible"
        :title="title"
        width="65%"
        :append-to-body="true"
        :before-close="close"
        :close-on-click-modal="false"
        :lazy="true"
        draggable
        custom-class="fixed-dialog"
    >
        <el-form
            :model="form"
            :validate-on-rule-change="false"
            :scroll-to-error="true"
            :rules="rules"
            ref="ruleFormRef"
            label-width="auto"
            class="form-two"
        >
            <el-form-item for="-" label="计划名称：" prop="workPlanName">
                <el-input v-model="form.workPlanName" autocomplete="off" placeholder="请输入计划名称" />
            </el-form-item>
            <el-form-item for="-" label="监督单位：" prop="supvOrgId">
                <Area ref="areaRef" v-model="form.supvOrgId" />
            </el-form-item>
            <el-form-item for="-" label="计划编制单位：" prop="planOrgId">
                <Area ref="areaRef" v-model="form.planOrgId" />
            </el-form-item>
            <el-form-item for="-" label="监督类型：" prop="supvType">
                <el-select v-model="form.supvType" clearable style="width: 100%" placeholder="请选择监督类型" filterable>
                    <el-option
                        v-for="item in supvTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="监督阶段：" prop="supvStage">
                <el-select v-model="form.supvStage" clearable style="width: 100%" placeholder="请选择监督阶段" filterable>
                    <el-option
                        v-for="item in supvStageList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="计划监督时间：" prop="planSupvDate">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.planSupvDate"
                    type="datetime"
                    format="YYYY-MM-DD hh:mm:ss"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    placeholder="请选择计划监督时间"
                />
            </el-form-item>
            <el-form-item for="-" label="监督对象类型：" prop="supvObjType">
                <el-select v-model="form.supvObjType" clearable style="width: 100%" placeholder="请选择监督对象类型" filterable>
                    <el-option
                        v-for="item in supvObjTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="监督对象名称：" prop="supvObjName">
                <el-input v-model="form.supvObjName" autocomplete="off" placeholder="请输入监督对象名称" />
            </el-form-item>
            <el-form-item for="-" label="监督对象电压等级：" prop="objVoltageLevel">
                <el-select
                    v-model="form.objVoltageLevel"
                    clearable
                    style="width: 100%"
                    placeholder="请选择监督对象电压等级"
                    filterable
                >
                    <el-option
                        v-for="item in voltageLevelList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="监督对象属性：" prop="objType">
                <el-select v-model="form.objType" clearable style="width: 100%" placeholder="请选择监督对象属性" filterable>
                    <el-option
                        v-for="item in objTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="监督对象属性名称：" prop="objTypeName">
                <el-input v-model="form.objTypeName" autocomplete="off" placeholder="请输入监督对象属性名称" />
            </el-form-item>
            <el-form-item for="-" label="监督对象协议容量：" prop="objCapacity">
                <el-input
                    oninput="value=value.replace(/[^0-9.]/g,'')"
                    v-model="form.objCapacity"
                    autocomplete="off"
                    placeholder="请输入监督对象监督对象协议容量"
                >
                    <template #append>MVA</template>
                </el-input>
            </el-form-item>
            <el-form-item for="-" label="监督对象关联电站：" prop="substationName">
                <el-input v-model="form.substationName" autocomplete="off" placeholder="请输入监督对象关联电站" />
            </el-form-item>
            <el-form-item for="-" label="监督对象关联电站电压等级：" prop="substationVoltageLevel">
                <el-select
                    v-model="form.substationVoltageLevel"
                    clearable
                    style="width: 100%"
                    placeholder="请选择监督对象关联电站电压等级"
                    filterable
                >
                    <el-option
                        v-for="item in voltageLevelList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="实施状态：" prop="effectStatus">
                <el-select v-model="form.effectStatus" clearable style="width: 100%" placeholder="请选择实施状态" filterable>
                    <el-option
                        v-for="item in effectStatusList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="实施人员：">
                <el-select v-model="form.effectUserId" clearable style="width: 100%" placeholder="请选择实施人员" filterable>
                    <el-option
                        v-for="item in effectUserIdList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="开始实施时间：">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.effectStartTime"
                    type="datetime"
                    format="YYYY-MM-DD hh:mm:ss"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    placeholder="请选择开始实施时间"
                />
            </el-form-item>
            <el-form-item for="-" label="结束实施时间：">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.effectEndTime"
                    type="datetime"
                    format="YYYY-MM-DD hh:mm:ss"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    placeholder="请选择结束实施时间"
                />
            </el-form-item>
            <el-form-item for="-" label="报告出具时间：">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.reportIssueTime"
                    type="datetime"
                    format="YYYY-MM-DD hh:mm:ss"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    placeholder="请选择报告出具时间"
                />
            </el-form-item>
            <el-form-item for="-" label="电能质量问题发生时间：">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.problemOcTime"
                    type="datetime"
                    format="YYYY-MM-DD hh:mm:ss"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    placeholder="请选择电能质量问题发生时间"
                />
            </el-form-item>
            <el-form-item for="-" label="计划状态：">
                <el-select v-model="form.planStatus" clearable style="width: 100%" placeholder="请选择计划状态" filterable  >
                    <el-option
                        v-for="item in planStatusList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="其他要求：" style="width: 100%">
                <el-input
                    type="textarea"
                    v-model="form.otherRemark"
                    autocomplete="off"
                    placeholder="请输入其他要求"
                    style="width: 100%"
                />
            </el-form-item>
            <el-form-item
                for="-"
                v-if="false"
                label="盖章报告："
                class="uploadFile"
                prop="informationSecurityTestReport"
            >
                <el-upload
                    v-model:file-list="form.informationSecurityTestReport"
                    ref="uploadRef"
                    action=""
                    :accept="acceptType"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="choose"
                    :auto-upload="false"
                    :on-progress="uploadFileName('informationSecurityTestReport')"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="false"
                label="佐证材料："
                class="uploadFile"
                prop="acceptanceInspectionReportSingle"
            >
                <el-upload
                    v-model:file-list="form.acceptanceInspectionReportSingle"
                    ref="uploadRef"
                    action=""
                    :accept="acceptType"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="choose"
                    :auto-upload="false"
                    :on-progress="uploadFileName('acceptanceInspectionReportSingle')"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="false"
                label="计划变更材料："
                class="uploadFile"
                prop="acceptanceInspectionReport"
            >
                <el-upload
                    v-model:file-list="form.acceptanceInspectionReport"
                    ref="uploadRef"
                    action=""
                    :accept="acceptType"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="choose"
                    :auto-upload="false"
                    :on-progress="uploadFileName('acceptanceInspectionReport')"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="false"
                label="告预警单材料："
                class="uploadFile"
                prop="typeExperimentReport"
                :show-message="false"
            >
                <el-upload
                    v-model:file-list="form.typeExperimentReport"
                    ref="uploadRef"
                    action=""
                    :accept="acceptType"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="choose"
                    :auto-upload="false"
                    :on-progress="uploadFileName('typeExperimentReport')"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="false"
                label="告预警单反馈材料："
                class="uploadFile"
                prop="factoryInspectionReport"
            >
                <el-upload
                    v-model:file-list="form.factoryInspectionReport"
                    ref="uploadRef"
                    action=""
                    :accept="acceptType"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="choose"
                    :auto-upload="false"
                    :on-progress="uploadFileName('factoryInspectionReport')"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="false"
                label="评估报告："
                class="uploadFile"
                prop="performanceTestReport"
                :show-message="false"
            >
                <el-upload
                    v-model:file-list="form.performanceTestReport"
                    ref="uploadRef"
                    action=""
                    :accept="acceptType"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="choose"
                    :auto-upload="false"
                    :on-progress="uploadFileName('performanceTestReport')"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close()">取消</el-button>
                <el-button type="primary" @click="confirmForm()">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, onMounted, defineExpose, defineEmits, watch } from 'vue'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { genFileId, ElMessage } from 'element-plus'
import { useDictData } from '@/stores/dictData'
import { useAdminInfo } from '@/stores/adminInfo'
import { uploadFile } from '@/api/system-boot/file'
import {
    addPlanFormData,
    getUserByDeptId,
    getPlanDetailsById,
    updatePlanFormData
} from '@/api/supervision-boot/plan/index'
import Area from '@/components/form/area/index.vue'
const emits = defineEmits(['onSubmit'])
const dictData = useDictData()
const dialogFormVisible = ref(false)
const form: any = ref({})
const title = ref('')
const ruleFormRef = ref(null)
// .xls,.xlsx
const acceptType = ''
//获取登陆用户姓名和部门
const adminInfo = useAdminInfo()
//字典获取监督类型
const supvTypeList = dictData.getBasicData('supv_type')
//字典获取监督阶段
const supvStageList = dictData.getBasicData('supv_stage')
//字典获取监督对象类型
const supvObjTypeList = dictData.getBasicData('supv_obj_type')
//字典获取实施状态
const effectStatusList = dictData.getBasicData('effect_status')
//字典获取计划状态
const planStatusList = dictData.getBasicData('plan_status')
//字典获取电压等级
const voltageLevelList = dictData.getBasicData('Dev_Voltage_Stand')
//监督对象属性
const objTypeList = [
    {
        id: '1',
        name: '在运站'
    },
    {
        id: '2',
        name: '新（改、扩）建站'
    }
]
const effectUserIdList: any = ref([])
//根据当前登陆用户的部门id查询实施人员
const getEffectUserList = () => {
    getUserByDeptId({ deptId: adminInfo.$state.deptId }).then(res => {
        effectUserIdList.value = res.data
    })
}
getEffectUserList()
const resetForm = () => {
    form.value = {
        workPlanName: '', //计划名称
        supvOrgId: '', //监督单位
        planOrgId: '', //计划编制单位
        supvType: supvTypeList[0].id, //监督类型
        supvStage: supvStageList[0]?.id, //监督阶段
        planSupvDate: '', //计划监督时间
        supvObjType: supvObjTypeList[0]?.id, //监督对象类型
        supvObjName: '', //监督对象名称
        objVoltageLevel: voltageLevelList[0].id, //	监督对象电压等级
        objType: objTypeList[0].id, //监督对象属性
        objTypeName: '', //监督对象属性名称
        objCapacity: '0', //监督对象协议容量
        substationName: '', //监督对象关联电站
        substationVoltageLevel: voltageLevelList[0].id, //	监督对象关联电站电压等级
        effectStatus: effectStatusList[0].id, //实施状态
        effectStartTime: '', //开始实施时间
        effectEndTime: '', //结束实施时间
        reportIssueTime: '', //报告出具时间
        problemOcTime: '', //电能质量问题发生时间
        effectUserId: effectUserIdList.value[0]?.id, //实施人员
        planStatus: planStatusList[0].id, //计划状态
        otherRemark: '', //其他要求
        planUserId: '' //计划编制人,挡墙登陆用户
        // sealReport: '', //盖章报告
        // evidenceMaterials:'', //佐证材料
        // planChangeMaterials: '', //计划变更材料
        // alarmMaterials:'', //告预警单材料
        // alarmFeedbackMaterials: '', //告预警单反馈材料
        // assessReport:'' //评估报告
    }
}
//初始化数据
resetForm()
//定义校验规则
const rules = ref({
    //基础信息
    workPlanName: [
        {
            required: true,
            message: '请输入计划名称',
            trigger: 'blur'
        }
    ],
    supvOrgId: [
        {
            required: true,
            message: '请选择监督单位',
            trigger: 'change'
        }
    ],
    planOrgId: [
        {
            required: true,
            message: '请选择计划编制单位',
            trigger: 'change'
        }
    ],
    supvType: [
        {
            required: true,
            message: '请选择监督类型',
            trigger: 'change'
        }
    ],
    supvStage: [
        {
            required: true,
            message: '请选择监督阶段',
            trigger: 'change'
        }
    ],
    planSupvDate: [
        {
            required: true,
            message: '请选择计划监督时间',
            trigger: 'change'
        }
    ],
    supvObjType: [
        {
            required: true,
            message: '请选择监督对象类型',
            trigger: 'change'
        }
    ],
    supvObjName: [
        {
            required: true,
            message: '请输入监督对象名称',
            trigger: 'blur'
        }
    ],
    objVoltageLevel: [
        {
            required: true,
            message: '请选择监督对象电压等级',
            trigger: 'change'
        }
    ],
    objType: [
        {
            required: true,
            message: '请选择监督对象属性',
            trigger: 'change'
        }
    ],
    objTypeName: [
        {
            required: false,
            message: '请输入监督对象属性名称',
            trigger: 'blur'
        }
    ],
    objCapacity: [
        {
            required: true,
            message: '请输入监督对象监督对象协议容量',
            trigger: 'blur'
        }
    ],
    substationName: [
        {
            required: true,
            message: '请输入监督对象关联电站',
            trigger: 'blur'
        }
    ],
    substationVoltageLevel: [
        {
            required: true,
            message: '请选择监督对象关联电站电压等级',
            trigger: 'change'
        }
    ],
    effectStatus: [
        {
            required: true,
            message: '请选择实施状态',
            trigger: 'change'
        }
    ]
})
watch(
    () => form.value,
    (val, oldVal) => {},
    {
        deep: true,
        immediate: true
    }
)
const resendId = ref('')
const open = (row: any) => {
    title.value = row.title
    dialogFormVisible.value = true
    if (row.row) {
        resendId.value = row.row.planId
        getPlanDetailsById({ id: row.row.planId }).then(res => {
            form.value = res.data
        })
    } else {
        resendId.value = ''
    }
}
const close = () => {
    //重置表单内容
    //取消表单校验状态
    ruleFormRef.value && ruleFormRef.value.resetFields()
    dialogFormVisible.value = false
    emits('onSubmit')
    resetForm()
}
onMounted(() => {
    console.log()
})
// 上传报告
const uploadRef = ref()
const handleExceed: UploadProps['onExceed'] = files => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
}
let uploadName = ref('')
//上传报告改变
const uploadFileName = val => {
    uploadName.value = val
}
// 盖章报告
const sealReport = ref('')
// 佐证材料
const evidenceMaterials = ref('')
// 计划变更材料
const planChangeMaterials = ref('')
//告预警单材料
const alarmMaterials = ref('')
//告预警单反馈材料
const alarmFeedbackMaterials = ref('')
//评估报告
const assessReport = ref('')
const choose = (e: any) => {
    uploadFile(e.raw, '/supervision/').then(res => {
        //盖章报告
        if (uploadName.value == 'sealReport') {
            sealReport.value = res.data.name
        }
        //佐证材料
        else if (uploadName.value == 'evidenceMaterials') {
            evidenceMaterials.value = res.data.name
        }
        //计划变更材料
        else if (uploadName.value == 'planChangeMaterials') {
            planChangeMaterials.value = res.data.name
        }
        //告预警单材料
        else if (uploadName.value == 'alarmMaterials') {
            alarmMaterials.value = res.data.name
        }
        //告预警单反馈材料
        else if (uploadName.value == 'alarmFeedbackMaterials') {
            alarmFeedbackMaterials.value = res.data.name
        }
        //评估报告
        else if (uploadName.value == 'assessReport') {
            assessReport.value = res.data.name
        }
    })
}
//设置监督类型时间选择范围不能<今天
const disabledDate = time => {
    return time.getTime() < Date.now() - 8.64e7 // 8.64e7 毫秒数代表一天
}
//提交
const confirmForm = () => {
    // 提交终端信息
    ruleFormRef.value.validate(valid => {
        if (valid) {
            form.value.planUserId = adminInfo.$state.id
            let confirmFormData = JSON.parse(JSON.stringify(form.value))
            //提交终端信息
            // confirmFormData = {
            //     ...confirmFormData,
            //     sealReport: sealReport?.value, //盖章报告
            //     evidenceMaterials: evidenceMaterials.value, //佐证材料
            //     planChangeMaterials: planChangeMaterials.value, //计划变更材料
            //     alarmMaterials: alarmMaterials.value, //告预警单材料
            //     alarmFeedbackMaterials: alarmFeedbackMaterials.value, //告预警单反馈材料
            //     assessReport: assessReport.value //评估报告
            // }
            if (title.value == '技术监督计划') {
                addPlanFormData(confirmFormData).then(res => {
                    if (res.code == 'A0000') {
                        ElMessage({
                            message: '新建技术监督计划成功',
                            type: 'success'
                        })
                        ruleFormRef.value.resetFields()
                        resetForm()
                        close()
                    }
                })
            } else {
                console.log(confirmFormData)
                confirmFormData.id = resendId.value
                confirmFormData.planSupvDate = confirmFormData.planSupvDate.replace('T', ' ')
                updatePlanFormData(confirmFormData).then(res => {
                    if (res.code == 'A0000') {
                        ElMessage({
                            message: '重新发起成功',
                            type: 'success'
                        })
                        ruleFormRef.value.resetFields()
                        resetForm()
                        close()
                    }
                })
            }
        } else {
            console.log('表单验证失败')
            return false
        }
    })
}
defineExpose({ open })
</script>
<style lang="scss" scoped></style>
