<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80vw" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project_name">
                            <el-input v-model="formData.project_name" clearable placeholder="点击选择项目" readonly
                                @click="showDialog = true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="编号">
                            <el-input v-model="formData.inspection_code" disabled clearable placeholder="系统自动生成" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="巡视类型" prop="inspection_type">
                            <el-select class="flex-1" v-model="formData.inspection_type" clearable placeholder="请选择巡视类型">
                                <el-option v-for="(item, index) in dictData.inspection_type" :key="index" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单位工程" prop="check_item_name">
                            <el-input v-model="formData.check_item_name" clearable placeholder="点击选择单位工程" readonly
                                @click="showDialog1 = true, flag = false" class="!flex flex-1" />
                            <ToolTip content="可在监理工作新增检查项添加节点类型为单位工程的节点"
                                url="/supervision/supervision_work/supervision_check_item"></ToolTip>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="巡视部位" prop="inspection_position">
                            <el-input v-model="formData.inspection_position" clearable placeholder="请输入巡视部位" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="施工人数" prop="workers">
                            <el-input v-model="formData.workers" clearable placeholder="请输入施工人数" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="管理人数" prop="managers">
                            <el-input v-model="formData.managers" clearable placeholder="请输入管理人数" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="巡视开始时间" prop="start_time" label-width="120px">
                            <el-date-picker class="flex-1 !flex" v-model="formData.start_time" clearable type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择巡视开始时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="巡视结束时间" prop="end_time">
                            <el-date-picker class="flex-1 !flex" v-model="formData.end_time" clearable type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择巡视结束时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="巡视人员" prop="inspection_user">
                            <el-input v-model="formData.inspection_user" clearable placeholder="请输入巡视人员" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="施工单位" prop="company_name">
                            <el-input v-model="formData.company_name" clearable placeholder="点击选择施工单位" readonly
                                @click="showDialog2 = true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="巡视内容" prop="inspection_content">
                            <el-input v-model="formData.inspection_content" clearable placeholder="请输入巡视内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设置重点关注" prop="is_importent">
                            <el-select v-model="formData.is_important" clearable placeholder="请选择" class="flex-1">
                                <el-option label="有效" :value="0" />
                                <el-option label="无效" :value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="关注人" prop="follow_user">
                            <el-input v-model="formData.follow_user" clearable placeholder="请输入关注人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="检查表单选择" prop="check_item_detail_name">
                            <el-input v-model="formData.check_item_detail_name" clearable placeholder="点击选择"
                                @click="showDialog1 = true, flag = true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="附件" prop="annex">
                            <uploadAnnex :formData="formData"></uploadAnnex>
                        </el-form-item>
                    </el-col>
                    <createUserLable :formData="formData" flag></createUserLable>
                </el-row>
                <el-dialog v-model="showDialog" title="选择项目" width="70%">
                    <dialogTable @customEvent="customEvent" :config="supervision_project" />
                </el-dialog>
                <div v-if="showDialog1">
                    <el-dialog v-model="showDialog1" width="70%" :title="flag ? '检查表单' : '选择施工单位'">
                        <dialogTable :config="supervision_check_item" @customEvent="customEvents"
                            :query="{ project_id: formData.project_id, node_type: flag ? '' : 2 }" :multipleChoice="flag">
                        </dialogTable>
                    </el-dialog>
                </div>
                <div v-if="showDialog2">
                    <el-dialog v-model="showDialog2" width=" 70%" title="选择施工单位">
                        <dialogTable :config="supervision_participating_units"
                            :query="{ project_id: formData.project_id, unit_type: 6 }" @customEvent="customEvent1">
                        </dialogTable>
                    </el-dialog>
                </div>
            </el-form>
            <formTable :formData="formData.inspection_result" :config="tableConfig"></formTable>
            <formTable :formData="formData.inspection_problem" :config="tableConfig1" :dictData="dictData"></formTable>
        </popup>
    </div>
</template>

<script lang="ts" setup name="supervisionInspectionEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiSupervisionInspectionAdd, apiSupervisionInspectionEdit, apisupervision_inspection_result_delete, apisupervision_problem_delete, apiSupervisionInspectionDetail, apisupervision_inspection_result, apisupervision_problem } from '@/api/supervision_inspection'
import { apisupervision_check_item_detailLists } from '@/api/supervision_check_item'
import { supervision_project, supervision_check_item, supervision_participating_units } from "@/components/dialogTable/dialogTableConfig"
import type { PropType } from 'vue'
import { timeFormat } from '@/utils/util'

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 showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog2 = ref(false)
const flag = ref(false)


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑工程监理--巡视登记' : '新增工程监理--巡视登记'
})


const tableConfig = reactive(
    {
        title: "巡视结果",
        tableConfig: [
            {
                label: "检查类别",
                value: 'check_type'

            },
            {
                label: "检查内容",
                value: 'check_content'
            },
            {
                label: "是否必检",
                value: 'must_check',
                select: [
                    {
                        name: "否",
                        value: 0
                    },
                    {
                        name: "是",
                        value: 1
                    }
                ]
            },
            {
                label: "是否检查结果必检",
                value: 'check_result',
                select: [
                    {
                        name: "合格",
                        value: 0
                    },
                    {
                        name: "不合格",
                        value: 1
                    }
                ]
            },

        ],
        deleteApi: apisupervision_inspection_result_delete,
    }
)

const tableConfig1 = reactive(
    {
        title: "巡视问题",
        tableConfig: [
            {
                label: "问题分类",
                value: 'problem_cate',
                select: 'problem_cate'

            },
            {
                label: "问题说明",
                value: 'problem_description'
            },
            {
                label: "问题名称",
                value: 'problem_name',
            },

        ],
        deleteApi: apisupervision_problem_delete,
    }
)


// 表单数据
const formData = reactive({
    id: '',
    project_id: '',
    project_name: '',
    inspection_code: '',
    is_important: "",
    inspection_type: '',
    check_item_id: '',
    check_item_name: "",
    inspection_position: '',
    workers: '',
    managers: '',
    start_time: timeFormat('', 'yyyy-mm-dd hh:MM:ss'),
    end_time: '',
    inspection_user: '',
    company_id: 0,
    company_name: '',
    inspection_content: '',
    create_time: "",
    follow_user: '',
    check_item_detail_ids: [],
    check_item_detail_name: '',
    annex: [],
    create_user: '',
    inspection_result: [],
    inspection_problem: []
})
const customEvent = (e) => {
    formData.project_id = e.id
    formData.project_name = e.project_name
    showDialog.value = false
    formData.company_name = ''
    formData.company_id = ''
    formData.check_item_detail_ids = []
    formData.check_item_detail_name = ''
    formData.inspection_result = [{
        "check_type": "",
        "check_content": "",
        "must_check": 0,
        "check_result": 0
    },]
}

const customEvents = (e) => {
    if (flag.value) {
        formData.check_item_detail_ids = e.map(item => item.id)
        formData.check_item_detail_name = e.map(item => item.node_name)
        apisupervision_check_item_detailLists({ node_ids: formData.check_item_detail_ids.join(',') }).then(res => {
            let lists = res.lists.map(item => ({
                check_type: item.check_type,
                check_content: item.check_content,
                must_check: item.must_check,
                check_result: item.check_result
            }))
            formData.inspection_result = lists
        })
    } else {
        formData.check_item_id = e.id
        formData.check_item_name = e.node_name
    }
    showDialog1.value = false
}

const customEvent1 = (e) => {
    formData.company_id = e.id
    formData.company_name = e.unit_name
    showDialog2.value = false
}

const checkDate = (rule: any, value: any, callback: any) => {
    if (new Date(formData.end_time) < new Date(formData.start_time)) {
        callback(new Error('巡视结束时间不能早于巡视开始时间'))
    } else {
        callback()
    }
}

// 表单验证
const formRules = reactive<any>({
    project_id: [{
        required: true,
        message: '请选择项目',
        trigger: ['blur']
    }],
    inspection_code: [{
        required: true,
        message: '请输入编号',
        trigger: ['blur']
    }],
    inspection_type: [{
        required: true,
        message: '请输入巡视类型',
        trigger: ['blur']
    }],
    check_item_id: [{
        required: true,
        message: '请输入单位工程',
        trigger: ['blur']
    }],
    inspection_position: [{
        required: true,
        message: '请输入巡视部位',
        trigger: ['blur']
    }],
    workers: [{
        required: true,
        message: '请输入施工人数',
        trigger: ['blur']
    }],
    managers: [{
        required: true,
        message: '请输入管理人数',
        trigger: ['blur']
    }],
    start_time: [{
        required: true,
        message: '请输入巡视开始时间',
        trigger: ['blur']
    }],
    end_time: [{
        required: true,
        message: '请输入巡视结束时间',
        trigger: ['blur']
    },
    {
        validator: checkDate,
        trigger: ['blur']
    }],
    inspection_user: [{
        required: true,
        message: '请输入巡视人员',
        trigger: ['blur']
    }],
    inspection_content: [{
        required: true,
        message: '请输入巡视内容',
        trigger: ['blur']
    }],
    follow_user: [{
        required: true,
        message: '请输入关注人',
        trigger: ['blur']
    }],
    check_item_detail_ids: [{
        required: true,
        message: '请输入检查表单选择',
        trigger: ['blur']
    }],
    create_user: [{
        required: true,
        message: '请输入创建人',
        trigger: ['blur']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    formData.inspection_type = String(formData.inspection_type)
    // formData.is_important = (formData.is_important)
    formData.company_id == 0 ? formData.company_id = '' : ""
    apisupervision_inspection_result({ inspection_id: formData.id }).then(res => {
        formData.inspection_result = res.lists
    })
    apisupervision_problem({ data_id: formData.id, data_type: 1 }).then(res => {
        formData.inspection_problem = res.lists
    })
}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiSupervisionInspectionEdit(data)
        : await apiSupervisionInspectionAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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



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