<template>
    <el-dialog
        v-model="dialogFormVisible"
        :title="titleButton"
        width="65%"
        :append-to-body="true"
        :before-close="close"
        :close-on-click-modal="false"
        draggable
    >
        <!-- 用户档案录入 新建1 -->
        <el-form
            :model="form"
            :validate-on-rule-change="false"
            :scroll-to-error="true"
            ref="ruleFormRef"
            :rules="rules"
            label-width="auto"
            class="form-two"
        >
            <el-divider content-position="left">干扰源用户基本信息</el-divider>
            <el-form-item label="用户性质：" prop="userType">
                <el-select v-model="form.userType" placeholder="请选择用户性质" :disabled="openType == 'detail'" 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 label="所在地市：" prop="city">
                <el-select v-model="form.city" clearable placeholder="请选择所在地市" :disabled="openType == 'detail'" 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 label="归口管理部门：" prop="responsibleDepartment">
                <el-input
                    v-model="form.responsibleDepartment"
                    autocomplete="off"
                    placeholder="请输入归口管理部门"
                    :disabled="openType == 'detail'"
                />
            </el-form-item>
            <el-form-item label="项目名称：" prop="projectName">
                <el-input
                    v-model="form.projectName"
                    autocomplete="off"
                    placeholder="请输入项目名称"
                    :disabled="openType == 'detail'"
                />
            </el-form-item>
            <el-form-item label="用户状态：" prop="userStatus">
                <el-select v-model="form.userStatus" placeholder="请选择用户状态" :disabled="openType == 'detail'" filterable>
                    <el-option
                        v-for="(item, index) in userStateList"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.label != '可研'"
                        :key="index"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="厂站名称：" prop="substation">
                <el-input
                    v-model="form.substation"
                    autocomplete="off"
                    placeholder="请输入厂站名称"
                    :disabled="openType == 'detail'"
                />
            </el-form-item>
            <el-form-item v-if="form.userType == '0' || form.userType == '1'" label="电压等级：" prop="voltageLevel">
                <el-select
                    v-model="form.voltageLevel"
                    placeholder="请选择电压等级"
                    node-key="id"
                    :disabled="openType == 'detail'"
                    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
                v-if="form.userType == '0' || form.userType == '1'"
                label="预测评估单位："
                prop="evaluationDept"
            >
                <el-select
                    v-model="form.evaluationDept"
                    placeholder="请选择预测评估单位"
                    :disabled="openType == 'detail'" 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 v-if="form.userReportSubstationPO" label="是否需要治理：" prop="needGovernance">
                <el-radio-group v-model="form.userReportSubstationPO.needGovernance" :disabled="openType == 'detail'">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.userReportSubstationPO" label="是否开展背景测试：" prop="backgroundTestPerformed">
                <el-radio-group
                    v-model="form.userReportSubstationPO.backgroundTestPerformed"
                    :disabled="openType == 'detail'"
                >
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-divider content-position="left">
                {{ bussType == 0 ? '入网设计方案审查报告' : '治理工程验收报告' }}
            </el-divider>
            <el-form-item label="填报人：" prop="reporter">
                <el-input v-model="form.reporter" autocomplete="off" :disabled="true" place-holder="请输入填报人" />
            </el-form-item>
            <el-form-item label="填报日期：" prop="reportDate">
                <el-date-picker
                    :disabled="true"
                    style="width: 100%"
                    v-model="form.reportDate"
                    type="date"
                    placeholder="请选择填报日期"
                />
            </el-form-item>
            <el-form-item label="填报部门：" prop="orgId">
                <el-input v-model="form.orgId" :disabled="true" autocomplete="off" />
            </el-form-item>
            <el-form-item
                class="uploadFile"
                :label="bussType == 0 ? '入网设计方案审查报告：' : '治理工程验收报告：'"
                prop="goToNetReport"
            >
                <el-upload
                    v-model:file-list="form.goToNetReport"
                    ref="uploadRef"
                    action=""
                    accept=".doc,.docx,.xlsx,.xls,.pdf"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="choose"
                    :auto-upload="false"
                    :on-remove="removeFile"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item
                class="uploadFile"
                v-if="bussType != 0"
                label="治理方案仿真校验评估报告"
                prop="simulationReportUrl"
            >
                <el-upload
                    v-model:file-list="form.simulationReportUrl"
                    ref="simulationReportRef"
                    action=""
                    accept=".doc,.docx,.xlsx,.xls,.pdf"
                    :limit="1"
                    :on-exceed="handleExceed1"
                    :on-change="choose1"
                    :auto-upload="false"
                    :on-remove="removeFile1"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close()">取消</el-button>
                <!-- <el-button type="primary" @click="confirmForm()">确定</el-button> -->
                <el-button type="primary" @click="confirmForm(true)" :loading="loading">保存</el-button>
                <el-button type="primary" @click="confirmForm(false)" :loading="loading">提交审批</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, defineExpose, defineProps, defineEmits } from 'vue'
import type { UploadProps, UploadRawFile } from 'element-plus'
import { genFileId, ElMessage } from 'element-plus'
import { useDictData } from '@/stores/dictData'
import { useAdminInfo } from '@/stores/adminInfo'
import { uploadFile } from '@/api/system-boot/file'
import { submitGoNet, getFileById, addOrUpdateFile } from '@/api/supervision-boot/interfere/index'
import { getUserReportById } from '@/api/supervision-boot/userReport/form'

const props = defineProps({
    openType: {
        type: String,
        default: 'create'
    },
    id: {
        type: String
    },
    bussType: {
        type: Number
    },
    titleButton: {
        type: String
    }
})
const rules = {
    goToNetReport: [{ required: true, message: '请上传报告', trigger: 'blur' }],
    simulationReportUrl: [{ required: true, message: '请上传报告', trigger: 'blur' }]
}
const loading = ref(false)
const emits = defineEmits(['onSubmit'])
const dictData = useDictData()
const dialogFormVisible = ref(false)

const form: any = ref({})
const ruleFormRef: any = ref(null)
const simulationReportRef: any = ref(null)
//字典获取所在地市
const areaOptionList = dictData.getBasicData('jibei_area')
//字典电压等级
const voltageLevelList = dictData.getBasicData('Dev_Voltage_Stand')
//字典预测评估单位
const evaluationDeptList = dictData.getBasicData('evaluation_dept')

//用户性质数组
const userTypeList = reactive([
    {
        label: '新建电网工程',
        value: 0
    },
    {
        label: '扩建电网工程',
        value: 1
    },
    {
        label: '新建非线性负荷用户',
        value: 2
    },
    {
        label: '扩建非线性负荷用户',
        value: 3
    },
    {
        label: '新建新能源发电站',
        value: 4
    },
    {
        label: '扩建新能源发电站',
        value: 5
    },
    {
        label: '敏感及重要用户',
        value: 6
    }
])
//用户状态数组
const userStateList = reactive([
    {
        label: '可研',
        value: 0
    },
    {
        label: '建设',
        value: 1
    },
    {
        label: '运行',
        value: 2
    },
    {
        label: '退运',
        value: 3
    }
])
//获取登陆用户姓名和部门
const adminInfo = useAdminInfo()
const resetForm = () => {
    form.value = {
        reporter: '', //填报人
        reportDate: new Date(), //填报日期
        orgId: '', //填报部门
        goToNetReport: [], //报告
        simulationReportUrl: [], //报告
        userType: 0, //用户性质
        city: areaOptionList[0].name, //所在地市
        responsibleDepartment: '', //归口管理部门
        projectName: '', //项目名称
        userStatus: userStateList[0].value, //用户状态
        substation: '', //变电站
        backgroundTestPerformed: 0, //是否开展背景测试
        antiInterferenceTest: 0, //是否开展抗扰度测试
        voltageLevel: voltageLevelList[0].id, //电压等级
        evaluationDept: evaluationDeptList[0].name //预测评估单位
    }
    form.value.reporter = adminInfo.$state.name
    form.value.orgId = adminInfo.$state.deptName
}
//初始化数据
resetForm()

const detailLoading = ref(false) // 表单的加载中
const getInfo = async (row?: any) => {
    detailLoading.value = true
    try {
        await getUserReportById(props.id).then(res => {
            form.value = res.data
            form.value.reporter = adminInfo.$state.name
            form.value.orgId = adminInfo.$state.deptName
            form.value.reportDate = new Date()
            if (row) {
                goToNetReport.value = row.otherReport
                simulationReportUrl.value = row.simulationReport
                form.value.id = row.id
                form.value.goToNetReport =
                    row.otherReport == null || row.otherReport == ''
                        ? []
                        : [
                              {
                                  name: row.otherReport.split('/')[2]
                              }
                          ]
                form.value.simulationReportUrl =
                    row.simulationReport == null || row.simulationReport == ''
                        ? []
                        : [
                              {
                                  name: row.simulationReport.split('/')[2]
                              }
                          ]
            }
        })
    } finally {
        detailLoading.value = false
    }
}

const open = (row?: any) => {
    dialogFormVisible.value = true
    goToNetReport.value = ''
    resetForm()
    getInfo(row)
}
const close = () => {
    //重置表单内容
    resetForm()
    dialogFormVisible.value = false
}

// 上传报告
const uploadRef = ref()
const handleExceed: UploadProps['onExceed'] = files => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
}
const handleExceed1: UploadProps['onExceed'] = files => {
    simulationReportRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    simulationReportRef.value!.handleStart(file)
}

//移除文件上传
const removeFile = (file: any, uploadFiles: any) => {
    console.log(file, uploadFiles)
    goToNetReport.value = ''
    form.value.goToNetReport = uploadFiles
}
const removeFile1 = (file: any, uploadFiles: any) => {
    console.log(file, uploadFiles)
    simulationReportUrl.value = ''
    form.value.simulationReportUrl = uploadFiles
}

// 治理工程验收报告数组
const goToNetReport = ref('')
const simulationReportUrl = ref('')

const choose = (e: any) => {
    uploadFile(e.raw, '/supervision/').then(res => {
        //治理工程验收报告
        goToNetReport.value = res.data.name
    })
}
const choose1 = (e: any) => {
    uploadFile(e.raw, '/supervision/').then(res => {
        //治理工程验收报告
        simulationReportUrl.value = res.data.name
    })
}

//提交
const confirmForm = (flag: boolean) => {
    loading.value = true
    if (flag) {
        let data = {
            type: props.bussType,
            userReportId: props.id,
            reportUrl: goToNetReport.value,
            simulationReportUrl: simulationReportUrl.value,
            id: form.value.id || null,
            saveOrCheckflag: '1'
        }
        submitGoNet(data).then((res: any) => {
            ElMessage({
                message: '保存成功！',
                type: 'success'
            })
            emits('onSubmit')
            close()
        })
    } else {
        if (goToNetReport.value == null || goToNetReport.value == '') {
            loading.value = false
            return ElMessage({
                message: props.bussType == 0 ? '请上传入网设计方案审查报告' : '请上传治理工程验收报告',
                type: 'warning'
            })
        }
        let data = {
            type: props.bussType,
            userReportId: props.id,
            reportUrl: goToNetReport.value,
            simulationReportUrl: simulationReportUrl.value,
            id: form.value.id || null,
            saveOrCheckflag: '2'
        }
        submitGoNet(data).then((res: any) => {
            if (res.code === 'A0000') {
                ElMessage({
                    message: '新建流程成功',
                    type: 'success'
                })
                emits('onSubmit')
                close()
            }
        })
    }
    setTimeout(() => {
        loading.value = false
    }, 0)
}

defineExpose({ open })
</script>
