<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="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="form.orgId" :disabled="true" autocomplete="off" />
            </el-form-item>
            <el-form-item 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-date="disabledDate"
                    placeholder="请选择工程预期投产日期" />
            </el-form-item>
            <el-form-item for="-" label="用户性质：" prop="userType">
                <!-- :disabled="resendId != '' && title != '编辑'" -->
                <el-select v-model="form.userType" placeholder="请选择用户性质"  :disabled="resendId !== '' && title !== '用户档案录入'" filterable>
                    <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="所在地市：" prop="city">
                <el-select v-model="form.city" clearable placeholder="请选择所在地市" filterable>
                    <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="responsibleDepartment">
                <el-input v-model="form.responsibleDepartment" autocomplete="off" placeholder="请输入归口管理部门" maxlength="32" show-word-limit clearable/>
            </el-form-item>
            <el-form-item for="-" label="项目名称：" prop="projectName">
                <el-input v-model="form.projectName" autocomplete="off" placeholder="请输入项目名称" maxlength="32" show-word-limit clearable/>
            </el-form-item>
            <el-form-item for="-" label="用户状态：" prop="userStatus">
                <el-select v-model="form.userStatus" placeholder="请选择用户状态" filterable>
                    <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="厂站名称：" prop="substation">
                <el-input v-model="form.substation" autocomplete="off" placeholder="请输入厂站名称" maxlength="32" show-word-limit clearable/>
            </el-form-item>
            <el-form-item for="-" v-if="form.userType == '0' || form.userType == '1'" label="用户协议容量："
                prop="agreementCapacity">
                <el-input v-model="form.agreementCapacity" 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 == '0' || form.userType == '1'" label="非线性终端类型："
                prop="nonlinearDeviceType">
                <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="电压等级：" prop="voltageLevel">
                <el-select v-model="form.voltageLevel" placeholder="请选择电压等级" node-key="id" filterable>
                    <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="预测评估单位：" prop="evaluationDept">
                <el-select v-model="form.evaluationDept" allow-create  placeholder="请选择预测评估单位" filterable>
                    <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="是否需要治理：" prop="needGovernance">
                <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="是否开展背景测试：" prop="backgroundTestPerformed">
                <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 label="关联终端" prop="devId" v-if="props.openType != 'create'">
                <el-select v-model="form.devId" filterable placeholder="请选择关联终端" @change="changeDevId" >
                    <el-option v-for="(item, index) in devIdList" :label="item.devName" :value="item.devId"
                        :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="关联监测点" prop="lineId" v-if="props.openType != 'create'">
                <el-select v-model="form.lineId" placeholder="请选择关联监测点" filterable>
                    <el-option v-for="(item, index) in lineIdList" :label="item.lineName" :value="item.lineId"
                        :key="index" />
                </el-select>
            </el-form-item>

            <el-form-item for="-" v-if="form.userType != '0' && form.userType != '1'" label="评估类型："
                prop="evaluationType">
                <el-select v-model="form.evaluationType" placeholder="请选择评估类型" filterable>
                    <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点：" prop="pccPoint">
                <el-input v-model="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="基准短路容量：" prop="baseShortCircuitCapacity">
                <el-input v-model="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="系统最小短路容量：" prop="minShortCircuitCapacity">
                <el-input v-model="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供电设备容量：" prop="pccEquipmentCapacity">
                <el-input v-model="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="用户用电协议容量：" prop="userAgreementCapacity">
                <el-input v-model="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="行业：" prop="industry">
                <el-select v-model="form.industry" placeholder="请选择行业" filterable>
                    <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="敏感终端名称：" prop="deviceName">
                <el-input v-model="form.deviceName" autocomplete="off" placeholder="请输入敏感终端名称" />
            </el-form-item>
            <el-form-item for="-" v-if="form.userType == '6'" label="供电电源数量：" prop="powerSupplyCount">
                <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="敏感电能质量指标：" prop="energyQualityIndex">
                <el-select v-model="form.energyQualityIndex" multiple collapse-tags collapse-tags-tooltip
                    placeholder="请选择敏感电能质量指标" filterable>
                    <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' ? '非线性设备类型: ' : '非线性负荷类型：'"
                prop="nonlinearLoadType">
                <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="是否开展抗扰度测试：" prop="antiInterferenceTest">
                <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="负荷级别："
                prop="loadLevel">
                <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="供电电源情况："
                prop="powerSupplyInfo">
                <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="预测评估评审单位："
                prop="evaluationChekDept">
                <el-input v-model="form.evaluationChekDept" autocomplete="off" placeholder="请输入预测评估评审单位" maxlength="32" show-word-limit clearable/>
            </el-form-item>
            <el-form-item for="-" label="预测评估结论：" prop="evaluationConclusion" style="width: 100%">
                <el-input type="textarea" v-model="form.evaluationConclusion" autocomplete="off"
                    placeholder="请输入预测评估结论" />
            </el-form-item>
            <el-form-item class="uploadFile" for="-" label="可研报告：" prop="feasibilityReport">
                <el-upload v-model:file-list="form.feasibilityReport" ref="uploadRef" action="" :accept="acceptType"
                    :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('feasibilityReport')"
                    :on-progress="uploadFileName('feasibilityReport')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item class="uploadFile" for="-" label="项目初步设计说明书：" prop="preliminaryDesignDescription">
                <el-upload v-model:file-list="form.preliminaryDesignDescription" ref="uploadRef" action=""
                    :accept="acceptType" :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('preliminaryDesignDescription')"
                    :on-progress="uploadFileName('preliminaryDesignDescription')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item class="uploadFile" for="-" label="预测评估报告：" prop="predictionEvaluationReport">
                <el-upload v-model:file-list="form.predictionEvaluationReport" ref="uploadRef" action=""
                    :accept="acceptType" :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('predictionEvaluationReport')"
                    :on-progress="uploadFileName('predictionEvaluationReport')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item class="uploadFile" for="-" label="预测评估评审意见报告：" prop="predictionEvaluationReviewOpinions">
                <el-upload v-model:file-list="form.predictionEvaluationReviewOpinions" ref="uploadRef" action=""
                    :accept="acceptType" :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('predictionEvaluationReviewOpinions')"
                    :on-progress="uploadFileName('predictionEvaluationReviewOpinions')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item class="uploadFile" for="-" label="其他附件：" prop="additionalAttachments">
                <el-upload v-model:file-list="form.additionalAttachments" ref="uploadRef" action="" :accept="acceptType"
                    :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('additionalAttachments')"
                    :on-progress="uploadFileName('additionalAttachments')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item for="-" class="uploadFile" v-if="form.userType != '0' && form.userType != '1'"
                label="用户接入变电站主接线示意图：" prop="substationMainWiringDiagram">
                <el-upload v-model:file-list="form.substationMainWiringDiagram" ref="uploadRef" action=""
                    :accept="acceptType" :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('substationMainWiringDiagram')"
                    :on-progress="uploadFileName('substationMainWiringDiagram')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item class="uploadFile" for="-" label="主要敏感终端清单：" v-if="form.userType == '6'"
                prop="sensitiveDevices">
                <el-upload v-model:file-list="form.sensitiveDevices" ref="uploadRef" action="" :accept="acceptType"
                    :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('sensitiveDevices')"
                    :on-progress="uploadFileName('sensitiveDevices')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item class="uploadFile" for="-" v-if="form.userType == '6'" label="抗扰度测试报告："
                prop="antiInterferenceReport">
                <el-upload v-model:file-list="form.antiInterferenceReport" ref="uploadRef" action=""
                    :accept="acceptType" :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('antiInterferenceReport')"
                    :on-progress="uploadFileName('antiInterferenceReport')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item class="uploadFile" for="-" v-if="form.userType == '6'" label="背景电能质量测试报告："
                prop="powerQualityReport">
                <el-upload v-model:file-list="form.powerQualityReport" ref="uploadRef" action="" :accept="acceptType"
                    :limit="1" :on-change="choose" :auto-upload="false" :on-remove="removeFile('powerQualityReport')"
                    :on-progress="uploadFileName('powerQualityReport')">
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <addUpload ref="addUploadRef" v-if="props.openType == 'sourcesOfInterference'" />
        </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" v-if="props.submissionControl" @click="confirmForm(false)" :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 { UploadFile, 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 addUpload from './addUpload.vue'
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 addUploadRef: any = ref()
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
        feasibilityReport: [], // 可研报告告地址  1
        preliminaryDesignDescription: [], //项目初步设计说明书告地址 1
        predictionEvaluationReport: [], //预测评估报告地址 1
        predictionEvaluationReviewOpinions: [], //预测评估评审意见报告地址 1
        additionalAttachments: [], //其他附件告地址 1
        state: '', //数据状态
        pccPoint: '', //PCC点 1
        evaluationType: evaluationTypeList[0].id, //评估类型 1
        evaluationChekDept: '', //预测评估审单位  1
        substationMainWiringDiagram: [], //用户接入变电站主接线示意图地址  1
        powerQualityReport: [], //背景电能质量测试报告 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
        sensitiveDevices: [], //主要敏感终端清单 1
        antiInterferenceReport: [] //抗扰度测试报告 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 VITE_FLAG = import.meta.env.VITE_NAME == 'jibei'
//获取树形图数据
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: {
        additionalAttachments: [], //其他附件告地址
        agreementCapacity: 0,
        backgroundTestPerformed: 0,
        feasibilityReport: [], //可研报告
        id: '',
        needGovernance: 0,
        nonlinearDeviceType: '',
        predictionEvaluationReport: [], //预测评估报告告地址
        predictionEvaluationReviewOpinions: [], //预测评估评审意见报告地址
        preliminaryDesignDescription: [], //项目初步设计说明书告地址
        state: 0
    },
    //userType=='2,3,4,5'
    userReportSubstationPO: {
        additionalAttachments: [], //其他附件告地址
        backgroundTestPerformed: 0,
        baseShortCircuitCapacity: 0,
        evaluationChekDept: '',
        evaluationType: '',
        feasibilityReport: [], //可研报告
        id: '',
        minShortCircuitCapacity: 0,
        needGovernance: 0,
        nonlinearLoadType: '',
        pccEquipmentCapacity: 0,
        pccPoint: '',
        predictionEvaluationReport: [], //预测评估报告告地址
        predictionEvaluationReviewOpinions: [], //预测评估评审意见报告地址
        preliminaryDesignDescription: [], //项目初步设计说明书告地址
        state: 0,
        substationMainWiringDiagram: [], //用户接入变电站主接线示意图地址
        userAgreementCapacity: 0
    },
    //userType=='6'
    userReportSensitivePO: {
        additionalAttachments: [], //其他附件告地址
        antiInterferenceReport: [], //抗扰度测试报告
        antiInterferenceTest: '0',
        backgroundTestPerformed: 0,
        deviceName: '',
        energyQualityIndex: [],
        evaluationChekDept: '',
        evaluationType: '',
        feasibilityReport: [], //可研报告告地址
        id: '',
        industry: '',
        needGovernance: 0,
        pccPoint: '',
        powerQualityReport: [], //背景电能质量测试报告
        powerSupplyCount: 0,
        predictionEvaluationReport: [], //预测评估报告告地址
        predictionEvaluationReviewOpinions: [], //预测评估评审意见报告地址
        preliminaryDesignDescription: [], //项目初步设计说明书告地址
        sensitiveDevices: [], //主要敏感终端清单
        state: 0,
        substationMainWiringDiagram: [] //用户接入变电站主接线示意图地址
    }
})

//定义校验规则
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' }],
    userStatus: [{ required: true, message: '请选择用户状态', trigger: 'change' }],
    projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    substation: [{ required: true, message: '请输入变电站', trigger: 'blur' }],
    voltageLevel: [{ required: true, message: '请选择电压等级', trigger: 'change' }],
    evaluationDept: [{ required: true, message: '请选择预测评估单位', trigger: 'change' }],
    evaluationConclusion: [{ required: true, message: '请输入预测评估结论', 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' }],
    substationMainWiringDiagram: [{ required: true, message: '请上传用户接入变电站主接线示意图', trigger: 'change' }],
    sensitiveDevices: [{ required: true, message: '请上传主要敏感终端清单', trigger: 'change' }],
    antiInterferenceReport: [{ required: true, message: '请上传抗扰度测试报告', trigger: 'change' }],
    powerQualityReport: [{ required: true, message: '请上传背景电能质量测试报告', trigger: 'change' }],
    feasibilityReport: [{ required: false, message: '请上传可研报告', trigger: 'blur' }],
    preliminaryDesignDescription: [{ required: false, message: '请上传项目初步设计说明书', trigger: 'blur' }],
    predictionEvaluationReport: [{ required: true, message: '请上传预测评估报告', trigger: 'blur' }],
    predictionEvaluationReviewOpinions: [{ required: true, message: '请上传预测评估评审意见报告', trigger: 'blur' }],
    additionalAttachments: [{ required: false, 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 = {
                additionalAttachments: [], //其他附件告地址
                agreementCapacity: 0,
                backgroundTestPerformed: 0,
                feasibilityReport: [], //可研报告
                id: '',
                needGovernance: 0,
                nonlinearDeviceType: '',
                predictionEvaluationReport: [], //预测评估报告告地址
                predictionEvaluationReviewOpinions: [], //预测评估评审意见报告地址
                preliminaryDesignDescription: [], //项目初步设计说明书告地址
                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 = {
                additionalAttachments: [], //其他附件告地址
                backgroundTestPerformed: 0,
                baseShortCircuitCapacity: 0,
                evaluationChekDept: '',
                evaluationType: '',
                feasibilityReport: [], //可研报告
                id: '',
                minShortCircuitCapacity: 0,
                needGovernance: 0,
                nonlinearLoadType: '',
                pccEquipmentCapacity: 0,
                pccPoint: '',
                predictionEvaluationReport: [], //预测评估报告告地址
                predictionEvaluationReviewOpinions: [], //预测评估评审意见报告地址
                preliminaryDesignDescription: [], //项目初步设计说明书告地址
                state: 0,
                substationMainWiringDiagram: [], //用户接入变电站主接线示意图地址
                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 = {
                additionalAttachments: [], //其他附件告地址
                antiInterferenceReport: [], //抗扰度测试报告
                antiInterferenceTest: '0',
                backgroundTestPerformed: 0,
                deviceName: '',
                energyQualityIndex: [],
                evaluationChekDept: '',
                evaluationType: '',
                feasibilityReport: [], //可研报告告地址
                id: '',
                industry: '',
                needGovernance: 0,
                pccPoint: '',
                powerQualityReport: [], //背景电能质量测试报告
                powerSupplyCount: 0,
                predictionEvaluationReport: [], //预测评估报告告地址
                predictionEvaluationReviewOpinions: [], //预测评估评审意见报告地址
                preliminaryDesignDescription: [], //项目初步设计说明书告地址
                sensitiveDevices: [], //主要敏感终端清单
                state: 0,
                substationMainWiringDiagram: [], //用户接入变电站主接线示意图地址

                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
    addUploadRef.value?.reset()
    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)
            })
        }
        setTimeout(() => {
            addUploadRef.value?.queryFiles(row.row.id)
        }, 0)
    } else {
        resendId.value = ''
        form.value.userType = userTypeList.value[0].value


        // 清空所有文件引用
        feasibilityReport.value = ''
        preliminaryDesignDescription.value = ''
        predictionEvaluationReport.value = ''
        predictionEvaluationReviewOpinions.value = ''
        additionalAttachments.value = ''
        substationMainWiringDiagram.value = ''
        sensitiveDevices.value = ''
        antiInterferenceReport.value = ''
        powerQualityReport.value = ''
        
        // 清空表单中的文件列表
        form.value.feasibilityReport = []
        form.value.preliminaryDesignDescription = []
        form.value.predictionEvaluationReport = []
        form.value.predictionEvaluationReviewOpinions = []
        form.value.additionalAttachments = []
        form.value.substationMainWiringDiagram = []
        form.value.sensitiveDevices = []
        form.value.antiInterferenceReport = []
        form.value.powerQualityReport = []
    }
    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 }
        fileRaw(data, 'userReportProjectPO')
    } else if (data.userReportSubstationPO) {
        form.value = { ...data, ...data.userReportSubstationPO }
        fileRaw(data, 'userReportSubstationPO')
    } else if (data.userReportSensitivePO) {
        form.value = {
            ...data, 
            ...data.userReportSensitivePO,
            energyQualityIndex: data.userReportSensitivePO.energyQualityIndex.split(', ')
        }
        fileRaw(data, 'userReportSensitivePO')
    }
    form.value.orgId = adminInfo.$state.deptName
}

// 处理上传文件回显
const fileRaw = (row: any, key: string) => {
    let list = [
        'feasibilityReport',
        'preliminaryDesignDescription',
        'predictionEvaluationReport',
        'predictionEvaluationReviewOpinions',
        'additionalAttachments',
        'substationMainWiringDiagram',
        'sensitiveDevices',
        'antiInterferenceReport',
        'powerQualityReport'
    ]
    for (let k of list) {
        if (row[key][k] != null) {
            form.value[k] =
                row[key][k].length == 0
                    ? []
                    : [
                        {
                            name: row[key][k].split('/')[2]
                        }
                    ]
        } else {
            form.value[k] = []
        }
    }

    feasibilityReport.value = row[key].feasibilityReport
    preliminaryDesignDescription.value = row[key].preliminaryDesignDescription
    predictionEvaluationReport.value = row[key].predictionEvaluationReport
    predictionEvaluationReviewOpinions.value = row[key].predictionEvaluationReviewOpinions
    additionalAttachments.value = row[key].additionalAttachments
    substationMainWiringDiagram.value = row[key].substationMainWiringDiagram
    sensitiveDevices.value = row[key].sensitiveDevices
    antiInterferenceReport.value = row[key].antiInterferenceReport
    powerQualityReport.value = row[key].powerQualityReport
}
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 = (val: any) => {
  return (file: UploadFile, fileList: UploadFile[]) => {
    // 根据上传字段名称清除对应的文件引用
    switch(val) {
      case 'feasibilityReport':
        feasibilityReport.value = ''
        break
      case 'preliminaryDesignDescription':
        preliminaryDesignDescription.value = ''
        break
      case 'predictionEvaluationReport':
        predictionEvaluationReport.value = ''
        break
      case 'predictionEvaluationReviewOpinions':
        predictionEvaluationReviewOpinions.value = ''
        break
      case 'additionalAttachments':
        additionalAttachments.value = ''
        break
      case 'substationMainWiringDiagram':
        substationMainWiringDiagram.value = ''
        break
      case 'sensitiveDevices':
        sensitiveDevices.value = ''
        break
      case 'antiInterferenceReport':
        antiInterferenceReport.value = ''
        break
      case 'powerQualityReport':
        powerQualityReport.value = ''
        break
    }
    
    // 同步更新表单中的文件列表
    form.value[val] = fileList
  }
}
// 可研报告数组
const feasibilityReport = ref('')
//项目初步设计说明书
const preliminaryDesignDescription = ref('')
//预测评估报告
const predictionEvaluationReport = ref('')
//预测评估评审意见报告：
const predictionEvaluationReviewOpinions = ref('')
//其他附件：
const additionalAttachments = ref('')
//用户接入变电站主接线示意图
const substationMainWiringDiagram = ref('')
//主要敏感终端清单：
const sensitiveDevices = ref('')
//抗扰度测试报告：
const antiInterferenceReport = ref('')
//背景电能质量测试报告：
const powerQualityReport = ref('')
const choose = (e: any) => {
    // console.log('🚀 ~ choose ~ e:', e)
    uploadFile(e.raw, '/supervision/').then(res => {
        //可研报告
        if (uploadName.value == 'feasibilityReport') {
            feasibilityReport.value = res.data.name
        }
        //项目初步设计说明书
        else if (uploadName.value == 'preliminaryDesignDescription') {
            preliminaryDesignDescription.value = res.data.name
        }
        //预测评估报告：
        else if (uploadName.value == 'predictionEvaluationReport') {
            predictionEvaluationReport.value = res.data.name
        }
        //预测评估评审意见报告：
        else if (uploadName.value == 'predictionEvaluationReviewOpinions') {
            predictionEvaluationReviewOpinions.value = res.data.name
        }
        //其他附件：
        else if (uploadName.value == 'additionalAttachments') {
            additionalAttachments.value = res.data.name
        }
        //用户接入变电站主接线示意图
        else if (uploadName.value == 'substationMainWiringDiagram') {
            substationMainWiringDiagram.value = res.data.name
        }
        //主要敏感终端清单：
        else if (uploadName.value == 'sensitiveDevices') {
            sensitiveDevices.value = res.data.name
        }
        //抗扰度测试报告：
        else if (uploadName.value == 'antiInterferenceReport') {
            antiInterferenceReport.value = res.data.name
        }
        //背景电能质量测试报告：
        else if (uploadName.value == 'powerQualityReport') {
            powerQualityReport.value = res.data.name
        }
    })
}
// 关联终端
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

        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,
                    feasibilityReport: feasibilityReport.value, //可研报告
                    preliminaryDesignDescription: preliminaryDesignDescription.value, //项目初步设计说明书告地址
                    predictionEvaluationReport: predictionEvaluationReport.value, //预测评估报告告地址
                    predictionEvaluationReviewOpinions: predictionEvaluationReviewOpinions.value, //预测评估评审意见报告地址
                    additionalAttachments: additionalAttachments?.value //其他附件告地址
                }
            }
        }

        if (
            subForm.value.userType == '2' ||
            subForm.value.userType == '3' ||
            subForm.value.userType == '4' ||
            subForm.value.userType == '5'
        ) {
            {
                confirmFormData.userReportSubstationPO = {
                    ...confirmFormData.userReportSubstationPO,
                    feasibilityReport: feasibilityReport.value, //可研报告
                    preliminaryDesignDescription: preliminaryDesignDescription.value, //项目初步设计说明书告地址
                    predictionEvaluationReport: predictionEvaluationReport.value, //预测评估报告告地址
                    predictionEvaluationReviewOpinions: predictionEvaluationReviewOpinions.value, //预测评估评审意见报告地址
                    additionalAttachments: additionalAttachments.value, //其他附件告地址
                    substationMainWiringDiagram: substationMainWiringDiagram.value //用户接入变电站主接线示意图地址
                }
            }
        }
        //userType==6
        if (subForm.value.userType == '6') {
            {
                confirmFormData.userReportSensitivePO = {
                    ...confirmFormData.userReportSensitivePO,
                    feasibilityReport: feasibilityReport.value, //可研报告
                    preliminaryDesignDescription: preliminaryDesignDescription.value, //项目初步设计说明书告地址
                    predictionEvaluationReport: predictionEvaluationReport.value, //预测评估报告告地址
                    predictionEvaluationReviewOpinions: predictionEvaluationReviewOpinions.value, //预测评估评审意见报告地址
                    additionalAttachments: additionalAttachments.value, //其他附件告地址
                    substationMainWiringDiagram: substationMainWiringDiagram.value, //用户接入变电站主接线示意图地址
                    sensitiveDevices: sensitiveDevices.value, //主要敏感终端清单
                    antiInterferenceReport: antiInterferenceReport.value, //抗扰度测试报告
                    powerQualityReport: powerQualityReport.value, //背景电能质量测试报告
                    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()
                addUploadRef.value?.submitForm(res.data)
                resetForm()
                close()
            }).catch(() => {
                loading.value = false
            })
        } else {
            await submitFormData(confirmFormData).then(res => {
                ElMessage({
                    message: '保存成功!',
                    type: 'success'
                })
                ruleFormRef.value.resetFields()
                addUploadRef.value?.submitForm(res.data)
                resetForm()
                close()
            }).catch(() => {
                loading.value = false
            })
        }
    } else {
        await ruleFormRef.value.validate(async (valid: any) => {
            if (valid) {
                //整理上传文件的数据
                // userType==0,1
                addUploadRef.value?.submitForm()
                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') {
                    if (!predictionEvaluationReport.value) {
                        return ElMessage({
                            message: '请上传预测评估报告',
                            type: 'warning'
                        })
                    }
                    if (!predictionEvaluationReviewOpinions.value) {
                        return ElMessage({
                            message: '请上传预测评估评审意见报告',
                            type: 'warning'
                        })
                    } else {
                        //其他报告非必填
                        confirmFormData.userReportProjectPO = {
                            ...confirmFormData.userReportProjectPO,
                            feasibilityReport: feasibilityReport.value, //可研报告
                            preliminaryDesignDescription: preliminaryDesignDescription.value, //项目初步设计说明书告地址
                            predictionEvaluationReport: predictionEvaluationReport.value, //预测评估报告告地址
                            predictionEvaluationReviewOpinions: predictionEvaluationReviewOpinions.value, //预测评估评审意见报告地址
                            additionalAttachments: additionalAttachments?.value //其他附件告地址
                        }
                    }
                }
                //userType==2,3,4,5
                if (
                    subForm.value.userType == '2' ||
                    subForm.value.userType == '3' ||
                    subForm.value.userType == '4' ||
                    subForm.value.userType == '5'
                ) {
                    if (!predictionEvaluationReport.value) {
                        return ElMessage({
                            message: '请上传预测评估报告',
                            type: 'warning'
                        })
                    }
                    if (!predictionEvaluationReviewOpinions.value) {
                        return ElMessage({
                            message: '请上传预测评估评审意见报告',
                            type: 'warning'
                        })
                    }
                    if (!substationMainWiringDiagram.value) {
                        return ElMessage({
                            message: '请上传用户接入变电站主接线示意图',
                            type: 'warning'
                        })
                    }
                    //其他附件非必填
                    else {
                        confirmFormData.userReportSubstationPO = {
                            ...confirmFormData.userReportSubstationPO,
                            feasibilityReport: feasibilityReport.value, //可研报告
                            preliminaryDesignDescription: preliminaryDesignDescription.value, //项目初步设计说明书告地址
                            predictionEvaluationReport: predictionEvaluationReport.value, //预测评估报告告地址
                            predictionEvaluationReviewOpinions: predictionEvaluationReviewOpinions.value, //预测评估评审意见报告地址
                            additionalAttachments: additionalAttachments.value, //其他附件告地址
                            substationMainWiringDiagram: substationMainWiringDiagram.value //用户接入变电站主接线示意图地址
                        }
                    }
                }
                //userType==6
                if (subForm.value.userType == '6') {
                    if (!predictionEvaluationReport.value) {
                        return ElMessage({
                            message: '请上传预测评估报告',
                            type: 'warning'
                        })
                    }
                    if (!predictionEvaluationReviewOpinions.value) {
                        return ElMessage({
                            message: '请上传预测评估评审意见报告',
                            type: 'warning'
                        })
                    }
                    if (!substationMainWiringDiagram.value) {
                        return ElMessage({
                            message: '请上传用户接入变电站主接线示意图',
                            type: 'warning'
                        })
                    }
                    if (!sensitiveDevices.value) {
                        return ElMessage({
                            message: '请上传主要敏感终端清单',
                            type: 'warning'
                        })
                    }
                    if (!antiInterferenceReport.value) {
                        return ElMessage({
                            message: '请上传抗扰度测试报告',
                            type: 'warning'
                        })
                    }
                    if (!powerQualityReport.value) {
                        return ElMessage({
                            message: '请上传背景电能质量测试报告',
                            type: 'warning'
                        })
                    }
                    //其他附件非必填
                    else {
                        confirmFormData.userReportSensitivePO = {
                            ...confirmFormData.userReportSensitivePO,
                            feasibilityReport: feasibilityReport.value, //可研报告
                            preliminaryDesignDescription: preliminaryDesignDescription.value, //项目初步设计说明书告地址
                            predictionEvaluationReport: predictionEvaluationReport.value, //预测评估报告告地址
                            predictionEvaluationReviewOpinions: predictionEvaluationReviewOpinions.value, //预测评估评审意见报告地址
                            additionalAttachments: additionalAttachments.value, //其他附件告地址
                            substationMainWiringDiagram: substationMainWiringDiagram.value, //用户接入变电站主接线示意图地址
                            sensitiveDevices: sensitiveDevices.value, //主要敏感终端清单
                            antiInterferenceReport: antiInterferenceReport.value, //抗扰度测试报告
                            powerQualityReport: powerQualityReport.value, //背景电能质量测试报告
                            energyQualityIndex: confirmFormData.userReportSensitivePO.energyQualityIndex.join(', ')
                        }
                    }
                }
                confirmFormData.saveOrCheckflag = '2'
                if (controFlag.value) confirmFormData.dataType = 1
                if (title.value == '用户档案录入') {
                    await submitFormData(confirmFormData).then(res => {
                        ElMessage({
                            message: '新增成功',
                            type: 'success'
                        })
                        ruleFormRef.value.resetFields()
                        addUploadRef.value?.submitForm(res.data)
                        resetForm()
                        close()
                    }).catch(() => {
                loading.value = false
            })
                } else {
                    confirmFormData.id = resendId.value
                    if (controFlag.value) confirmFormData.dataType = 1

                    if (props.normalizedControl) {
                        if (title.value == '编辑') {
                            if (status.value != '') confirmFormData.status = status.value
                            await addEditor(confirmFormData).then(res => {
                                ElMessage({
                                    message: '发起成功',
                                    type: 'success'
                                })
                                ruleFormRef.value.resetFields()
                                addUploadRef.value?.submitForm(res.data)
                                resetForm()
                                close()
                            }).catch(() => {
                loading.value = false
            })
                        } else {
                            await resend(confirmFormData).then(res => {
                                ElMessage({
                                    message: '重新发起成功',
                                    type: 'success'
                                })
                                ruleFormRef.value.resetFields()
                                resetForm()
                                close()
                            }).catch(() => {
                loading.value = false
            })
                        }
                    } else {
                        await updateFormData(confirmFormData).then(res => {
                            ElMessage({
                                message: '重新发起成功',
                                type: 'success'
                            })
                            addUploadRef.value?.submitForm(res.data)
                            ruleFormRef.value.resetFields()
                            resetForm()
                            close()
                        }).catch(() => {
                loading.value = false
            })
                    }
                }
            } else {
                console.log('表单验证失败')
                return 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>
