<template>
    <el-dialog draggable :title="title" v-model="planAddition" width="500px" :before-close="cancelFn">
        <el-form
            :model="form"
            ref="formRef"
            :rules="rules"
            label-width="auto"
            scroll-to-error
            :validate-on-rule-change="false"
            class="form-one"
        >
            <el-form-item for="-" label="计划负责单位:">
                <Area v-model="form.deptId" @change="changeArea" />
            </el-form-item>
            <el-form-item for="-" label="计划名称:" prop="planName">
                <el-input
                    v-model="form.planName"
                    placeholder="请输入计划名称"
                    clearable
                    maxlength="32"
                    show-word-limit
                ></el-input>
            </el-form-item>
            <el-form-item label="监督类型:" prop="supvType">
                <el-select v-model="form.supvType" placeholder="请选择监督类型" style="width: 100%" @change="++key" filterable>
                    <el-option
                        v-for="item in supvTypeOptionList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item for="-" label="监督对象名称:" prop="supvObjectName">
                <el-input
                    v-model="form.supvObjectName"
                    placeholder="请输入监督对象名称"
                    clearable
                    maxlength="32"
                    show-word-limit
                ></el-input>
            </el-form-item>
            <el-form-item for="-" label="计划开始时间:" prop="planStartTime">
                <el-date-picker
                    v-model="form.planStartTime"
                    type="date"
                    placeholder="选择计划开始时间"
                    value-format="YYYY-MM-DD"
                    :disabled-date="disableStartDate"
                ></el-date-picker>
            </el-form-item>
            <el-form-item for="-" label="计划结束时间:" prop="planEndTime">
                <el-date-picker
                    v-model="form.planEndTime"
                    type="date"
                    placeholder="选择计划结束时间"
                    :disabled-date="disableEndDate"
                    value-format="YYYY-MM-DD"
                ></el-date-picker>
            </el-form-item>
            <!-- <el-form-item for="-" label="实际完成时间:" prop="planComplateTime">
                <el-date-picker
                    v-model="form.planComplateTime"
                    type="date"
                    placeholder="选择实际完成时间"
                    value-format="YYYY-MM-DD"
                ></el-date-picker>
            </el-form-item> -->
            <!-- <el-form-item for="-" label="测试负责人:" prop="leader">
                <el-input v-model="form.leader" placeholder="请输入测试负责人"></el-input>
            </el-form-item> -->
            <el-form-item for="-" label="系统电站：" prop="customSubstationFlag">
                <!-- 默认值 开启 -->
                <el-radio-group v-model="form.customSubstationFlag" @change="changeSubstationFlag">
                    <el-radio :value="0">是</el-radio>
                    <el-radio :value="1">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item
                :key="key"
                label="关联电站:"
                v-if="form.customSubstationFlag == 0"
                :prop="dynamicProp"
                style="display: flex; align-items: center"
            >
                <el-cascader
                    v-model="form.substation"
                    :options="treeData"
                    :props="defaultProps"
                    clearable
                    filterable
                    collapse-tags
                    collapse-tags-tooltip
                    placeholder="请选择关联电站"
                />
                <!-- <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.substation"
                    :data="treeList"
                    :render-after-expand="false"
                /> -->
            </el-form-item>

            <el-form-item
                for="-"
                label="关联电站:"
                :key="key"
                v-if="form.customSubstationFlag == 1"
                :prop="dynamicProp"
            >
                <el-input v-model="form.substation" placeholder="名称格式：220kV某某电站"></el-input>
            </el-form-item>
            <!-- <el-form :model="form" label-width="auto"> -->
            <!-- <el-form-item for="-" class="uploadFile" label="普测报告:" prop="fileList">
                <el-upload
                    v-model:file-list="form.fileList"
                    ref="upload"
                    action=""
                    :limit="5"
                    :on-exceed="handleExceed"
                    :auto-upload="false"
                    :on-remove="removeFile"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
</el-upload>
</el-form-item> -->
            <!-- </el-form> -->
        </el-form>
        <!-- <el-divider content-position="left" style="font-size: 18px; font-weight: bolder">添加电站</el-divider> -->
        <!-- <generalTestTree ref="treeRef" /> -->
        <!-- <div
            v-if="
                (title == '查看计划' || title == '计划审核') &&
                (title == '计划审核' || form.status == 1 || form.status == 3 || form.status == 4)
            "
        >
            <el-divider content-position="left" style="font-size: 18px; font-weight: bolder">审核意见</el-divider>
            <el-input
                :disabled="title != '计划审核'"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                v-model="form.checkComment"
            ></el-input>
        </div> -->
        <template #footer v-if="title != '查看计划'">
            <div class="dialog-footer">
                <el-button @click="cancelFn">取消</el-button>

                <el-button type="primary" @click="submitFn(true)" :loading="loading">保存</el-button>
                <el-button type="primary" @click="submitFn(false)" :loading="loading">提交审批</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import {
    addSurvey,
    auditSurvey,
    addSurveyPlan,
    getById,
    initDetpStataionTree,
    updateSurveyPlan
} from '@/api/process-boot/generalTest'
import Area from '@/components/form/area/index.vue'
import { ElMessage, UploadProps } from 'element-plus'

import { useDictData } from '@/stores/dictData'
const VITE_FLAG = import.meta.env.VITE_NAME == 'jibei'
const emit = defineEmits(['onsubmit'])
const loading = ref(false)
const dictData = useDictData()
const supvTypeOptionList = dictData.getBasicData('supv_type')
const title = ref('')
const planAddition = ref(false)
const key: any = ref(0)
const dynamicProp = computed(() => {
    // report_supervision
    let code = supvTypeOptionList.filter(item => item.id === form.value.supvType)[0]?.code
    return code == 'Technical_Super' ? '' : code == 'report_supervision' ? '' : 'substation'
})

const defaultProps = ref({
    label: 'name',
    value: 'id',
    checkStrictly: true,
    emitPath: false,
    expandTrigger: 'hover' as const,
    multiple: true
})
//开始时间不能大于结束时间
const disableStartDate = (time: any) => {
    if (time && form.value.planEndTime) {
        return time.getTime() > new Date(form.value.planEndTime).getTime()
    } else {
        return false
    }
}
//结束时间不能小于开始时间
const disableEndDate = (time: any) => {
    if (time && form.value.planStartTime) {
        return time.getTime() <= new Date(form.value.planStartTime).getTime() - 8.64e7
    } else {
        return false
    }
}
const form: any = ref({
    // orgName: '',
    deptId: dictData.state.area[0].id,
    planStartTime: '',
    planEndTime: '',
    planName: '',
    // fileList: [],
    // checkComment: '',
    // filePath: '',
    substation: '', //关联电站
    customSubstationFlag: 0 //电站类型
})
const props = {
    expandTrigger: 'hover' as const
}
const formRef = ref()
const treeRef = ref()
const rules = ref({
    planStartTime: [{ required: true, message: '选择计划开始时间', trigger: 'change' }],
    planEndTime: [{ required: true, message: '选择计划结束时间', trigger: 'change' }],
    supvType: [{ required: true, message: '请选择监督类型', trigger: 'change' }],
    planComplateTime: [{ required: true, message: '选择实际完成时间	', trigger: 'change' }],
    supvObjectName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
    planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
    leader: [{ required: true, message: '请输入测试负责人', trigger: 'blur' }],
    substation: [{ required: true, message: '请选择关联电站', trigger: 'blur' }]
    // fileList: [{ required: true, message: '请上传文件', trigger: 'change' }],
})
const changeSubstationFlag = () => {
    console.log(form.value.customSubstationFlag)
    //处理所属变电站手都输入1/下拉数据0
    key.value += 1
    if (form.value.customSubstationFlag == 0) {
        rules.value.substation[0].message = '请选择关联电站'
        form.value.substation = []
    } else {
        rules.value.substation[0].message = '请输入关联电站'
        form.value.substation = ''
    }
}
const cancelFn = () => {
    formRef.value?.resetFields()
    // treeRef.value.setKey([])
    planAddition.value = false
}
const treeList = ref()
const treeListCgy = ref()
const treeData = ref()
const loadData = () => {
    initDetpStataionTree({ orgId: dictData.state.area[0].id }).then(res => {
        treeList.value = res.data

        initDetpStataionTree({ orgId: 'a3069759b0b6072c99cf9a7af6c162e9' }).then(res => {
            treeListCgy.value = res.data
            setTimeout(() => {
                changeArea()
            }, 10)
        })
    })
}

const detailById = (id: any) => {
    getById(id).then(res => {
        form.value = res.data

        form.value.substation =
            res.data.customSubstationFlag == 0 ? res.data.substation.split(',') : res.data.substation
        key.value += 1
    })
}
// 提交
const submitFn = async (flag: boolean) => {
    loading.value = true
    if (flag) {
        const addForm = JSON.parse(JSON.stringify(form.value))

        if (form.value.customSubstationFlag == 0) {
            addForm.substation = addForm.substation.length == 0 ? '' : addForm.substation.join(',')
        }
        addForm.saveOrCheckflag = '1'

        await addSurveyPlan(addForm)
            .then(res => {
                cancelFn()
                ElMessage.success('保存成功！')
                emit('onsubmit')
            })
            .catch(() => {
                loading.value = false
            })
    } else {
        formRef.value.validate(async (valid: any) => {
            if (valid) {
                //选择系统变电站
                const addForm = JSON.parse(JSON.stringify(form.value))
                if (form.value.customSubstationFlag == 0) {
                    addForm.substation = addForm.substation.length == 0 ? '' : addForm.substation.join(',')
                }
                addForm.saveOrCheckflag = '2'
                if (title.value == '计划新增') {
                    await addSurveyPlan(addForm)
                        .then(res => {
                            cancelFn()
                            ElMessage.success('计划新增成功！')
                            emit('onsubmit')
                        })
                        .catch(() => {
                            loading.value = false
                        })
                } else {
                    await updateSurveyPlan(addForm)
                        .then(res => {
                            cancelFn()
                            ElMessage.success('重新发起成功！')
                            emit('onsubmit')
                        })
                        .catch(() => {
                            loading.value = false
                        })
                }
            }
        })
    }
    await setTimeout(() => {
        loading.value = false
    }, 0)
}
// 修改关联电站
const changeArea = () => {
    let list: any = []
    if (VITE_FLAG) {
        treeList.value.forEach((item: any) => {
            if (item.id == form.value.deptId) {
                list.push(item)
                if (
                    item.id != treeListCgy.value[0].id &&
                    !item.name.includes('电力有限公司') &&
                 
                    item.name != '超高压'
                ) {
                    list.push(...treeListCgy.value)
                }
            } else {
                list.push(item.children.filter((v: any) => v.id == form.value.deptId)[0])
                if (form.value.deptId != treeListCgy.value[0].id) {
                    list.push(...treeListCgy.value)
                }
            }
        })
    } else {
        treeList.value.forEach((item: any) => {
            if (item.id == form.value.deptId) {
                list.push(item)
            } else {
                list.push(item.children.filter((v: any) => v.id == form.value.deptId)[0])
            }
        })
    }

    treeData.value = list
}
const audit = (filePath: any) => {
    return
}
// 上传文件
// 文件数超出提示
const handleExceed: UploadProps['onExceed'] = (): void => {
    ElMessage.error(`上传文件数量不能超过5个!`)
}
//移除文件上传
const removeFile = (file: any, uploadFiles: any) => {
    console.log(file, uploadFiles)
}
const open = (text: string, id: any) => {
    loadData()
    form.value = Object.assign({
        // orgName: '',
        deptId: dictData.state.area[0].id,
        planStartTime: '',
        planEndTime: '',
        planName: '',
        substation: '', //关联电站
        customSubstationFlag: 0 //电站类型
    })
    title.value = text
    planAddition.value = true
    setTimeout(() => {
        key.value += 1
    }, 10)
    if (id) {
        detailById(id)
    }
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
// :deep(.el-upload-list__item-info) {
//     width: 250px;
// }
</style>
