<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>
        <!--监测点信息录入 基础信息+监测点信息  监测点信息要有用户名称、用户状态 -->
        <el-form :model="form" :validate-on-rule-change="false" :scroll-to-error="true" :rules="rules" ref="ruleFormRef"
            label-width="auto" label-position="right" class="form-two">
            <div class="fixed_upload" v-if="false">
                <el-upload v-model:file-list="form.lineFilePath" ref="uploadRef" action="" accept=".xls,.xlsx"
                    :limit="1" :on-exceed="handleExceed" :on-change="choose" :auto-upload="false"
                    :on-progress="uploadFileName('lineFilePath')" :on-remove="removeFile">
                    <template #trigger>
                        <el-button type="primary">监测点台账信息</el-button>
                    </template>
                </el-upload>
            </div>
            <!-- 基础信息 -->
            <el-form-item v-if="false" for="-" label="填报人：" prop="reporterName">
                <el-input v-model="form.reporterName" autocomplete="off" placeholder="请输入填报人" :disabled="true" />
            </el-form-item>
            <el-form-item v-if="false" for="-" label="填报日期：" prop="reportDate">
                <el-date-picker style="width: 100%" v-model="form.reportDate" :disabled="true" type="date"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择填报日期" />
            </el-form-item>
            <el-form-item v-if="false" for="-" label="填报部门：" prop="orgId">
                <el-input v-model="form.orgName" :disabled="true" autocomplete="off" />
            </el-form-item>
            <el-form-item v-if="false" for="-" label="工程投产日期：" prop="expectedProductionDate">
                <el-date-picker style="width: 100%" v-model="form.expectedProductionDate" type="date"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" :disabled="true" :disabled-date="disabledDate"
                    placeholder="请选择工程投产日期" />
            </el-form-item>
            <el-form-item v-if="false" for="-" label="所在地市：" prop="city">
                <el-select v-model="form.city" clearable style="width: 100%" :disabled="true" placeholder="请选择所在地市" filterable>
                    <el-option v-for="item in areaOptionList" :key="item.id" :label="item.name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-if="false" for="-" label="用户状态：" prop="userStatus">
                <el-select v-model="form.userStatus" placeholder="请选择用户状态" :disabled="true" style="width: 100%" filterable>
                    <el-option v-for="(item, index) in userStateList" :label="item.name" :value="item.id"
                        :disabled="item.name != '建设'" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="关联干扰源：" prop="userName">
                <el-select v-model="form.userName" clearable style="width: 100%" placeholder="请选择关联干扰源"
                    @change="changeUserName" filterable>
                    <el-option v-for="(item, index) in userNameList" :key="index" :label="item.projectName"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="关联终端：" prop="monitoringTerminalCode">
                <el-select v-model="form.monitoringTerminalCode" clearable style="width: 100%" filterable
                    placeholder="请选择关联终端" @change="changeDevice" >
                    <el-option v-for="(item, index) in monitoringTerminalList" :key="index"
                        :label="item.monitoringTerminalCode" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="接入母线：" prop="connectedBus">
                <el-input v-model="form.connectedBus" autocomplete="off" placeholder="请输入接入母线 如：110kV4母线" />
            </el-form-item>
            <el-form-item for="-" label="监测点运行状态：" prop="operationStatus">
                <el-select v-model="form.operationStatus" placeholder="请选择运行状态" filterable>
                    <el-option v-for="(item, index) in operationStatusList" :label="item.name" :value="item.id"
                        :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="监测点名称：" prop="lineName">
                <el-input v-model="form.lineName" autocomplete="off" placeholder="请输入监测点名称" clearable maxlength="32" show-word-limit/>
            </el-form-item>
            <!-- {{ voltageLevelList[2].value * 10 }}:{{ 1 }} -->
            <el-form-item for="-" label="监测点电压等级：" prop="voltageLevel">
                <el-select v-model="form.voltageLevel" clearable style="width: 100%" placeholder="请选择监测点电压等级" 
                    @change="changevoltageDeviationLimit" 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="PT变比：" prop="pt1">
                <el-input style="width: 48%" v-model="form.pt1" autocomplete="off" placeholder="请输入PT变比"
                    oninput="value=value.replace(/[^0-9.]/g,'')" />
                <el-input style="width: 48%" v-model="form.pt2" autocomplete="off" placeholder="请输入PT变比"
                    oninput="value=value.replace(/[^0-9.]/g,'')" />
            </el-form-item>

            <el-form-item for="-" label="CT变比：" prop="ct1">
                <el-input v-model="form.ct1" style="width: 48%" autocomplete="off"
                    oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入CT变比" />
                <el-input v-model="form.ct2" style="width: 48%" autocomplete="off"
                    oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入CT变比" />
            </el-form-item>
            <el-form-item for="-" label="短路容量：" prop="shortCapacity">
                <el-input v-model="form.shortCapacity" autocomplete="off" oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')" placeholder="请输入短路容量">
                    <template #append>MVA</template>
                </el-input>
            </el-form-item>
            <el-form-item for="-" label="协议容量：" prop="dealCapacity">
                <el-input v-model="form.dealCapacity" autocomplete="off" oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')" placeholder="请输入协议容量">
                    <template #append>MVA</template>
                </el-input>
            </el-form-item>
            <el-form-item for="-" label="终端容量：" prop="devCapacity">
                <el-input v-model="form.devCapacity" autocomplete="off" oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')" placeholder="请输入终端容量">
                    <template #append>MVA</template>
                </el-input>
            </el-form-item>
            <el-form-item for="-" label="基准容量：" prop="standardCapacity">
                <el-input v-model="form.standardCapacity" autocomplete="off" oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')" placeholder="请输入基准容量">
                    <template #append>MVA</template>
                </el-input>
            </el-form-item>
            <el-form-item for="-" label="干扰源类型：" prop="loadType">
                <el-select v-model="form.loadType" style="width: 100%" placeholder="请选择干扰源类型" @change="changeLoadType" filterable>
                    <el-option v-for="item in loadTypeList" :key="item.id" :label="item.name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="干扰源类别：" prop="businessType">
                <el-select v-model="form.businessType" style="width: 100%" placeholder="请选择干扰源类别" filterable>
                    <el-option v-for="item in businessTypeList" :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.ptType" clearable style="width: 100%" placeholder="请选择接线方式" filterable>
                    <el-option v-for="item in ptTypeList" :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.num" clearable style="width: 100%" placeholder="请选择线路号" filterable>
                    <el-option v-for="item in numList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="电压偏差上限：" prop="voltageDeviationUpperLimit">
                <el-input-number style="width: 100%" v-model="form.voltageDeviationUpperLimit" />
            </el-form-item>
            <el-form-item for="-" label="电压偏差下限：" prop="voltageDeviationLowerLimit">
                <el-input-number style="width: 100%" v-model="form.voltageDeviationLowerLimit" />
            </el-form-item>
            <el-form-item for="-" label="测量间隔：" prop="timeInterval">
                <el-select v-model="form.timeInterval" placeholder="请选择测量间隔" filterable>
                    <el-option v-for="(item, index) in timeIntervalList" :label="item.name" :value="item.id"
                        :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="上送网公司编码：">
                <el-input v-model="form.lineId" autocomplete="off" placeholder="请输入上送网公司编码"  clearable maxlength="32" show-word-limit/>
            </el-form-item>
            <el-form-item for="-" label="监测点性质：" prop="pointNature">
                <el-select v-model="form.pointNature" placeholder="请选择监测点性质" filterable>
                    <el-option v-for="(item, index) in pointNatureList" :label="item.name" :value="item.id"
                        :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="是否参与统计：" prop="isStatistical">
                <el-radio-group v-model="form.isStatistical">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- <el-form-item for="-" label="对象名称(对端)：" prop="objName">
                <el-input v-model="form.objName" autocomplete="off" placeholder="请输入监测点对象名称" />
            </el-form-item> -->
            <el-form-item for="-" label="电网侧变电站：" prop="powerSubstationName">
                <el-input v-model="form.powerSubstationName" autocomplete="off" placeholder="请输入电网侧变电站"  clearable maxlength="32" show-word-limit/>
            </el-form-item>
            <el-form-item for="-" label="是否并网点：" prop="isGridConnectionPoint">
                <el-radio-group v-model="form.isGridConnectionPoint">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item for="-" label="主接线图：" prop="mainWiringDiagram" class="uploadFile">
                <el-upload v-model:file-list="form.mainWiringDiagram" ref="uploadRef" action="" :accept="acceptType"
                    :limit="1" :on-exceed="handleExceed" :on-change="choose" :auto-upload="false"
                    :on-progress="uploadFileName('mainWiringDiagram')" :on-remove="removeFile">
                    <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(true)" :loading="loading">保存</el-button>
                <el-button type="primary" @click="confirmForm(false)" :loading="loading">提交审批</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, defineExpose, nextTick, defineEmits, watch, onUnmounted } 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 { getTempLineDetailsById } from '@/api/supervision-boot/monitorpoint/index'
import { getDeviceList } from '@/api/supervision-boot/terminal/index'
import { addMointorPointFormData, getList, updateMointorPointFormData } from '@/api/supervision-boot/monitorpoint/index'
import { queryByAllCode } from '@/api/system-boot/dictTree'
import { getUserReportById } from '@/api/supervision-boot/userReport/form'
import { getDictTreeById } from '@/api/system-boot/dictTree'
import { use } from 'vxe-table'
const emits = defineEmits(['onSubmit'])
const dictData = useDictData()
const dialogFormVisible = ref(false)
const form: any = ref({})
const title = ref('')
const loading = ref(false)
const ruleFormRef: any = ref(null)
// acceptType .doc,.docx,.xlsx,.xls,.pdf
const acceptType = ''
//字典获取所在地市
const areaOptionList = dictData.getBasicData('jibei_area')
//字典获取监测点电压等级
const voltageLevelList = dictData.getBasicData('Dev_Voltage_Stand')
//用户状态数组
const userStateList = reactive([
    {
        name: '可研',
        id: '0'
    },
    {
        name: '建设',
        id: '1'
    },
    {
        name: '运行',
        id: '2'
    },
    {
        name: '退运',
        id: '3'
    }
])
//定义监测点性质下拉框数据
const pointNatureList = [
    {
        id: '0',
        name: '电网侧'
    },
    {
        id: '1',
        name: '非电网侧'
    }
]
//定义监测点运行状态下拉框数据
const operationStatusList = [
    {
        id: '0',
        name: '运行'
    },
    {
        id: '1',
        name: '检修'
    },
    {
        id: '2',
        name: '停运'
    },
    {
        id: '3',
        name: '调试'
    },
    {
        id: '4',
        name: '退运'
    }
]
//定义接线方式下拉框数据
const ptTypeList = [
    {
        id: 0,
        name: '星型接法'
    },
    {
        id: 1,
        name: '三角型接法'
    },
    {
        id: 2,
        name: '开口三角型接法'
    }
]
//定义线路号下拉框数据
const numList = [
    {
        id: '1',
        name: '1'
    },
    {
        id: '2',
        name: '2'
    },
    {
        id: '3',
        name: '3'
    },
    {
        id: '4',
        name: '4'
    },
    {
        id: '5',
        name: '5'
    },
    {
        id: '6',
        name: '6'
    },
    {
        id: '7',
        name: '7'
    },
    {
        id: '8',
        name: '8'
    },
    {
        id: '9',
        name: '9'
    },
    {
        id: '10',
        name: '10'
    }
]
//测量间隔数据
const timeIntervalList = [
    {
        id: 1,
        name: '1分钟'
    },
    {
        id: 3,
        name: '3分钟'
    },
    {
        id: 5,
        name: '5分钟'
    },
    {
        id: 10,
        name: '10分钟'
    }
]
//获取登陆用户姓名和部门
const adminInfo = useAdminInfo()
//工程下拉选择数据
const userNameList = ref([])
//查询干扰源列表获取可选数据
const projectList = ref([])

const monitoringTerminalList: any = ref([])
//获取关联终端
const findAllMonitoringTerminalList = () => {
    getDeviceList().then(res => {
        monitoringTerminalList.value = res.data
    })
}
//查询关联终端下拉框
const changeDevice = () => {
    const obj = monitoringTerminalList.value.find(item => {
        return form.value.monitoringTerminalCode == item.id
    })
    form.value = {
        ...form.value,
        monitoringTerminalCode: obj.id,
        monitoringTerminalName: obj.monitoringTerminalName
    }
}
//定义切换form类型
const selectFormType = ref('')
selectFormType.value = '0'
const resetForm = async () => {
    form.value = {
        // reporter: '', //填报人
        // reporterName: '', //填报人名称
        reportDate: '', //填报日期
        orgId: '', //填报部门id
        orgName: '', //填报部门名称
        expectedProductionDate: '', //工程投产日期
        city: areaOptionList[0].name, //所在地市
        userStatus: userStateList[1].id, //用户状态
        monitoringTerminalCode: monitoringTerminalList.value[0]?.id, //关联终端
        monitoringTerminalName: monitoringTerminalList.value[0]?.monitoringTerminalName,
        userName: projectList.value[0]?.id, //用户名称关联干扰源
        userId: '', //工程id
        //监测点信息实体
        businessType: '', //	干扰源类别
        connectedBus: '', //	接入母线
        ct1: 300, //CT变比1
        ct2: 5, //CT变比2
        pt1: 1, //	PT变比1
        pt2: 1, //	PT变比2
        shortCapacity: 10, //	短路容量
        dealCapacity: 10, //协议容量
        devCapacity: 10, //终端容量
        standardCapacity: 10, //基准容量
        isGridConnectionPoint: 0, //是否并网点
        isStatistical: 0, //	是否参与统计
        lineId: '', //	监测点编码
        lineName: '', //	监测点名称
        loadType: '', //干扰源类型
        mainWiringDiagram: [], //	主接线图
        objName: '', //监测点对象名称
        operationStatus: operationStatusList[0].id, //监测点运行状态
        pointNature: pointNatureList[0].id, //监测点性质
        powerSubstationName: '', //电网侧变电站
        timeInterval: timeIntervalList[0].id, //测量间隔
        voltageDeviationLowerLimit: 0, //电压偏差下限
        voltageDeviationUpperLimit: 0, //	电压偏差上限
        voltageLevel: voltageLevelList[0].id, //监测点电压等级
        ptType: ptTypeList[0].id, //接线方式
        num: numList[0].id //线路号
    }
    await getList({}).then(res => {
        projectList.value = res.data
        userNameList.value = res.data
        //初始化
        let obj = res.data[0]
        if (title.value != '重新发起' && title.value != '编辑') {
            form.value = {
                ...form.value,
                // city: obj.city,
                // reporter: obj.reporter,
                // reporterName: obj.reporterName,
                reportDate: obj?.reportDate,
                orgId: obj?.orgId,
                orgName: obj?.orgName,
                expectedProductionDate: obj?.expectedProductionDate,
                userName: userNameList.value[0]?.id,
                userId: userNameList.value[0]?.id,
                objName: userNameList.value[0]?.projectName
            }
           
           changeUserName()
        }
    })
    if (title.value != '编辑') {
        changevoltageDeviationLimit()
    }
}
//根据检测点电压等级切换电压偏差上限/下限
const changevoltageDeviationLimit = async () => {
    let obj = voltageLevelList.find(item => {
        return item.id == form.value.voltageLevel
    })
    const val = obj?.value
    if (Number(val) > 35) {
        form.value.voltageDeviationUpperLimit = 10
        form.value.voltageDeviationLowerLimit = -10
    }
    if (Number(val) < 20) {
        form.value.voltageDeviationUpperLimit = 7
        form.value.voltageDeviationLowerLimit = -7
    }
    if (Number(val) < 0.22) {
        form.value.voltageDeviationUpperLimit = 7
        form.value.voltageDeviationLowerLimit = -10
    }
    //PT变比 电压<0.48kv 1:1 电压>0.48 *1000/100
    if (Number(val) <= 0.48) {
        form.value.pt1 = 1
        form.value.pt2 = 1
    }
    if (Number(val) > 0.48) {
        form.value.pt1 = val * 10
        form.value.pt2 = 1
    }

    if (Number(val) < 0.6) {
        form.value.standardCapacity = 10
    } else if (Number(val) < 20) {
        form.value.standardCapacity = 100
    } else if (Number(val) < 35) {
        form.value.standardCapacity = 200
    } else if (Number(val) < 66) {
        form.value.standardCapacity = 250
    } else if (Number(val) < 110) {
        form.value.standardCapacity = 500
    } else if (Number(val) < 220) {
        form.value.standardCapacity = 750
    } else if (Number(val) < 330) {
        form.value.standardCapacity = 2000
    } else if (Number(val) < 500) {
        form.value.standardCapacity = 3000
    } else if (Number(val) < 750) {
        form.value.standardCapacity = 4500
    } else if (Number(val) < 1000) {
        form.value.standardCapacity = 7000
    } else {
        form.value.standardCapacity = 9000
    }
}
findAllMonitoringTerminalList()
//获取树形图数据
const treeData: any = ref('')
//干扰源类型 取树形图第一层children数据
const loadTypeList: any = ref([])
//干扰源类别 取树形图第二层children数据
const businessTypeList: any = ref([])




const getTreeList = () => {
    queryByAllCode().then(res => {
        treeData.value = [res.data.find((item: any) => item.code == 'Major_Nonlinear_Device')]
        treeData.value[0].children.map((item: any) => {
            //干扰源类型数据
            loadTypeList.value.push({
                id: item?.id,
                name: item?.name,
                children: item?.children
            })
        })

        form.value.loadType = loadTypeList.value[0]?.id
    
        changeLoadType()
    })
}
getTreeList()




//选择干扰源类型的时候，干扰源类别数据跟随改变
const changeLoadType = async () => {

    businessTypeList.value = loadTypeList.value.find(item => {
        return item.id == form.value.loadType
    })?.children

form.value.businessType = businessTypeList.value[0]?.id
}
//选择关联干扰源回显数据
const changeUserName = () => {
   
    let obj: any = projectList.value.find((item: any) => {
        return form.value.userName == item.id
    })
   
    form.value = {
        ...form.value,
        city: obj?.city,
        reporter: obj?.reporter,
        reporterName: obj?.reporterName,
        reportDate: obj?.reportDate,
        orgId: obj?.orgId,
        orgName: obj?.orgName,
        userName: obj?.projectName,
        userId: obj?.id,
        expectedProductionDate: obj?.expectedProductionDate,
        objName: obj?.projectName,
        userStatus: obj?.userStatus + ''
    }

    //回显数据
    if (obj.userType == '2' || obj.userType == '3' || obj.userType == '4' || obj.userType == '5') {
        getUserReportById(obj.id).then(res => {
            const obj = res.data
            form.value = {
                ...form.value,
                shortCapacity: obj.userReportSubstationPO?.minShortCircuitCapacity, //	短路容量
                dealCapacity: obj.userReportSubstationPO?.userAgreementCapacity, //协议容量
                devCapacity: obj.userReportSubstationPO?.pccEquipmentCapacity, //终端容量
                standardCapacity: obj.userReportSubstationPO?.baseShortCircuitCapacity //基准容量
            }
            getDictTree(obj.userReportSubstationPO?.nonlinearLoadType)
        })
    } else if (obj.userType == '0' || obj.userType == '1') {
        getUserReportById(obj.id).then(res => {
            const obj = res.data
            form.value = {
                ...form.value,
                shortCapacity: 0, //	短路容量
                dealCapacity: obj.userReportProjectPO?.agreementCapacity, //协议容量
                devCapacity: 0, //终端容量
                standardCapacity: 10 //基准容量
            }
            getDictTree(obj.userReportProjectPO?.nonlinearDeviceType)
        })
    } else if (obj.userType == '6') {
        getUserReportById(obj.id).then(res => {
            const obj = res.data
            form.value = {
                ...form.value,
                shortCapacity: 0, //	短路容量
                dealCapacity: 0, //协议容量
                devCapacity: 0, //终端容量
                standardCapacity: 10 //基准容量
            }
            getDictTree()
        })
    }
}
const getDictTree = (e?: string) => {
   
    if (e) {
        getDictTreeById(e).then(res => {
            form.value.loadType = res.data.pids.split(',')[1] || ''
            form.value.businessType = res.data.pids.split(',')[2] || ''
     
            changeLoadType()
        })
    } else {
        form.value.businessType = ''
        form.value.loadType = ''
    
        businessTypeList.value = []
    }
}
//定义校验规则
const rules = ref({
    //基础信息
    reporterName: [
        {
            required: true,
            message: '请输入填报人',
            trigger: 'blur'
        }
    ],
    reportDate: [
        {
            required: true,
            message: '请选择填报日期',
            trigger: 'change'
        }
    ],
    orgId: [
        {
            required: true,
            message: '请选择填报部门',
            trigger: 'change'
        }
    ],
    expectedProductionDate: [
        {
            required: true,
            message: '请选择工程投产日期',
            trigger: 'change'
        }
    ],
    city: [
        {
            required: true,
            message: '请选择所在地市',
            trigger: 'change'
        }
    ],
    userStatus: [
        {
            required: true,
            message: '请选择用户状态',
            trigger: 'change'
        }
    ],
    userName: [
        {
            required: true,
            message: '请选择用户名称',
            trigger: 'change'
        }
    ],
    monitoringTerminalCode: [
        {
            required: true,
            message: '请选择关联终端',
            trigger: 'change'
        }
    ],
    //监测点信息
    lineName: [
        {
            required: true,
            message: '请输入监测点名称',
            trigger: 'blur'
        }
    ],
    voltageLevel: [
        {
            required: true,
            message: '请选择监测点电压等级',
            trigger: 'change'
        }
    ],
    connectedBus: [
        {
            required: true,
            message: '请选择接入母线',
            trigger: 'blur'
        }
    ],
    shortCapacity: [
        {
            required: true,
            message: '请输入短路容量',
            trigger: 'blur'
        }
    ],
    dealCapacity: [
        {
            required: true,
            message: '请输入协议容量',
            trigger: 'blur'
        }
    ],
    devCapacity: [
        {
            required: true,
            message: '请输入终端容量',
            trigger: 'blur'
        }
    ],
    standardCapacity: [
        {
            required: true,
            message: '请输入基准容量',
            trigger: 'blur'
        }
    ],
    ct1: [
        {
            required: true,
            message: '请输入CT变化',
            trigger: 'blur'
        }
    ],
    pt1: [
        {
            required: true,
            message: '请输入PT变化',
            trigger: 'blur'
        }
    ],
    lineId: [
        {
            required: true,
            message: '请输入上送网公司编码',
            trigger: 'blur'
        }
    ],
    timeInterval: [
        {
            required: true,
            message: '请输入测量间隔',
            trigger: 'blur'
        }
    ],
    loadType: [
        {
            required: true,
            message: '请选择干扰源类型',
            trigger: 'change'
        }
    ],
    businessType: [
        {
            required: true,
            message: '请选择干扰源类别',
            trigger: 'change'
        }
    ],
    pointNature: [
        {
            required: true,
            message: '请选择监测点性质',
            trigger: 'change'
        }
    ],
    isStatistical: [
        {
            required: true,
            message: '请选择是否参与统计',
            trigger: 'change'
        }
    ],
    objName: [
        {
            required: true,
            message: '请输入监测点对象名称',
            trigger: 'blur'
        }
    ],
    powerSubstationName: [
        {
            required: true,
            message: '请选择电网侧变电站',
            trigger: 'change'
        }
    ],
    isGridConnectionPoint: [
        {
            required: true,
            message: '请选择是否并网点',
            trigger: 'change'
        }
    ],
    operationStatus: [
        {
            required: true,
            message: '请选择监测点运行状态',
            trigger: 'change'
        }
    ],
    mainWiringDiagram: [
        {
            required: true,
            message: '请上传主接线图',
            trigger: 'change'
        }
    ],
    voltageDeviationUpperLimit: [
        {
            required: false,
            message: '请输入电压偏差上限',
            trigger: 'blur'
        }
    ],
    voltageDeviationLowerLimit: [
        {
            required: false,
            message: '请输入电压偏差下限',
            trigger: 'blur'
        }
    ]
})
const resendId = ref('')
const rowValue: any = ref({})


const open = async (row: any) => {
    resetForm()
    dialogFormVisible.value = true
    title.value = row.title
    //初始化数据

    nextTick(async () => {
        if (row.row) {
            resendId.value = row.row.id
            rowValue.value = row.row
            await getTempLineDetailsById({ id: row.row.id }).then(res => {
                form.value = res.data

                form.value.loadType = loadTypeList.value.filter((item: any) => item.name == res.data.loadType)[0]?.id

                businessTypeList.value = loadTypeList.value.find(item => {
        return item.id == form.value.loadType
    })?.children
                form.value.businessType = businessTypeList.value.filter(
                    (item: any) => item.name == res.data.businessType
                )[0]?.id
                mainWiringDiagram.value =
                    res.data.mainWiringDiagram.length == 0 ? [] : JSON.parse(JSON.stringify(res.data.mainWiringDiagram))
                form.value.mainWiringDiagram =
                    res.data.mainWiringDiagram.length == 0
                        ? []
                        : JSON.parse(
                            JSON.stringify([
                                {
                                    name: res.data.mainWiringDiagram.split('/')[2]
                                }
                            ])
                        )
            })
        } else {
            resendId.value = ''
        }
    })
}
const close = () => {
    //重置表单内容
    //取消表单校验状态
    ruleFormRef.value && ruleFormRef.value.resetFields()
    dialogFormVisible.value = false
    emits('onSubmit')
}
onMounted(() => { })

watch(
    () => projectList.value,
    (val, oldVal) => {
        if (val && val.length != 0 && resendId.value) {
            let obj: any = projectList.value.find((item: any) => {
                return rowValue.value.createBy == item.createBy
            })
            form.value = {
                ...form.value,
                reporter: obj?.reporter,
                reporterName: obj?.reporterName
            }
        }
    },
    {
        deep: true,
        immediate: true
    }
)
// 上传报告
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: any) => {
    uploadName.value = val
}
//移除文件上传
const removeFile = (file: any, uploadFiles: any) => {
    // console.log(file, uploadFiles)
}
//监测点台账信息
const lineFilePath = ref('')
//主接线图
const mainWiringDiagram = ref('')
const choose = (e: any) => {
    uploadFile(e.raw, '/supervision/').then(res => {
        //监测点台账信息
        if (uploadName.value == 'lineFilePath') {
            lineFilePath.value = res.data.name
        }
        //主接线图
        else if (uploadName.value == 'mainWiringDiagram') {
            mainWiringDiagram.value = res.data.name
        }
    })
}
//设置工程投产日期时间选择范围不能<今天
const disabledDate = time => {
    return time.getTime() < Date.now() - 8.64e7 // 8.64e7 毫秒数代表一天
}
const activeName = ref('0')
//提交
const confirmForm = async (flag: boolean) => {
    loading.value = true
    if (flag) {
        form.value.reportDate = window.XEUtils.toDateString(form.value.reportDate, 'yyyy-MM-dd')
        let confirmFormData = JSON.parse(JSON.stringify(form.value))
        if (!form.value.pt1 || !form.value.pt2) {
            return ElMessage({
                message: '请输入PT变比',
                type: 'warning'
            })
        }
        if (!form.value.ct1 || !form.value.ct2) {
            return ElMessage({
                message: '请输入CT变比',
                type: 'warning'
            })
        }
        //提交终端信息
        confirmFormData = {
            ...confirmFormData,
            lineFilePath: form.value.lineFilePath?.length == 0 ? '' : lineFilePath?.value, //监测点信息
            mainWiringDiagram: form.value.mainWiringDiagram?.length == 0 ? '' : mainWiringDiagram.value //主接线图
        }
        confirmFormData.saveOrCheckflag = '1'
        if (title.value != '监测点信息') confirmFormData.id = resendId.value
        await addMointorPointFormData(confirmFormData).then(res => {
            ElMessage({
                message: '保存成功!',
                type: 'success'
            })
            ruleFormRef.value.resetFields()
 
            resetForm()
            
            close()
        }).catch(() => {
            loading.value = false
        })
    } else {
        // 先判断提交终端信息与监测点信息
        // 提交监测点信息
        ruleFormRef.value.validate(async (valid) => {
            if (valid) {
                //整理上传文件的数据
                //处理填报日期时间格式
                form.value.reportDate = window.XEUtils.toDateString(form.value.reportDate, 'yyyy-MM-dd')
                let confirmFormData = JSON.parse(JSON.stringify(form.value))
                if (!form.value.pt1 || !form.value.pt2) {
                    return ElMessage({
                        message: '请输入PT变比',
                        type: 'warning'
                    })
                }
                if (!form.value.ct1 || !form.value.ct2) {
                    return ElMessage({
                        message: '请输入CT变比',
                        type: 'warning'
                    })
                }
                //提交终端信息
                confirmFormData = {
                    ...confirmFormData,
                    lineFilePath: form.value.lineFilePath?.length == 0 ? null : lineFilePath?.value, //监测点信息
                    mainWiringDiagram: form.value.mainWiringDiagram?.length == 0 ? null : mainWiringDiagram.value //主接线图
                    // pt1: form.value.pt1 / form.value.pt2, //PT变比
                    // ct1: form.value.ct1 / form.value.ct2 //CT变比
                }
                confirmFormData.saveOrCheckflag = '2'
                if (title.value == '监测点信息') {
                    await addMointorPointFormData(confirmFormData).then(res => {
                        ElMessage({
                            message: '新增成功',
                            type: 'success'
                        })
                        ruleFormRef.value.resetFields()
                        resetForm()
                        close()
                    }).catch(() => {
            loading.value = false
        })
                } else {
                    confirmFormData.id = resendId.value
                    await updateMointorPointFormData(confirmFormData).then(res => {
                        if (res.code == 'A0000') {
                            ElMessage({
                                message: '重新发起成功',
                                type: 'success'
                            })
                            ruleFormRef.value.resetFields()
                            resetForm()
                            close()
                        }
                    }).catch(() => {
            loading.value = false
        })
                }
            } else {
                // // console.log('表单验证失败')
                return false
            }
        })
    }
    await setTimeout(() => {
        loading.value = false
    }, 0)
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.fixed_upload {
    width: 100%;
    height: auto;
    display: flex;
    justify-content: flex-end;
}

::v-deep .el-tabs__content {
    height: 100% !important;
}

::v-deep .el-form-item__content {
    display: flex !important;
    justify-content: space-between !important;
}
</style>
