<template>
    <el-dialog draggable :title="title" v-model="planAddition" width="65%" :before-close="cancelFn">
        <el-form
            :model="formdata"
            :disabled="title == '查看计划' || title == '计划审核'"
            ref="formRef"
            :rules="rules"
            label-width="auto"
            class="form-two"
        >
            <el-form-item label="普测负责单位:">
                <Area v-model="formdata.orgNo" disabled />
            </el-form-item>
            <el-form-item label="计划名称:" prop="planName">
                <el-input v-model="formdata.planName" placeholder="请输入计划名称"></el-input>
            </el-form-item>
            <el-form-item label="计划开始时间:" prop="planStartTime">
                <el-date-picker
                    v-model="formdata.planStartTime"
                    type="date"
                    placeholder="选择计划开始时间"
                    value-format="YYYY-MM-DD"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="计划结束时间:" prop="planEndTime">
                <el-date-picker
                    v-model="formdata.planEndTime"
                    type="date"
                    placeholder="选择计划结束时间"
                    value-format="YYYY-MM-DD"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="实际完成时间:" prop="planComplateTime">
                <el-date-picker
                    v-model="formdata.planComplateTime"
                    type="date"
                    placeholder="选择实际完成时间"
                    value-format="YYYY-MM-DD"
                ></el-date-picker>
            </el-form-item>

            <el-form-item label="测试负责人:" prop="leader">
                <el-input v-model="formdata.leader" placeholder="请输入测试负责人"></el-input>
            </el-form-item>

            <el-form-item label="关联电站:" prop="subIds">
                <el-cascader v-model="formdata.subIds" :options="treeList" :props="defaultProps" clearable filterable />
                <!-- <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="formdata.subIds"
                    :data="treeList"
                    :render-after-expand="false"
                /> -->
            </el-form-item>
            <!-- <el-form :model="formdata" label-width="auto"> -->
            <el-form-item label="上传文件:" prop="fileList">
                <el-upload
                    v-model:file-list="formdata.fileList"
                    ref="upload"
                    action=""
                    :limit="5"
                    :on-exceed="handleExceed"
                    :auto-upload="false"
                >
                    <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 == '计划审核' || formdata.status == 1 || formdata.status == 3 || formdata.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="formdata.checkComment"
            ></el-input>
        </div> -->
        <template #footer v-if="title != '查看计划'">
            <div class="dialog-footer">
                <el-button type="primary" @click="submitFn">提交</el-button>
                <el-button @click="cancelFn">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import generalTestTree from '@/components/tree/pqs/generalTestTree.vue'
import { ref, reactive, nextTick } from 'vue'
import { addSurvey, auditSurvey } from '@/api/process-boot/generalTest'
import Area from '@/components/form/area/index.vue'
import { ElMessage, UploadProps } from 'element-plus'
import { uploadFile, getFileNameAndFilePath } from '@/api/system-boot/file'
import { useDictData } from '@/stores/dictData'
import { initDetpStataionTree } from '@/api/process-boot/generalTest'
const emit = defineEmits(['onsubmit'])
const dictData = useDictData()
const title = ref('')
const planAddition = ref(false)
const defaultProps = ref({
    label: 'name',
    value: 'id',
    checkStrictly: true,
    emitPath: false,
    expandTrigger: 'hover' as const,
})
const formdata: any = ref({
    orgName: '',
    orgNo: dictData.state.area[0].id,
    planStartTime: '',
    planEndTime: '',
    planComplateTime: '',
    planName: '',
    leader: '',
    rgeneralSurveyPlanDetailAddParm: [],
    subCount: '',
    busCount: '',
    subIds: '',
    fileList: [],
    checkComment: '',
    filePath: ''
})
const props = {
    expandTrigger: 'hover' as const
}
const formRef = ref()
const treeRef = ref()
const rules = {
    planStartTime: [{ required: true, message: '选择计划开始时间', trigger: 'change' }],
    planEndTime: [{ required: true, message: '选择计划结束时间', trigger: 'change' }],
    planComplateTime: [{ required: true, message: '选择实际完成时间	', trigger: 'change' }],
    planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
    leader: [{ required: true, message: '请输入测试负责人', trigger: 'blur' }],
    subIds: [{ required: true, message: '请选择关联电站', trigger: 'change' }],
    fileList: [{ required: true, message: '请上传文件', trigger: 'change' }]
}
const cancelFn = () => {
    formRef.value.resetFields()
    // treeRef.value.setKey([])
    planAddition.value = false
}
const treeList = ref()
const loadData = () => {
    initDetpStataionTree({ orgId: dictData.state.area[0].id }).then(res => {
        treeList.value = res.data
        console.log(treeList.value)
    })
}
loadData()
// 提交
const submitFn = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            let filePath = ''
            // formdata.value.subIds = treeRef.value.treeRef.getCheckedKeys(false)
            formdata.value.subIds= typeof(formdata.value.subIds)=='string'?[formdata.value.subIds]:formdata.value.subIds
            if (formdata.value.fileList.length == 0) {
                audit(filePath)
            } else {
                for (let i = 0; i < formdata.value.fileList.length; i++) {
                    if (formdata.value.fileList[i].raw) {
                        await uploadFile(formdata.value.fileList[i].raw, 'supervision/').then(res => {
                            filePath = filePath + res.data.name + ','
                        })
                    } else {
                        filePath = filePath + formdata.value.fileList[i].supervision + ','
                    }

                    if (i == formdata.value.fileList.length - 1) {
                        audit(filePath)
                    }
                }
            }
        }
    })
}

const audit = (filePath: any) => {
    if (title.value == '普测计划新增') {
        addSurvey({ ...formdata.value, filePath: filePath }).then((res: any) => {
            ElMessage.success('新增成功!')
            cancelFn()
            emit('onsubmit')
        })
    } else if (title.value == '重新发起计划') {
        auditSurvey({ ...formdata.value, filePath: filePath }).then((res: any) => {
            ElMessage.success('重新发起计划成功!')
            cancelFn()
            emit('onsubmit')
        })
    }
}
// 上传文件
// 文件数超出提示
const handleExceed: UploadProps['onExceed'] = (): void => {
    ElMessage.error(`上传文件数量不能超过5个!`)
}

const open = (text: string, row?: any) => {
    formdata.value = Object.assign({
        orgName: '',
        orgNo: dictData.state.area[0].id,
        planStartTime: '',
        planEndTime: '',
        planComplateTime: '',
        planName: '',
        leader: '',
        rgeneralSurveyPlanDetailAddParm: [],
        subCount: '',
        busCount: '',
        subIds: [],
        checkComment: '',
        fileList: [],
        filePath: []
    })
    title.value = text
    planAddition.value = true
    formRef.value?.resetFields()

    // if (row) {
    //     formdata.value = JSON.parse(JSON.stringify(row))
    //     nextTick(() => {
    //         formdata.value.fileList = []
    //         treeRef.value.loadData()
    //         treeRef.value.setKey(row.subIds || [], text)
    //         let arr = row.filePath.split(',')
    //         arr.slice(0, -1).forEach((item: any) => {
    //             getFileNameAndFilePath({ filePath: item }).then((res: any) => {
    //                 formdata.value.fileList.push({
    //                     name: res.data.fileName,
    //                     supervision: res.data.name,
    //                     url: res.data.url
    //                 })
    //             })
    //         })
    //     })
    // } else {
    //     nextTick(() => {
    //         treeRef.value.loadData()
    //     })
    // }
}

defineExpose({ open })
</script>
<style lang="scss" scoped>
:deep(.el-upload-list__item-info) {
    width: 250px;
}
</style>
