<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">
                            <annexUpload :annex="formData.annex" @handleAvatarSuccess="handleAvatarSuccess_four"
                                @delFile="delFileFn" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-dialog v-model="showDialog" title="选择项目" width="70%">
                    <dialogTable @customEvent="customEvent" :config="supervision_project" />
                </el-dialog>
                <el-dialog v-model="showDialog2" title="选择来源单据" width="70%">
                    <supervision_material_entry @customEvent="customEvent1"></supervision_material_entry>
                </el-dialog>
            </el-form>
            <div style="margin-bottom: 30px;">材料信息</div>
            <div style="margin-bottom: 30px;">
                <el-table :data="formData.sampling_detail">
                    <!-- <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" />
                        </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="num">

                        <template #default="{ row }">
                            <el-input v-model="row.num" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </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 } from "@/components/dialogTable/dialogTableConfig"
import { apisupervision_material_entry_detail, } from '@/api/supervision_material_entry'

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 handleAvatarSuccess_four = (response: any) => {
    Array.isArray(formData.annex) ? '' : formData.annex = []
    // @ts-ignore
    response.code != 0 ? formData.annex.push({ uri: response.data.uri, name: response.data.name }) : ElMessage.error(response.msg);
};

// 删除上传的文件
const delFileFn = (index: number) => { formData.annex.splice(index, 1) }

// 弹窗标题
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: '',
    sampling_detail: [
        {
            "name": "",
            "brand": "",
            "model": "",
            "unit": "",
            "contract_brand": 0,
            "entry_number": 0,
            num: ""
        }

    ]
})
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 apisupervision_material_entry_detail({ material_entry_id: formData.material_entry_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()
    // formData.sampling_detail = formData.sampling_detail.map(item => ({ material_entry_detail_id: item.id, num: item.num }))
    const data = { ...formData, }
    data.sampling_detail = 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>
