<template>
    <el-dialog draggable :title="title" width="900px" v-model="planAddition" :before-close="cancelFn">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="auto" class="form-two" scroll-to-error>
            <el-form-item label="计划负责单位:">
                <el-input v-model="form.deptName" disabled></el-input>
            </el-form-item>
            <el-form-item label="计划名称:" prop="planName">
                <el-input v-model="form.planName" disabled></el-input>
            </el-form-item>
            <el-form-item label="监督类型:">
                <el-input v-model="form.supvType" disabled></el-input>
            </el-form-item>
            <el-form-item label="监督对象名称:">
                <el-input v-model="form.supvObjectName" disabled></el-input>
            </el-form-item>
            <el-form-item label="计划开始时间:" prop="planStartTime">
                <el-input v-model="form.planStartTime" disabled></el-input>
            </el-form-item>
            <el-form-item label="计划结束时间:" prop="planEndTime">
                <el-input v-model="form.planEndTime" disabled></el-input>
            </el-form-item>
            <el-form-item for="-" label="测试变电站:" prop="subIds" style="display: flex; align-items: center">
                <el-input v-model="form.substationName" disabled />
            </el-form-item>
            <el-form-item label="实际完成时间:" prop="completeTime">
                <el-date-picker
                    v-model="form.completeTime"
                    type="date"
                    placeholder="选择实际完成时间"
                    value-format="YYYY-MM-DD"
                ></el-date-picker>
            </el-form-item>
            <el-form-item for="-" label="测试负责人:" prop="completeBy">
                <el-input v-model="form.completeBy" placeholder="请输入测试负责人"></el-input>
            </el-form-item>
            <el-form-item for="-" label="测试是否有问题：" prop="problemFlag">
                <!-- 默认值 否 -->
                <el-radio-group v-model="form.problemFlag">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item for="-" class="uploadFile" label="技术监督报告:" prop="supervisionReport">
                <el-upload
                    ref="uploadRef"
                    v-model:file-list="form.supervisionReport"
                    action=""
                    :accept="acceptType"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="event => choose(event, 'supervisionReport')"
                    :auto-upload="false"
                >
                    <!-- :on-progress="uploadFileName('supervisionReport')" -->
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item for="-" class="uploadFile" label="测试报告:" prop="testReport">
                <el-upload
                    ref="upload1Ref"
                    v-model:file-list="form.testReport"
                    action=""
                    :accept="acceptType"
                    :limit="1"
                    :on-exceed="handleExceed1"
                    :on-change="event => choose(event, 'testReport')"
                    :auto-upload="false"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item for="-" class="uploadFile" label="其他报告:">
                <el-upload
                    ref="upload2Ref"
                    v-model:file-list="form.otherReport"
                    action=""
                    :accept="acceptType"
                    :on-exceed="handleExceed2"
                    :on-change="event => choose(event, 'otherReport')"
                    :auto-upload="false"
                >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>

            <el-form-item
                style="width: 100%"
                for="-"
                label="问题描述:"
                prop="problemDetail"
                v-if="form.problemFlag == '1'"
            >
                <el-input type="textarea" v-model="form.problemDetail" placeholder="请输入问题描述"></el-input>
            </el-form-item>
            <!-- </el-form> -->
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelFn">取消</el-button>
                <!-- <el-button type="primary" @click="submitFn">确定</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, inject, nextTick } from 'vue'
import { addSurvey, auditSurvey } from '@/api/process-boot/generalTest'
import TableStore from '@/utils/tableStore' // 若不是列表页面弹框可删除
import { ElMessage, genFileId, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { uploadFile, getFileNameAndFilePath } from '@/api/system-boot/file'
import { useDictData } from '@/stores/dictData'
import { addSurveyTest, updateSurveyTest, getTestById } from '@/api/supervision-boot/survey/test'
const loading = ref(false)
const acceptType = ref('')
const tableStore = inject('tableStore') as TableStore
let uploadName = ref('')
// 上传报告
const uploadRef = ref()
const upload1Ref = ref()
const upload2Ref = ref()
const fileList = ref<UploadUserFile[]>([])
const emit = defineEmits(['onsubmit'])
const dictData = useDictData()
const supvTypeOptionList = dictData.getBasicData('supv_type')
const addFlagRef = ref(true)
const title = ref('')
const planAddition = ref(false)
const form: any = ref({
    id: '',
    deptName: '',
    planStartTime: '',
    planEndTime: '',
    planName: '',
    substationName: '',
    completeTime: '',
    completeBy: '',
    testReport: [],
    otherReport: [],
    supervisionReport: [],
    problemDetail: '', //测试问题
    problemFlag: 0 //是否有问题
})

/**
 * addFlag为true，则为填报测试数据，创建新流程
 * 为false，则为修改测试数据，重新发起流程
 */
const open = async (text: string, id: string, addFlag: boolean) => {
    title.value = text
    formRef.value?.resetFields()
    addFlagRef.value = addFlag
    //根据测试id获取数据
    await getTestById(id).then(res => {
        //如果是新增，则只需将计划的一些信息回显即可
        form.value.id = id
        form.value.deptName = res.data.deptName
        form.value.planStartTime = res.data.planStartTime
        form.value.planEndTime = res.data.planEndTime
        form.value.planName = res.data.planName
        form.value.supvType = supvTypeOptionList.find(item => {
            return item.id == res.data.supvType
        })?.name
        form.value.supvObjectName = res.data.supvObjectName
        form.value.substationName = res.data.substationName
        //部分清空
        // uploadRef.value?.clearFiles()
        form.value.completeTime = ''
        form.value.completeBy = ''
        form.value.testReport = []
        form.value.otherReport = []
        form.value.supervisionReport = []
        form.value.problemDetail = ''
        form.value.problemFlag = 0
        fileList.value = []

        if (!addFlag) {
            //还需回显上次填报的测试数据 todo...,待重新发起的时候去做
            form.value = {
                ...form.value,
                completeTime: res.data.completeTime,
                completeBy: res.data.completeBy,
                problemFlag: res.data.problemFlag,
                testReport:
                    res.data.testReport == null
                        ? []
                        : [
                              {
                                  name: res.data.testReport.split('/')[2]
                              }
                          ],
                supervisionReport:
                    res.data.supervisionReport == null
                        ? []
                        : [
                              {
                                  name: res.data.supervisionReport.split('/')[2]
                              }
                          ],

                // otherReport:
                //     res.data.otherReport == null
                //         ? []
                //         : [
                //               {
                //                   name: res.data.otherReport.split('/')[2]
                //               }
                //           ],

                problemDetail: res.data.problemDetail
            }
            form.value.otherReport = []
            if (res.data.otherReport != null) {
                for (let i = 0; i < res.data.otherReport.split(',').length - 1; i++) {
                    form.value.otherReport.push({
                        name: res.data.otherReport.split(',')[i]
                    })
                }
            }

            testReport.value = res.data.testReport
            otherReport.value = res.data.otherReport
            supervisionReport.value = res.data.supervisionReport
        }
    })

    planAddition.value = true
}

//处理成效报告
const testReport = ref('')
const otherReport = ref('')
const supervisionReport = ref('')

const formRef = ref()
const rules = {
    completeTime: [{ required: true, message: '选择实际完成时间	', trigger: 'change' }],
    completeBy: [{ required: true, message: '请输入测试负责人', trigger: 'blur' }],
    testReport: [{ required: true, message: '请上传文件', trigger: 'change' }],
    otherReport: [{ required: true, message: '请上传文件', trigger: 'change' }],
    supervisionReport: [{ required: true, message: '请上传文件', trigger: 'change' }],
    problemFlag: [{ required: true, message: '请选择测试是否有问题', trigger: 'change' }],
    problemDetail: [{ required: true, message: '请输入测试问题', trigger: 'blur' }]
}
const cancelFn = () => {
    formRef.value.resetFields()
    planAddition.value = false
}
// 提交
const submitFn = async (flag: boolean) => {
    loading.value = true
    const subForm = JSON.parse(JSON.stringify(form.value))
    subForm.otherReport = ''

    if (form.value.otherReport.length > 0) {
        form.value.otherReport.forEach((item: any) => {
            // + '/supervision/'
            subForm.otherReport = subForm.otherReport + item.name + ','
        })
    }
    if (flag) {
        subForm.testReport = testReport.value
        subForm.supervisionReport = supervisionReport.value
        subForm.saveOrCheckflag = '1'

        //新增，则组装业务数据提交后台
        await addSurveyTest(subForm).then(res => {
            ElMessage.success('保存成功!')
            tableStore.index()
            planAddition.value = false
        })
        //查询进线数据，避免一直处于loading状态
    } else {
        formRef.value.validate(async (valid: any) => {
            if (!testReport.value) {
                return ElMessage({
                    message: '请上传处理成效报告！',
                    type: 'warning'
                })
            }

            if (!supervisionReport.value) {
                return ElMessage({
                    message: '请上传技术监督报告！',
                    type: 'warning'
                })
            }
            if (valid) {
                subForm.testReport = testReport.value
                // subForm.otherReport = otherReport.value
                subForm.supervisionReport = supervisionReport.value
                subForm.saveOrCheckflag = '2'
                if (addFlagRef.value) {
                    //新增，则组装业务数据提交后台
                    await addSurveyTest(subForm).then(res => {
                        //查询进线数据，避免一直处于loading状态
                        ElMessage.success('申请成功')
                        tableStore.index()
                        planAddition.value = false
                    })
                } else {
                    await updateSurveyTest(subForm).then(res => {
                        //查询进线数据，避免一直处于loading状态
                        ElMessage.success('重新申请成功')
                        tableStore.index()
                        planAddition.value = false
                    })
                }
            }
        })
    }
    await setTimeout(() => {
        loading.value = false
    }, 0)
}
const audit = (filePath: any) => {
    if (title.value == '计划测试填报') {
        addSurvey({ ...form.value, filePath: filePath }).then((res: any) => {
            ElMessage.success('新增成功!')
            emit('onsubmit')
            cancelFn()
        })
    } else if (title.value == '重新发起计划') {
        auditSurvey({ ...form.value, filePath: filePath }).then((res: any) => {
            ElMessage.success('重新发起计划成功!')
            emit('onsubmit')
            cancelFn()
        })
    }
}

defineExpose({ open })

const choose = (e: any, text: string) => {
    if (text == 'testReport') {
        uploadFile(e.raw, '/supervision/').then(res => {
            testReport.value = res.data.name
        })
    } else if (text == 'otherReport') {
        uploadFile(e.raw, '/supervision/').then(res => {
            otherReport.value = res.data.name
        })
    } else {
        uploadFile(e.raw, '/supervision/').then(res => {
            supervisionReport.value = res.data.name
        })
    }
}

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 => {
    upload1Ref.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload1Ref.value!.handleStart(file)
}
const handleExceed2: UploadProps['onExceed'] = files => {
    upload2Ref.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload2Ref.value!.handleStart(file)
}

//上传报告改变
const uploadFileName = val => {
    uploadName.value = val
}
</script>
<style lang="scss" scoped>
// :deep(.el-upload-list__item-info) {
//     width: 250px;
// }
</style>
