<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="90px" :rules="formRules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="来源单据" prop="material_entry_name">
                            <el-input v-model="formData.material_entry_name" clearable placeholder="点击来源单据" readonly
                                @click="showDialog2 = true" />
                        </el-form-item>
                    </el-col>
                    <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-date-picker class="flex-1 !flex" v-model="formData.inspection_date" clearable
                                value-format="YYYY-MM-DD" placeholder="选择取样日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="送检人">
                            <el-input v-model="formData.inspector" clearable placeholder="请输入见证人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" type="textarea" />
                        </el-form-item>
                    </el-col>
                    <createUserLable :formData="formData" flag></createUserLable>
                    <el-col :span="8">
                        <el-form-item label="附件" prop="annex">
                            <uploadAnnex :formData="formData"></uploadAnnex>
                        </el-form-item>
                    </el-col>
                </el-row>
                <formTable :formData="formData.detail" :config="tableConfig"></formTable>
                <el-dialog v-model="showDialog2" title="选择来源单据" width="70%">
                    <dialogTable :config="supervision_material_entry" @customEvent="customEvent1"
                        :query="{ parallel_test: 1 }"></dialogTable>
                </el-dialog>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="supervisionWitnessSamplingEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiSupervisionMaterialParallelTestingAdd, apiSupervisionMaterialParallelTestingEdit, apisupervision_material_parallel_testing_detail, apisupervision_material_parallel_testing_delete } from '@/api/supervision_material_parallel_testing'
import { apisupervision_material_entry_detail } from '@/api/supervision_material_entry'
import type { PropType } from 'vue'
import { supervision_material_entry } 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 popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑工程监理--材料平行检验' : '新增工程监理--材料平行检验'
})

// 表单数据
const formData = reactive({
    id: "",
    project_name: "",
    "project_id": 1,
    "material_entry_id": 1,
    material_entry_name: "",
    "inspector": "",
    "inspection_date": "",
    "remark": "",
    "annex": [],
    create_user: "",
    create_time: "",
    "detail": []
})

const checkNum = (rule: any, value: any, callback: any, source) => {
    const regex = /\[(\d+)\]/; // 匹配方括号内的数字,也就是table的下标
    let index = 0

    for (let key in source) {
        index = key.match(regex)[1]
    }

    (+formData.detail[index].num) > (+formData.detail[index].entry_number)
        ? callback(new Error(`超过进场数量(${formData.detail[index].entry_number})`))
        : callback()
}


const tableConfig = reactive(
    {
        title: "材料信息",
        tableConfig: [
            {
                label: "材料名称",
                value: 'name',

            },
            {
                label: "材料品牌",
                value: 'brand'
            },
            {
                label: "单位",
                value: 'unit',
            },
            {
                label: "是否合同约定品牌",
                value: 'contract_brand',
                select: [
                    {
                        name: "否",
                        value: 0
                    },
                    {
                        name: "是",
                        value: 1
                    }
                ]
            },
            {
                label: "型号",
                value: 'model',
            },
            {
                label: "进场数量",
                value: 'entry_number',
            },
            {
                label: "检验数量",
                value: 'num',
                check: ['detail', checkNum]
            },
        ],
        deleteApi: apisupervision_material_parallel_testing_delete
    }
)

const customEvent1 = async (e) => {
    formData.project_name = e.project_name
    formData.project_id = e.project_id
    formData.material_entry_id = e.id
    formData.material_entry_name = e.theme
    showDialog2.value = false
    let res = await apisupervision_material_entry_detail({ material_entry_id: e.id })
    formData.detail = res.lists
}

// 表单验证
const formRules = reactive<any>({
    project_name: [{
        required: true,
        message: '请选择项目',
        trigger: ['blur']
    }],
    material_entry_id: [{
        required: true,
        message: '请输入来源单据',
        trigger: ['blur']
    }],
    sampling_date: [{
        required: true,
        message: '请输入取样日期',
        trigger: ['blur']
    }],
    witness: [{
        required: true,
        message: '请输入见证人',
        trigger: ['blur']
    }],
    sampler: [{
        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]
        }
    }

    let res = await apisupervision_material_parallel_testing_detail({ material_parallel_testing_id: formData.id })
    formData.detail = res.lists
}



// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    data.detail = (mode.value == 'edit'
        ? formData.detail.map(item => ({ material_entry_detail_id: item.material_entry_detail_id, id: item.id, num: item.num }))
        : formData.detail.map(item => ({ material_entry_detail_id: item.id, num: item.num })))
    mode.value == 'edit'
        ? await apiSupervisionMaterialParallelTestingEdit(data)
        : await apiSupervisionMaterialParallelTestingAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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



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