<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="100px" :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="进场时间" prop="enter_time">
                            <el-date-picker class="flex-1 !flex" v-model="formData.enter_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="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="enter_result">
                            <el-radio-group v-model="formData.enter_result" placeholder="请选择骑缝盖章">
                                <el-radio :label="0">进场</el-radio>
                                <el-radio :label="1">退场</el-radio>
                            </el-radio-group>

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="共同参与人" prop="co_participant">
                            <el-input v-model="formData.co_participant" clearable placeholder="请输入共同参与人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" type="textarea" />
                        </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="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-dialog v-model="showDialog3" title="选择材料信息" width="70%">
                    <dialogTable :config="supervision_material_equipment_info" :query="{ type: 1 }"
                        @customEvent="customEvent2">
                    </dialogTable>

                </el-dialog>
            </el-form>
            <div style="margin-bottom: 30px;">设备信息</div>
            <div style="margin-bottom: 30px;">
                <el-table :data="formData.entry_detail">
                    <template #empty>
                        <span class="cursor-pointer">暂无数据，点击添加 <el-button @click="handleAdd">+</el-button></span>
                    </template>

                    <el-table-column label="序号" width="150px">
                        <template #default="{ row }">
                            <el-button @click="handleAdd()">+</el-button>
                            <el-button @click="handleDelete(row)">-</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="设备名称" prop="name">

                        <template #default="scope">
                            <el-input v-model="scope.row.name" @click="showDialog3 = true, tableIndex = scope.$index" />
                        </template>
                    </el-table-column>
                    <el-table-column label="设备品牌" prop="brand">

                        <template #default="scope">
                            <el-input v-model="scope.row.brand" />
                        </template>
                    </el-table-column>
                    <el-table-column label="计数单位" prop="unit">

                        <template #default="{ row }">
                            <el-input v-model="row.unit" />
                        </template>
                    </el-table-column>
                    <el-table-column label="是否合同约定品牌" prop="contract_brand">

                        <template #default="{ row }">
                            <el-select class="flex-1" v-model="row.contract_brand" clearable placeholder="请选择">
                                <el-option label="否" :value="0" />
                                <el-option label="是" :value="1" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="型号" prop="model">

                        <template #default="{ row }">
                            <el-input v-model="row.model" />
                        </template>
                    </el-table-column>
                    <el-table-column label="进场数量" prop="entry_number">

                        <template #default="{ row }">
                            <el-input v-model="row.entry_number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="证明文件是否安全" prop="documentation">

                        <template #default="{ row }">
                            <el-select class="flex-1" v-model="row.documentation" clearable placeholder="请选择">
                                <el-option label="否" :value="0" />
                                <el-option label="是" :value="1" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="核对是否一致" prop="verify">

                        <template #default="{ row }">
                            <el-select class="flex-1" v-model="row.verify" clearable placeholder="请选择">
                                <el-option label="否" :value="0" />
                                <el-option label="是" :value="1" />
                            </el-select>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <formTable :formData="formData.entry_problem" :config="tableConfig"></formTable>

        </popup>
    </div>
</template>

<script lang="ts" setup name="supervisionDeviceEntryEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiSupervisionDeviceEntryAdd, apiSupervisionDeviceEntryEdit, apiSupervisionDeviceEntryDetail, apisupervision_device_entry_detail, apisupervision_device_entry_detail_delete } from '@/api/supervision_device_entry'
import { apisupervision_problem_delete, apisupervision_problem } from '@/api/supervision_inspection'
import { supervision_project } from "@/components/dialogTable/dialogTableConfig"
import type { PropType } from 'vue'
import { supervision_participating_units, supervision_material_equipment_info } from "@/components/dialogTable/dialogTableConfig"


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 showDialog2 = ref(false)
const showDialog3 = ref(false)
const tableIndex = ref(0)

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑工程监理--设备进场' : '新增工程监理--设备进场'
})

// 表单数据
const formData = reactive({
    id: '',
    project_id: 0,
    project_name: "",
    code: '',
    enter_time: '',
    company_id: '',
    company_name: "",
    enter_result: '',
    co_participant: '',
    remark: '',
    create_user: "",
    create_time: "",
    entry_detail: [],
    entry_problem: []
})

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

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

        ],
        deleteApi: apisupervision_problem_delete,
    }
)


const handleAdd = () => {
    formData.entry_detail.push({
        "name": "",
        "brand": "",
        "model": "",
        "unit": "",
        "contract_brand": 0,
        "entry_number": 0,
        "documentation": 0,
        "verify": 0
    })
}
const handleDelete = async (row: any) => {
    if (row.id) {
        await apisupervision_device_entry_detail_delete({ id: row.id })
        const index = formData.entry_detail.indexOf(row);
        formData.entry_detail.splice(index, 1);
    } else {
        const index = formData.entry_detail.indexOf(row);
        formData.entry_detail.splice(index, 1);
    }
}



const customEvent = (e) => {
    formData.project_id = e.id
    formData.project_name = e.project_name
    showDialog.value = false
    formData.company_id = ''
    formData.company_name = ''

}
const customEvent1 = (e) => {
    formData.company_id = e.id
    formData.company_name = e.unit_name
    showDialog2.value = false
}
const customEvent2 = (e) => {
    let { name, brand, model, unit, contract_brand, entry_number, documentation, verify } = e
    Object.assign(formData.entry_detail[tableIndex.value], { name, brand, model, unit, contract_brand, entry_number, documentation, verify })
    showDialog3.value = false
}

// 表单验证
const formRules = reactive<any>({
    project_id: [{
        required: true,
        message: '请选择项目',
        trigger: ['blur']
    }],
    code: [{
        required: true,
        message: '请输入编号',
        trigger: ['blur']
    }],
    enter_time: [{
        required: true,
        message: '请输入进场时间',
        trigger: ['blur']
    }],
    company_id: [{
        required: true,
        message: '请输入施工单位',
        trigger: ['blur']
    }],
    enter_result: [{
        required: true,
        message: '请输入进场结果 0-进场 1-退场',
        trigger: ['blur']
    }],
    co_participant: [{
        required: true,
        message: '请输入共同参与人',
        trigger: ['blur']
    }],
    remark: [{
        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]
        }
    }
    apisupervision_device_entry_detail({ device_entry_id: formData.id }).then(res => {
        formData.entry_detail = res.lists
    })
    apisupervision_problem({ data_id: formData.id, data_type: 4 }).then(res => {
        formData.entry_problem = res.lists
    })

}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiSupervisionDeviceEntryEdit(data)
        : await apiSupervisionDeviceEntryAdd(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>
