<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-input v-model="formData.code" clearable placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="取样日期" prop="sampling_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.sampling_date" clearable
                                value-format="YYYY-MM-DD" placeholder="选择取样日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="见证人" prop="witness">
                            <el-input v-model="formData.witness" clearable placeholder="请输入见证人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="取样人" prop="sampler">
                            <el-input v-model="formData.sampler" clearable placeholder="请输入取样人" />
                        </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>
                <formTable :formData="formData.sampling_detail" :config="tableConfig"></formTable>

                <el-dialog v-model="showDialog" title="选择项目" width="70%">
                    <dialogTable @customEvent="customEvent" :config="supervision_project" />
                </el-dialog>
                <el-dialog v-model="showDialog2" title="选择来源单据" width="70%">
                    <dialogTable :config="supervision_material_entry" @customEvent="customEvent1"></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 { apiSupervisionWitnessSamplingAdd, apiSupervisionWitnessSamplingEdit, apiSupervisionWitnessSamplingDetail } from '@/api/supervision_witness_sampling'
import { supervision_project, supervision_material_entry } from "@/components/dialogTable/dialogTableConfig"
// import { apisupervision_material_entry_detail, } from '@/api/supervision_material_entry'
import { apisupervision_material_entry_detail, } from '@/api/supervision_material_entry'
import { apiSupervisionWitnessSamplingListsDetail, } from '@/api/supervision_witness_sampling'


import type { PropType } from 'vue'
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_id: '',
    project_name: "",
    material_entry_id: '',
    material_entry_name: "",
    code: '',
    sampling_date: '',
    witness: '',
    sampler: '',
    annex: '',
    create_user: "",
    create_time: "",
    sampling_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]
    }

    (+value) > (+formData.sampling_detail[index].entry_number)
        ? callback(new Error(`超过进场数量(${formData.sampling_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: ['sampling_detail', checkNum]

            },

        ],
    }
)


const customEvent = (e) => {
    formData.project_id = e.id
    formData.project_name = e.project_name
    showDialog.value = false
}
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.sampling_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 apiSupervisionWitnessSamplingListsDetail({ witness_sampling_id: formData.id })
    formData.sampling_detail = res.lists
}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    data.sampling_detail = (mode.value == 'edit'
        ? formData.sampling_detail.map(item => ({ material_entry_detail_id: item.material_entry_detail_id, id: item.id, num: item.num }))
        : formData.sampling_detail.map(item => ({ material_entry_detail_id: item.id, num: item.num })))
    mode.value == 'edit'
        ? await apiSupervisionWitnessSamplingEdit(data)
        : await apiSupervisionWitnessSamplingAdd(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>
