<template>
    <up-popup :show="show" mode="bottom" @close="handleClose" :round="20" closeable style="height: 70vh">
        <view class="d-flex flex-cln h-100% pd-24 bg-#fff p-rtv" style="max-height: 70vh">
            <view class="f-s-34 f-w-5">添加产出信息</view>
            <scroll-view scroll-y class="h-0 flex1">
                <up-form ref="formRef" :model="formData" :rules="rules" labelPosition="top" labelWidth="auto">
                    <template v-if="+type == 1">
                        <!-- 规格等级 -->
                        <up-form-item borderBottom label="规格等级" required prop="specnLevel">
                            <ut-action-sheet v-model="formData.specnLevel" :tabs="specnLevelList" title="选择规格等级">
                                <template #right>
                                    <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                                </template>
                            </ut-action-sheet>
                        </up-form-item>
                        <!-- 产量 -->
                        <up-form-item borderBottom label="产量" prop="capacity" required>
                            <view class="d-flex a-c w-100%">
                                <up-input v-model="formData.capacity" type="number" placeholder="请输入产量" border="none" clearable></up-input>
                                <ut-action-sheet v-model="formData.unit" :tabs="unitList" title="选择单位" style="margin-left: 10rpx"></ut-action-sheet>
                            </view>
                        </up-form-item>

                        <!-- 产出物图片 -->
                        <up-form-item borderBottom label="产出物图片">
                            <ut-upload v-model="formData.imgs" :max-count="6" valueType="array" accept="image" width="210rpx" height="210rpx" style="card"></ut-upload>
                        </up-form-item>

                        <!-- 检验报告 -->
                        <up-form-item borderBottom label="检验报告">
                            <ut-upload v-model="formData.examinReport" :max-count="50" valueType="array" accept="image,file" width="260rpx" height="260rpx" style="card" uploadImageText="上传图片" uploadFileText="上传 PDF"></ut-upload>
                        </up-form-item>
                    </template>

                    <!-- 类型 2 特有字段 -->
                    <template v-if="+type == 2">
                        <!-- 切制形态 -->
                        <up-form-item borderBottom label="切制形态" prop="finalFormType" required>
                            <ut-action-sheet v-model="formData.finalFormType" :tabs="finalFormTypeList" title="选择切制形态">
                                <template #right>
                                    <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                                </template>
                            </ut-action-sheet>
                        </up-form-item>

                        <!-- 具体切制形态 -->
                        <up-form-item borderBottom label="具体切制形态" prop="finalFormOther">
                            <up-input v-model="formData.finalFormOther" placeholder="请输入具体切制形态" border="none" clearable></up-input>
                        </up-form-item>

                        <!-- 切制尺寸 -->
                        <up-form-item borderBottom label="切制尺寸" prop="finalUnit">
                            <view class="d-flex a-c w-100%">
                                <up-input v-model="formData.finalSpecn" type="number" placeholder="请输入切制尺寸" border="none" clearable></up-input>
                                <view class="ml-10" style="font-size: 28rpx; font-weight: 500; color: #333">mm</view>
                            </view>
                        </up-form-item>
                        <!-- 产出物图片 -->
                        <up-form-item borderBottom label="产出物图片">
                            <ut-upload v-model="formData.imgs" :max-count="6" valueType="array" accept="image" width="210rpx" height="210rpx" style="card"></ut-upload>
                        </up-form-item>

                        <!-- 检验报告 -->
                        <up-form-item borderBottom label="检验报告">
                            <ut-upload v-model="formData.examinReport" :max-count="50" valueType="array" accept="image,file" width="260rpx" height="260rpx" style="card" uploadImageText="上传图片" uploadFileText="上传 PDF"></ut-upload>
                        </up-form-item>
                    </template>
                </up-form>
            </scroll-view>

            <!-- 底部按钮 -->
            <view class="d-flex gap-20">
                <up-button plain type="info" @click="handleClose">取消</up-button>
                <up-button type="primary" @click="handleSubmit">确认</up-button>
            </view>
        </view>
    </up-popup>
</template>

<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
const props = defineProps<{
    show: boolean;
    type: number; // 1: 初加工，2: 趁鲜切制
    processId: string | number; // 加工任务 ID
}>();
console.log(props.type, 'type');

const emit = defineEmits<{
    'update:show': [value: boolean];
    confirm: [data: any];
}>();

const formRef = ref();
const specnLevelList = ref<any[]>([]); // 规格等级列表（先空着）
const unitList = ref<any[]>([]); // 单位列表（先空着）
const finalFormTypeList = ref<any[]>([]); // 切制形态列表 pt_final_form_type

// 表单数据
const formData = ref({
    specnLevel: '',
    capacity: '',
    unit: '',
    imgs: [] as any[],
    examinReport: [] as any[],
    finalFormType: '',
    finalFormOther: '',
    finalSpecn: '',
    finalUnit: '',
});

// 表单验证规则
const rules = {
    specnLevel: [{ required: true, message: '请选择规格等级', trigger: 'change' }],
    capacity: [
        { required: true, message: '请输入产量', trigger: 'blur' },
        { type: 'number', message: '产量必须为数字', trigger: 'blur' },
    ],
    unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
    finalFormType: [{ required: true, message: '请选择切制形态', trigger: 'change' }],
};

// 关闭弹框
const handleClose = () => {
    emit('update:show', false);
    resetForm();
};

// 重置表单
const resetForm = () => {
    formData.value = {
        specnLevel: '',
        capacity: '',
        unit: '',
        imgs: [],
        examinReport: [],
        finalFormType: '',
        finalFormOther: '',
        finalSpecn: '',
        finalUnit: '',
    };
    formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
    try {
        const valid = await formRef.value?.validate();
        if (!valid) return;

        // 准备提交数据
        const submitData = {
            processId: props.processId,
            specnLevel: formData.value.specnLevel,
            capacity: Number(formData.value.capacity),
            unit: formData.value.unit,
            imgs: formData.value.imgs.map((item: any) => item.url).join(','),
            examinReport: formData.value.examinReport.map((item: any) => ({
                fileName: item.fileName || '',
                url: item.url || '',
                fileSize: item.fileSize || 0,
            })),
            finalFormType: formData.value.finalFormType,
            finalFormOther: formData.value.finalFormOther,
            finalSpecn: formData.value.finalSpecn,
            finalUnit: formData.value.finalUnit,
        };

        // 调用接口
        const res: any = await useClientRequest.post('/plt-api/app/processOutPut/output', submitData);

        if (res && res.code === 200) {
            uni.showToast({ title: '添加成功', icon: 'success' });
            handleClose();
            emit('confirm', res.data);
        }
    } catch (error) {
        console.error('提交失败:', error);
    }
};
</script>

<style scoped lang="scss"></style>
