<template>
    <div class="edit-popup">

        <popup ref="popupRef" :title="popupTitle" :async="true" width="80%" @confirm="handleSubmit"
            @close="handleClose">

            <el-form ref="formRef" :model="formData" label-width="auto" :rules="formRules">
                <el-row :gutter="10">
                    <el-col :span="8">
                        <el-form-item label="组织名称" prop="org_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-select v-model="formData.org_id" clearable placeholder="请选择组织" @change="deptrmt"
                                class="flex-1">
                                <el-option v-for="(item, index) in list1" :key="index" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="部门名称" prop="dept_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-select v-model="formData.dept_id" clearable placeholder="请选择部门" class="flex-1">
                                <el-option v-for="( item, index ) in  list2 " :key="index" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project_id" @click="showDialog = true">
                            <el-input v-model="project_name" clearable placeholder="请输入项目名称" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="检测任务" prop="detection_task">
                            <el-input v-model="formData.detection_task" clearable placeholder="请输入检测任务" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="所属阶段" prop="owning_stage">
                            <el-input v-model="formData.owning_stage" clearable placeholder="请输入所属阶段" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="责任人" prop="resp_user">
                            <el-input v-model="formData.resp_user" clearable placeholder="请输入责任人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="标准工期" prop="standard_duration">
                            <el-input v-model="formData.standard_duration" clearable placeholder="请输入标准工期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="计划开始时间" prop="scheduled_start_time">
                            <el-date-picker v-model="formData.scheduled_start_time" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="选择计划开始时间" class="flex-1 !flex">
                            </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="计划结束时间" prop="scheduled_end_time">
                            <el-date-picker v-model="formData.scheduled_end_time" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="选择计划结束时间" class="flex-1 !flex">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否完成" prop="complete">
                            <el-input v-model="formData.complete" clearable placeholder="请输入是否完成" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="实际开始时间" prop="actual_start_time">
                            <el-date-picker v-model="formData.actual_start_time" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="选择实际开始时间" class="flex-1 !flex">
                            </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="实际结束时间" prop="actual_end_time">
                            <el-date-picker v-model="formData.actual_end_time" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="选择实际结束时间" class="flex-1 !flex">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>



                    <el-col :span="8">
                        <el-form-item label="资料编号" prop="document_number">
                            <el-input v-model="formData.document_number" clearable placeholder="请输入资料编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="资料名称" prop="document_name">
                            <el-input v-model="formData.document_name" clearable placeholder="请输入资料名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="文件稿本" prop="document_manuscript">
                            <el-input v-model="formData.document_manuscript" clearable placeholder="请输入文件稿本" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="是否归档" prop="archiving">
                            <el-input v-model="formData.archiving" clearable placeholder="请输入是否归档" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="资料内容要求" prop="data_content_requirements">
                            <el-input v-model="formData.data_content_requirements" clearable placeholder="请输入资料内容要求" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="检测情况" prop="detection_situation">
                            <el-input v-model="formData.detection_situation" clearable placeholder="请输入检测情况" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" clearable type="textarea" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="24">

                        <el-form-item label="附件" prop="field127">
                            <el-upload
                                accept="doc, docx, xls, xlsx, ppt, pptx, pdf, txt, zip, rar, tar, jpg, png, gif, jpeg, webp, wmv, avi, mpg, mpeg, 3gp, mov, mp4, flv, f4v, rmvb, mkv"
                                class="upload-demo" :show-file-list="false" aria-hidden="true"
                                :headers="{ Token: userStore.token }" :action="base_url + '/upload/file'"
                                :on-success="handleAvatarSuccess_four" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="( item, index ) in  formDataannex "
                                    style="margin-left: 5px;display: block;">
                                    <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start"
                                        :href="item.uri" target="_blank">{{ item.name }}</a>
                                    <span style="cursor: pointer;margin-left: 5px;" @click="delFileFn(index)">x</span>
                                </div>
                            </div>

                        </el-form-item>
                    </el-col>
                </el-row>


                <el-dialog v-model="showDialog" title="选择项目" width="70%">
                    <porjectDialog @customEvent="customEvent"></porjectDialog>
                </el-dialog>


            </el-form>
        </popup>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import porjectDialog from '@/components/project/index.vue'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { qualitydetectionAdd, qualitydetectionEdit, qualitydetectionDetail } from '@/api/quality_detection'
import { toChinesNum } from "@/utils/util";
import { getAllProjectTypes } from '@/api/projecttype'
import { timeFormat } from '@/utils/util'
import { isEmail, isIdCard, isPhone } from '@/utils/validate'
import type { PropType } from 'vue'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
const protype = reactive([])
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const active = ref(0)
const formDataannex = reactive([])
const list1 = reactive([])
const list2 = reactive([])
const showDialog = ref(false)
const project_name = ref('')
import feedback from '@/utils/feedback'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
const userInfo = userStore.userInfo
// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }


    );
};

// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
//获取值
const customEvent = (e: any) => {
    formData.project_id = e.id;
    project_name.value = e.name;
    showDialog.value = false;
};

//获取所有组织
const getlist = () => {
    getAll().then((res) => {
        Object.assign(list1, res)

    })
}
//获取部门
const deptrmt = (e: any) => {
    formData.dept_id = ''
    getlist1(e)

}
//获取所有部门
const getlist1 = (id: any) => {
    deptAll({ 'org_id': id }).then((res) => {
        list2.splice(0, list2.length, ...res)
    })
}

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑质量检测表' : '新增质量检测表'
})

// 表单数据
const formData = reactive({
    id: '',
    dept_id: '',
    org_id: "",
    project_id: "",
    detection_task: "",
    owning_stage: "",
    resp_user: "",
    standard_duration: "",
    scheduled_start_time: "",
    scheduled_end_time: "",
    complete: "",
    actual_start_time: "",
    actual_end_time: "",
    document_number: "",
    document_name: "",
    document_manuscript: "",
    archiving: "",
    data_content_requirements: "",
    detection_situation: "",
    remark: "",
    file: [],

})


// 表单验证
const formRules = reactive<any>({

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    if (data.file && data.file.length > 0) {

        const arry1 = data.file.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)

    }


    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    if (data.dept_id) {
        getlist1(data.dept_id
        )
    }

    project_name.value = data.project_name


}
const getDetail = async (row: Record<string, any>) => {
    const data = await qualitydetectionDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    formData.file = formDataannex.map((item) => item.uri)



    const startTime = new Date(formData.actual_start_time)
    const endTime = new Date(formData.actual_end_time)
    if (endTime < startTime) {
        feedback.msgError("实际结束时间不能小于实际开始时间");
        return
    } else if (startTime > endTime) {
        feedback.msgError("实际开始时间不能大于实际结束时间");
        return
    } else {
    }


    const startTime1 = new Date(formData.scheduled_start_time)
    const endTime1 = new Date(formData.scheduled_end_time)
    if (endTime1 < startTime1) {
        feedback.msgError("计划结束时间不能小于计划开始时间");
        return
    } else if (startTime1 > endTime1) {
        feedback.msgError("计划开始时间不能大于计划结束时间");
        return
    } else {
    }


    await formRef.value?.validate()


    const data = { ...formData }
    mode.value == 'edit'
        ? await qualitydetectionEdit(data)
        : await qualitydetectionAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
    getlist()

}

// 关闭回调
const handleClose = () => {
    emit('close')
}



defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
