<template>
    <el-dialog
        v-model="dialogFormVisible"
        :title="title"
        width="65%"
        :append-to-body="true"
        :before-close="close"
        :close-on-click-modal="false"
        draggable
    >
        <!-- 用户档案录入 新建1 -->
        <el-form
            :model="form"
            class="form-two"
            :validate-on-rule-change="false"
            :rules="rules"
            :scroll-to-error="true"
            ref="ruleFormRef"
            label-width="auto"
        >
            <!-- <el-form-item for="-" label="填报人：" prop="reporter">
                <el-input v-model.trim="form.reporter" autocomplete="off" :disabled="true" placeholder="请输入填报人" />
            </el-form-item>
            <el-form-item for="-" label="填报日期：" prop="reportDate">
                <el-date-picker
                    :disabled="true"
                    style="width: 100%"
                    v-model="form.reportDate"
                    type="date"
                    placeholder="请选择填报日期"
                />
            </el-form-item>
            <el-form-item for="-" label="填报部门：" prop="orgId">
                <el-input v-model.trim="form.orgId" :disabled="true" autocomplete="off" />
            </el-form-item> -->
            <el-form-item for="-" label="所在地市：" prop="city">
                <el-select v-model="form.city" clearable placeholder="请选择所在地市">
                    <el-option
                        v-for="item in areaOptionList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="项目名称：" prop="projectName">
                <el-input
                    v-model.trim="form.projectName"
                    autocomplete="off"
                    placeholder="请输入项目名称"
                    maxlength="64"
                    show-word-limit
                />
            </el-form-item>
            <el-form-item for="-" label="工程预期投产日期：">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.expectedProductionDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled-date="disabledDate"
                    placeholder="请选择工程预期投产日期"
                />
            </el-form-item>
            <el-form-item for="-" label="用户性质：" >
                <!-- :disabled="resendId != '' && title != '编辑'" -->
                <el-select v-model="form.userType" placeholder="请选择用户性质">
                    <el-option
                        v-for="(item, index) in userTypeList"
                        :label="item.label"
                        :value="item.value"
                        :key="index"
                    />
                </el-select>
            </el-form-item>
     
            <el-form-item for="-" label="归口管理部门：" >
                <el-input
                    v-model.trim="form.responsibleDepartment"
                    autocomplete="off"
                    placeholder="请输入归口管理部门"
                    maxlength="32"
                    show-word-limit
                />
            </el-form-item>
           
            <el-form-item for="-" label="用户状态：">
                <el-select v-model="form.userStatus" placeholder="请选择用户状态">
                    <el-option
                        v-for="(item, index) in userStateList"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                        :key="index"
                    />
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="厂站名称：" >
                <el-input
                    v-model.trim="form.substation"
                    autocomplete="off"
                    placeholder="请输入厂站名称"
                    maxlength="64"
                    show-word-limit
                />
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType == '0' || form.userType == '1'"
                label="用户协议容量："
            >
                <el-input
                    v-model.trim="form.agreementCapacity"
                    oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')"
                    autocomplete="off"
                    placeholder="请输入用户协议容量"
                    maxlength="6"
                    show-word-limit
                >
                    <template #append>MVA</template>
                </el-input>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType == '0' || form.userType == '1'"
                label="非线性终端类型："
            >
                <el-tree-select
                    accordion
                    ref="treeRef"
                    :default-expand-all="false"
                    show-checkbox
                    check-strictly
                    :highlight-current="true"
                    readonly
                    node-key="id"
                    :props="defaultProps"
                    v-model="form.nonlinearDeviceType"
                    :data="nonlinearDeviceTypeList"
                    :render-after-expand="false"
                />
            </el-form-item>
            <el-form-item for="-" label="电压等级：">
                <el-select v-model="form.voltageLevel" placeholder="请选择电压等级" node-key="id">
                    <el-option
                        v-for="(item, index) in voltageLevelList"
                        :label="item.name"
                        :value="item.id"
                        :key="index"
                    />
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="预测评估单位：" >
                <el-select v-model="form.evaluationDept" allow-create filterable placeholder="请选择预测评估单位">
                    <el-option
                        v-for="(item, index) in evaluationDeptList"
                        :label="item.name"
                        :value="item.name"
                        :key="index"
                    />
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="是否需要治理：" >
                <el-radio-group v-model="form.needGovernance">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item for="-" label="是否开展背景测试：" >
                <el-radio-group v-model="form.backgroundTestPerformed">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
          

            <el-form-item
                for="-"
                v-if="form.userType != '0' && form.userType != '1'"
                label="评估类型："
              
            >
                <el-select v-model="form.evaluationType" placeholder="请选择评估类型">
                    <el-option
                        v-for="(item, index) in evaluationTypeList"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item for="-" v-if="form.userType != '0' && form.userType != '1'" label="PCC点：" >
                <el-input v-model.trim="form.pccPoint" autocomplete="off" placeholder="请输入PCC点" />
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType == '2' || form.userType == '3' || form.userType == '4' || form.userType == '5'"
                label="基准短路容量："
            >
                <el-input
                    v-model.trim="form.baseShortCircuitCapacity"
                    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="-"
                v-if="form.userType == '2' || form.userType == '3' || form.userType == '4' || form.userType == '5'"
                label="系统最小短路容量："
            >
                <el-input
                    v-model.trim="form.minShortCircuitCapacity"
                    oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')"
                    autocomplete="off"
                    placeholder="请选择系统最小短路容量"
                >
                    <template #append>MVA</template>
                </el-input>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType == '2' || form.userType == '3' || form.userType == '4' || form.userType == '5'"
                label="PCC供电设备容量："
            >
                <el-input
                    v-model.trim="form.pccEquipmentCapacity"
                    oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')"
                    placeholder="请输入PCC供电设备容量"
                >
                    <template #append>MVA</template>
                </el-input>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType == '2' || form.userType == '3' || form.userType == '4' || form.userType == '5'"
                label="用户用电协议容量："
            >
                <el-input
                    v-model.trim="form.userAgreementCapacity"
                    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="-" v-if="form.userType == '6'" label="行业：">
                <el-select v-model="form.industry" placeholder="请选择行业">
                    <el-option v-for="(item, index) in industryList" :label="item.name" :value="item.id" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item for="-" v-if="form.userType == '6'" label="敏感终端名称：" >
                <el-input v-model.trim="form.deviceName" autocomplete="off" placeholder="请输入敏感终端名称" />
            </el-form-item>
            <el-form-item for="-" v-if="form.userType == '6'" label="供电电源数量：" >
                <el-input-number
                    style="width: 100%"
                    v-model="form.powerSupplyCount"
                    :min="0"
                    placeholder="请输入供电电源数量"
                />
            </el-form-item>
            <el-form-item for="-" v-if="form.userType == '6'" label="敏感电能质量指标：">
                <el-select
                    v-model="form.energyQualityIndex"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    placeholder="请选择敏感电能质量指标"
                >
                    <el-option
                        v-for="(item, index) in energyQualityIndexList"
                        :label="item.name"
                        :value="item.id"
                        :key="index"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType == '2' || form.userType == '3' || form.userType == '4' || form.userType == '5'"
                :label="form.userType == '4' || form.userType == '5' ? '非线性设备类型: ' : '非线性负荷类型：'"
              
            >
                <el-tree-select
                    accordion
                    ref="treeRef"
                    :default-expand-all="false"
                    show-checkbox
                    check-strictly
                    :highlight-current="true"
                    readonly
                    node-key="id"
                    :props="defaultProps"
                    filterable
                    v-model="form.nonlinearLoadType"
                    :data="nonlinearDeviceTypeList"
                    :render-after-expand="false"
                    placeholder="请选择"
                />
            </el-form-item>
            <el-form-item for="-" v-if="form.userType == '6'" label="是否开展抗扰度测试：" >
                <el-radio-group v-model="form.antiInterferenceTest">
                    <el-radio value="1">是</el-radio>
                    <el-radio value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType == '6' && isInterferencemanagement"
                label="负荷级别："
               
            >
                <el-select v-model="form.loadLevel" collapse-tags collapse-tags-tooltip placeholder="请选择负荷级别">
                    <el-option
                        v-for="(item, index) in loadLevelOptionList"
                        :label="item.name"
                        :value="item.id"
                        :key="index"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType == '6' && isInterferencemanagement"
                label="供电电源情况："
              
            >
                <el-select
                    v-model="form.powerSupplyInfo"
                    collapse-tags
                    collapse-tags-tooltip
                    placeholder="请选择供电电源情况"
                >
                    <el-option
                        v-for="(item, index) in powerSupplyInfoOptionList"
                        :label="item.name"
                        :value="item.id"
                        :key="index"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                for="-"
                v-if="form.userType != '0' && form.userType != '1'"
                label="预测评估评审单位："
            
            >
                <el-input
                    v-model.trim="form.evaluationChekDept"
                    autocomplete="off"
                    placeholder="请输入预测评估评审单位"
                />
            </el-form-item>
            <el-form-item for="-" label="预测评估结论："  style="width: 100%">
                <el-input
                    type="textarea"
                    v-model.trim="form.evaluationConclusion"
                    autocomplete="off"
                    placeholder="请输入预测评估结论"
                    maxlength="300"
                    show-word-limit
                />
            </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>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, defineExpose, defineProps, defineEmits, watch, onUnmounted } from 'vue'
// import { upload, insertTerminal, updateTerminal } from '@/api/process-boot/terminal'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { genFileId, ElMessage } from 'element-plus'
import { useDictData } from '@/stores/dictData'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { useAdminInfo } from '@/stores/adminInfo'
import { queryByAllCode } from '@/api/system-boot/dictTree'
import { uploadFile } from '@/api/system-boot/file'
import {
    submitFormData,
    getById,
    updateFormData,
    addEditor,
    resend,
    getByDeptDevLine
} from '@/api/supervision-boot/interfere/index'
import { getUserReportUpdateById } from '@/api/supervision-boot/userReport/form'
import { useRoute } from 'vue-router'

const route = useRoute()
const isInterferencemanagement: any = ref(false)
if (route.path.includes('interferencemanagement')) {
    isInterferencemanagement.value = false
} else {
    isInterferencemanagement.value = true
}

const props = defineProps({
    openType: {
        type: String,
        default: 'create'
    },
    submissionControl: {
        type: Boolean,
        default: true
    },
    update: {
        type: Boolean,
        default: false
    },
    normalizedControl: {
        type: Boolean,
        default: false
    }
})
const emits = defineEmits(['onSubmit'])
const dictData = useDictData()
const dialogFormVisible = ref(false)
// .doc,.docx,.xlsx,.xls,.pdf
const acceptType = ''
const form: any = ref({})
const loading = ref(false)
const control: any = ref(true)
const controFlag: any = ref(false)
const ruleFormRef: any = ref(null)
//字典获取所在地市
const areaOptionList = dictData
    .getBasicData('jibei_area')
    .filter(item => !(item.name == '超高压' || item.name == '风光储'))

//字典获取敏感电能质量指标
// const energyQualityIndexList = dictData.getBasicData('Indicator_Type')
const energyQualityIndexList = dictData.getBasicData('Problem_Indicators')
const devIdList: any = ref([])
const lineIdList: any = ref([])
//字典获取行业类型
const industryList = dictData.getBasicData('industry_type_jb')
//字典电压等级
const voltageLevelList = dictData.getBasicData('Dev_Voltage_Stand')
//字典评估类型
const evaluationTypeList = dictData.getBasicData('Evaluation_Type')
//字典预测评估单位
const evaluationDeptList = dictData.getBasicData('evaluation_dept')
//负荷级别
const loadLevelOptionList = dictData.getBasicData('load_level')
//供电电源情况
const powerSupplyInfoOptionList = dictData.getBasicData('supply_condition')
//用户性质数组
const userTypeList: any = ref([
    {
        label: '新建电网工程',
        value: 0
    },
    {
        label: '扩建电网工程',
        value: 1
    },
    {
        label: '新建非线性负荷用户',
        value: 2
    },
    {
        label: '扩建非线性负荷用户',
        value: 3
    },
    {
        label: '新建新能源发电站',
        value: 4
    },
    {
        label: '扩建新能源发电站',
        value: 5
    },
    {
        label: '敏感及重要用户',
        value: 6
    }
])
//用户状态数组
const userStateList = ref([
    {
        label: '可研',
        value: 0,
        disabled: false
    },
    {
        label: '建设',
        value: 1,
        disabled: true
    },
    {
        label: '运行',
        value: 2,
        disabled: true
    },
    {
        label: '退运',
        value: 3,
        disabled: true
    }
])
const title = ref('')

//获取非线性终端类型树形下拉
const defaultProps = {
    children: 'children',
    label: 'name',
    key: 'id'
}
const nonlinearDeviceTypeList: any = ref('')
//获取登陆用户姓名和部门
const adminInfo = useAdminInfo()
const resetForm = () => {
    form.value = {
        reporter: '', //填报人  1
        reportDate: new Date(), //填报日期  1
        orgId: '', //填报部门  1
        expectedProductionDate: '', //工程预期投产日期 1
        userType: 1, //用户性质 1
        city: areaOptionList[0].name, //所在地市 1
        responsibleDepartment: '', //归口管理部门 1
        userStatus: userStateList.value[0].value, //用户状态 1
        projectName: '', //项目名称 1
        substation: '', //变电站 1
        voltageLevel: voltageLevelList[0].id, //电压等级 1
        evaluationDept: evaluationDeptList[0].name, //预测评估单位 1
        evaluationConclusion: '', //预测评估结论 1
        backgroundTestPerformed: 0, //是否开展背景测试 1
        devId: '', //关联终端 1
        lineId: '', //关联监测点 1
        state: '', //数据状态
        pccPoint: '', //PCC点 1
        evaluationType: evaluationTypeList[0].id, //评估类型 1
        evaluationChekDept: '', //预测评估审单位  1
        minShortCircuitCapacity: '', //系统最小短路容量（MVA） 1
        userAgreementCapacity: '', //用户用电协议容量（MVA） 1
        needGovernance: 0, //是否需要治理 1
        agreementCapacity: '', //用户协议容量  1
        nonlinearDeviceType: '', //非线性终端类型 1
        nonlinearLoadType: '', //非线性负荷类型 1
        pccEquipmentCapacity: '', // PCC供电设备容量（MVA） 1
        baseShortCircuitCapacity: '', //基准短路容量（MVA）1
        industry: industryList[0].id, //行业 1
        deviceName: '', //敏感终端名称  1
        powerSupplyCount: 0, //供电电源数量 1
        energyQualityIndex: [energyQualityIndexList[0]?.id], //敏感电能质量指标 1
        antiInterferenceTest: '0' //是否开展抗扰度测试 1
    }
    form.value.reporter = adminInfo.$state.name
    form.value.orgId = adminInfo.$state.deptName
    if (isInterferencemanagement.value) {
        form.value.loadLevel = loadLevelOptionList[0]?.id //负荷级别
        form.value.powerSupplyInfo = powerSupplyInfoOptionList[0]?.id //供电电源情况
    } else {
        delete form.value.loadLevel
        delete form.value.powerSupplyInfo
    }
}
//初始化数据
resetForm()
//获取树形图数据
const getTreeList = () => {
    queryByAllCode().then(res => {
        // nonlinearDeviceTypeList.value = [res.data.find((item: any) => item.code == 'Major_Nonlinear_Device')]

        // nonlinearDeviceTypeList.value.map((item: any) => {
        //     //tree禁用根节点
        //     item.disabled = 'disabled'
        //     item.children.map((vv: any) => {
        //         //tree禁用二级节点
        //         vv.disabled = 'disabled'
        //         vv.children.map((kk: any) => {
        //             //tree禁用三级节点
        //             kk.disabled = 'disabled'
        //             kk.children.map((ss: any) => {
        //                 ss.name = vv.name + '-' + kk.name + '-' + ss.name
        //             })
        //         })
        //     })
        // })
        let data = [res.data.find((item: any) => item.code == 'Major_Nonlinear_Device')]
        nonlinearDeviceTypeList.value = [{ ...JSON.parse(JSON.stringify(...data)), children: [], disabled: 'disabled' }]
        data.map((item: any) => {
            //tree禁用根节点
            item.disabled = 'disabled'
            item.children.map((vv: any) => {
                //tree禁用二级节点
                vv.disabled = 'disabled'
                vv.children.map((kk: any) => {
                    //tree禁用三级节点
                    kk.disabled = 'disabled'
                    kk.children.map((ss: any) => {
                        ss.name = vv.name + '-' + kk.name + '-' + ss.name
                        nonlinearDeviceTypeList.value[0].children.push(ss)
                    })
                })
            })
        })
    })
}

getTreeList()
const treeRef = ref()
const subForm: any = ref({
    city: '', //所在地市
    evaluationConclusion: '', //预测评估结论
    evaluationDept: '', //预测评估单位
    expectedProductionDate: '', //工程预期投产日期
    orgId: '', //填报部门
    projectName: '',
    devId: 0, //关联终端 1
    lineId: 0, //关联监测点 1
    reporter: '', //填报人
    reportDate: new Date(), //填报日期
    responsibleDepartment: '', //归口管理部门
    substation: '', ////变电站
    userStatus: '0', //用户状态
    userType: 1, //用户性质
    voltageLevel: '',
    //userType=='0' '1'
    userReportProjectPO: {
        agreementCapacity: 0,
        backgroundTestPerformed: 0,
        id: '',
        needGovernance: 0,
        nonlinearDeviceType: '',
        state: 0
    },
    //userType=='2,3,4,5'
    userReportSubstationPO: {
        backgroundTestPerformed: 0,
        baseShortCircuitCapacity: 0,
        evaluationChekDept: '',
        evaluationType: '',
        id: '',
        minShortCircuitCapacity: 0,
        needGovernance: 0,
        nonlinearLoadType: '',
        pccEquipmentCapacity: 0,
        pccPoint: '',
        state: 0,
        userAgreementCapacity: 0
    },
    //userType=='6'
    userReportSensitivePO: {
        antiInterferenceTest: '0',
        backgroundTestPerformed: 0,
        deviceName: '',
        energyQualityIndex: [],
        evaluationChekDept: '',
        evaluationType: '',
        id: '',
        industry: '',
        needGovernance: 0,
        pccPoint: '',
        powerSupplyCount: 0,
        state: 0
    }
})
// 特殊字符正则表达式
const specialCharRegex = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/
//定义校验规则
const rules = ref({
    reporter: [{ required: true, message: '请输入填报人', trigger: 'blur' }],
    reportDate: [{ required: true, message: '请选择填报日期', trigger: 'change' }],
    orgId: [{ required: true, message: '请选择填报部门', trigger: 'change' }],
    expectedProductionDate: [{ required: true, message: '请选择工程预期投产日期', trigger: 'change' }],
    userType: [{ required: true, message: '清选择用户性质', trigger: 'change' }],
    city: [{ required: true, message: '请选择所在地市', trigger: 'change' }],
    responsibleDepartment: [
        { required: true, message: '请输入归口管理部门', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (specialCharRegex.test(value)) {
                    callback(new Error('输入包含不允许的特殊字符'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    userStatus: [{ required: true, message: '请选择用户状态', trigger: 'change' }],
    projectName: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (specialCharRegex.test(value)) {
                    callback(new Error('输入包含不允许的特殊字符'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    substation: [
        { required: true, message: '请输入厂站名称', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (specialCharRegex.test(value)) {
                    callback(new Error('输入包含不允许的特殊字符'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    voltageLevel: [{ required: true, message: '请选择电压等级', trigger: 'change' }],
    evaluationDept: [{ required: true, message: '请选择预测评估单位', trigger: 'change' }],
    evaluationConclusion: [
        { required: true, message: '请输入预测评估结论', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (specialCharRegex.test(value)) {
                    callback(new Error('输入包含不允许的特殊字符'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    devId: [{ required: true, message: '请选择关联终端', trigger: 'change' }],
    lineId: [{ required: true, message: '请选择关联监测点', trigger: 'change' }],
    agreementCapacity: [{ required: true, message: '请选择用户协议容量', trigger: 'blur' }],
    nonlinearDeviceType: [{ required: true, message: '请选择非线性终端类型', trigger: 'change' }],
    needGovernance: [{ required: true, message: '请选择是否需要治理', trigger: 'change' }],
    backgroundTestPerformed: [{ required: true, message: '请选择是否开展背景测试', trigger: 'change' }],
    state: [{ required: true, message: '请选择数据状态', trigger: 'change' }],
    pccPoint: [{ required: true, message: '请输入PCC点', trigger: 'blur' }],
    industry: [{ required: true, message: '请选择行业', trigger: 'change' }],
    deviceName: [{ required: true, message: '请输入敏感终端名称', trigger: 'blur' }],
    powerSupplyCount: [{ required: true, message: '请输入供电电源数量', trigger: 'blur' }],
    energyQualityIndex: [{ required: true, message: '请输入敏感电能质量指标', trigger: 'blur' }],
    evaluationType: [{ required: true, message: '请选择评估类型', trigger: 'change' }],
    antiInterferenceTest: [{ required: true, message: '请选择是否开展抗扰度测试', trigger: 'change' }],
    evaluationChekDept: [{ required: true, message: '请输入预测评估审单位', trigger: 'blur' }],
    baseShortCircuitCapacity: [{ required: true, message: '请输入基准短路容量', trigger: 'blur' }],
    minShortCircuitCapacity: [{ required: true, message: '请输入系统最小短路容量', trigger: 'blur' }],
    pccEquipmentCapacity: [{ required: true, message: '请输入PCC供电设备容量', trigger: 'blur' }],
    userAgreementCapacity: [{ required: true, message: '请输入用户用电协议容量', trigger: 'blur' }],
    nonlinearLoadType: [{ required: true, message: '请输入非线性负荷类型', trigger: 'blur' }],

    loadLevel: [{ required: true, message: '请选择负荷级别', trigger: 'change' }],
    powerSupplyInfo: [{ required: true, message: '请选择供电电源情况', trigger: 'change' }]
})
watch(
    () => form.value,
    (val, oldVal) => {
        for (let key in val) {
            if (subForm.value.hasOwnProperty(key)) {
                subForm.value[key] = val[key] // 对相同的key进行赋值
            }
        }
        //处理填报日期时间格式
        subForm.value.reportDate = window.XEUtils.toDateString(form.value.reportDate, 'yyyy-MM-dd')
        //userType==0,1
        if (val.userType == '0' || val.userType == '1') {
            subForm.value.userReportProjectPO = {
                agreementCapacity: 0,
                backgroundTestPerformed: 0,
                id: '',
                needGovernance: 0,
                nonlinearDeviceType: '',
                state: 0
            }
            for (let key in val) {
                if (subForm.value.userReportProjectPO && subForm.value.userReportProjectPO.hasOwnProperty(key)) {
                    // 对相同的key进行赋值
                    subForm.value.userReportProjectPO[key] = val[key]
                }
            }
            delete subForm.value.userReportSubstationPO
            delete subForm.value.userReportSensitivePO
            return
        }
        //userType==2,3,4,5
        if (val.userType == '2' || val.userType == '3' || val.userType == '4' || val.userType == '5') {
            subForm.value.userReportSubstationPO = {
                backgroundTestPerformed: 0,
                baseShortCircuitCapacity: 0,
                evaluationChekDept: '',
                evaluationType: '',
                id: '',
                minShortCircuitCapacity: 0,
                needGovernance: 0,
                nonlinearLoadType: '',
                pccEquipmentCapacity: 0,
                pccPoint: '',
                state: 0,
                userAgreementCapacity: 0
            }
            for (let key in val) {
                if (subForm.value.userReportSubstationPO && subForm.value.userReportSubstationPO.hasOwnProperty(key)) {
                    // 对相同的key进行赋值
                    subForm.value.userReportSubstationPO[key] = val[key]
                }
            }
            delete subForm.value.userReportProjectPO
            delete subForm.value.userReportSensitivePO
            return
        }
        //userType==6
        if (val.userType == '6') {
            subForm.value.userReportSensitivePO = {
                antiInterferenceTest: '0',
                backgroundTestPerformed: 0,
                deviceName: '',
                energyQualityIndex: [],
                evaluationChekDept: '',
                evaluationType: '',
                id: '',
                industry: '',
                needGovernance: 0,
                pccPoint: '',
                powerSupplyCount: 0,
                state: 0,

                loadLevel: loadLevelOptionList[0]?.id, //负荷级别
                powerSupplyInfo: powerSupplyInfoOptionList[0]?.id //供电电源情况
            }
            if (isInterferencemanagement.value) {
                subForm.value.userReportSensitivePO.loadLevel = loadLevelOptionList[0]?.id //负荷级别
                subForm.value.userReportSensitivePO.powerSupplyInfo = powerSupplyInfoOptionList[0]?.id //供电电源情况
            } else {
                delete subForm.value.userReportSensitivePO.loadLevel
                delete subForm.value.userReportSensitivePO.powerSupplyInfo
            }

            for (let key in val) {
                if (subForm.value.userReportSensitivePO && subForm.value.userReportSensitivePO.hasOwnProperty(key)) {
                    // 对相同的key进行赋值
                    subForm.value.userReportSensitivePO[key] = val[key]
                }
            }
            delete subForm.value.userReportProjectPO
            delete subForm.value.userReportSubstationPO
            return
        }
    },
    {
        deep: true
    }
)

const resendId = ref('')
const status = ref('')
const open = async (row: any) => {
    title.value = row.title
    dialogFormVisible.value = true
    let deptIds = adminInfo.$state.deptId
    if (row.row) {
        resendId.value = row.row.id
        status.value = row.row.status

        deptIds = row.row.orgId
        if (props.update) {
            await getUserReportUpdateById(row.row.id).then(res => {
                handleResponse(res.data.userReportMessageJson)
            })
        } else {
            await getById({ id: row.row.id }).then(res => {
                handleResponse(res.data)
            })
        }
    } else {
        resendId.value = ''
        form.value.userType = userTypeList.value[0].value
    }
    setTimeout(() => {
        getByDeptDevLine({ id: deptIds }).then(res => {
            devIdList.value = res.data
            changeDevId(form.value.devId, false)
        })
    }, 10)
}

async function handleResponse(data: any) {
    // userType logic is commented out; if needed, implement accordingly
    if (data.userReportProjectPO) {
        form.value = { ...data, ...data.userReportProjectPO }
    } else if (data.userReportSubstationPO) {
        form.value = { ...data, ...data.userReportSubstationPO }
    } else if (data.userReportSensitivePO) {
        form.value = {
            ...data,
            ...data.userReportSensitivePO,
            energyQualityIndex: data.userReportSensitivePO.energyQualityIndex.split(', ')
        }
    }
    form.value.orgId = adminInfo.$state.deptName
}

const close = () => {
    //重置表单内容
    //取消表单校验状态
    ruleFormRef?.value && ruleFormRef?.value.resetFields()
    dialogFormVisible.value = false
    emits('onSubmit')
    resetForm()
}
onMounted(() => {})

// 上传报告
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 changeDevId = (e: any, flag?: boolean = true) => {
    if (flag) {
        form.value.lineId = ''
    }

    lineIdList.value = devIdList.value.filter(item => item.devId == e)[0]?.lineList
}
//设置工程预期投产日期时间选择范围不能<今天
const disabledDate = (time: any) => {
    // return time.getTime() < Date.now() - 8.64e7 // 8.64e7 毫秒数代表一天
    return false
}
//提交
const confirmForm = async (flag: boolean) => {
    loading.value = true
    if (flag) {
        //整理上传文件的数据
        // userType==0,1
        ruleFormRef.value.validate(async valid => {
            if (valid) {
                subForm.value.reporter = adminInfo.$state.id
                subForm.value.orgId = adminInfo.$state.deptId
                let confirmFormData = JSON.parse(JSON.stringify(subForm.value))
                //1.判断是否上传
                if (subForm.value.userType == '0' || subForm.value.userType == '1') {
                    {
                        //其他报告非必填
                        confirmFormData.userReportProjectPO = {
                            ...confirmFormData.userReportProjectPO
                        }
                    }
                }

                if (
                    subForm.value.userType == '2' ||
                    subForm.value.userType == '3' ||
                    subForm.value.userType == '4' ||
                    subForm.value.userType == '5'
                ) {
                    {
                        confirmFormData.userReportSubstationPO = {
                            ...confirmFormData.userReportSubstationPO
                        }
                    }
                }
                //userType==6
                if (subForm.value.userType == '6') {
                    {
                        confirmFormData.userReportSensitivePO = {
                            ...confirmFormData.userReportSensitivePO,
                            energyQualityIndex: confirmFormData.userReportSensitivePO.energyQualityIndex.join(', ')
                        }
                    }
                }
                confirmFormData.saveOrCheckflag = '1'
                if (title.value != '用户档案录入') confirmFormData.id = resendId.value
                if (!control.value) confirmFormData.dataType = 1
                if (controFlag.value) confirmFormData.dataType = 1
                if (props.normalizedControl) {
                    await addEditor(confirmFormData)
                        .then(res => {
                            ElMessage({
                                message: '保存成功!',
                                type: 'success'
                            })
                            ruleFormRef.value.resetFields()
                            resetForm()
                            close()
                        })
                        .catch(() => {
                            loading.value = false
                        })
                } else {
                    await submitFormData(confirmFormData)
                        .then(res => {
                            ElMessage({
                                message: '保存成功!',
                                type: 'success'
                            })
                            ruleFormRef.value.resetFields()
                            resetForm()
                            close()
                        })
                        .catch(() => {
                            loading.value = false
                        })
                }
            }
        })
    }
    await setTimeout(() => {
        loading.value = false
    }, 0)
}

// 过滤用户
const filterUsers = (arr: any) => {
    controFlag.value = true
    userStateList.value.map(item => (item.disabled = false))
    userTypeList.value = userTypeList.value.filter(item => !arr.includes(item.value))
}
const setcontroFlag = () => {
    console.log(12333)

    controFlag.value = true
}
defineExpose({ open, filterUsers, setcontroFlag })
</script>
<style lang="scss" scoped>
.el-form {
}

.form-label-left-align {
    text-align: left;
}

::v-deep .el-input__wrapper {
    // border: 2px solid red;
}

::v-deep .el-input-number .el-input__inner {
    text-align: left;
}

::v-deep .el-tree__empty-text {
    width: 200px !important;
    margin-left: 150px !important;
    top: 20% !important;
    left: 50% !important;
}

:deep(.el-upload-list__item-file-name) {
    width: 250px;
    text-align: left;
}
</style>
