<template>
    <up-popup :show="show" mode="bottom" @close="handleClose" :round="20" closeable>
        <view class="d-flex flex-cln h-100%" style="max-height: 70vh">
            <view class="f-s-34 f-w-5 pd-24 pb-0">{{ getTitle() }}</view>
            <scroll-view scroll-y class="h-0 flex1">
                <view class="pd-24">
                    <up-form ref="formRef" :model="formData" :rules="rules" labelPosition="top" labelWidth="auto">
                        <template v-if="+type == 1">
                            <!-- 规格等级 -->
                            <up-form-item label="规格等级" required prop="specnLevel">
                                <view class="flex1" @click="goToSpecLevel">
                                    <up-input readonly v-model="formData.specnLevel" type="number" placeholder="请选择规格等级" style="padding-left: 0; padding-right: 0" border="bottom" clearable suffixIcon="arrow-down-fill" suffixIconStyle="color: #2A6D52;font-size: 22rpx"> </up-input>
                                </view>
                                <view class="ml-20">
                                    <up-checkbox :customStyle="{ marginBottom: '8px' }" label="统货" name="agree" usedAlone :checked="formData.specnLevel == '统货'" @change="handleSpecnLevelChange"> </up-checkbox>
                                </view>
                            </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="210rpx" height="210rpx" style="card"></ut-upload>
                            </up-form-item>
                        </template>

                        <!-- 类型 2 特有字段 -->
                        <template v-else>
                            <!-- 规格等级 -->
                            <up-form-item label="规格等级" required prop="specnLevel">
                                <view class="flex1" @click="goToSpecLevel">
                                    <up-input readonly v-model="formData.specnLevel" type="number" placeholder="请选择规格等级" style="padding-left: 0; padding-right: 0" border="bottom" clearable suffixIcon="arrow-down-fill" suffixIconStyle="color: #2A6D52;font-size: 22rpx"> </up-input>
                                </view>
                                <view class="ml-20">
                                    <up-checkbox :customStyle="{ marginBottom: '8px' }" label="统货" name="agree" usedAlone :checked="formData.specnLevel == '统货'" @change="handleSpecnLevelChange"> </up-checkbox>
                                </view>
                            </up-form-item>
                            <!-- 产量 -->
                            <up-form-item borderBottom label="产量" prop="capacity" required>
                                <view class="flex1 d-flex">
                                    <view class="flex1 ov-hd" id="capacitypppp">
                                        <up-form-item border-bottom prop="capacity" class="form-item-top-padding-0">
                                            <up-input v-model="formData.capacity" type="number" placeholder="请输入产量" border="none" clearable></up-input>
                                        </up-form-item>
                                    </view>
                                    <view class="pd-5"></view>
                                    <view class="min-w-100">
                                        <ut-action-sheet v-model="formData.unit" :tabs="unitList" title="选择单位">
                                            <up-form-item border-bottom prop="unit" class="form-item-top-padding-0">
                                                <view class="flex1" style="line-height: 24px">
                                                    <view v-if="formData?.unit" class="f-s-30 c-#333 f-w-5 flex1">{{ formData?.unit }}</view>
                                                    <view v-else class="f-s-30 c-ccc f-w-4 flex1">单位</view>
                                                </view>
                                                <template #right>
                                                    <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                                                </template>
                                            </up-form-item>
                                        </ut-action-sheet>
                                    </view>
                                </view>
                            </up-form-item>
                            <!-- 切制形态 -->
                            <ut-action-sheet v-model="formData.finalFormType" :tabs="pt_final_form_type" title="选择切制形态">
                                <up-form-item borderBottom label="切制形态" prop="finalFormType" required>
                                    <view v-if="formData?.finalFormType" class="f-s-30 c-#333 f-w-5 flex1">{{ selectDictLabel(pt_final_form_type, formData?.finalFormType) }}</view>
                                    <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择切制形态</view>
                                    <template #right>
                                        <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                                    </template>
                                </up-form-item>
                            </ut-action-sheet>
                            <!-- 具体切制形态 -->
                            <up-form-item borderBottom label="具体切制形态" prop="finalFormOther" required>
                                <up-input v-model="formData.finalFormOther" placeholder="请输入具体切制形态" border="none" clearable></up-input>
                            </up-form-item>

                            <!-- 切制尺寸 -->
                            <up-form-item label="切制尺寸" required>
                                <view class="flex1 d-flex">
                                    <view class="flex1 ov-hd" id="finalSpecnpppp">
                                        <up-form-item border-bottom prop="finalSpecn" class="form-item-top-padding-0">
                                            <up-input v-model="formData.finalSpecn" type="number" placeholder="请输入切制尺寸" border="none" clearable></up-input>
                                        </up-form-item>
                                    </view>
                                    <view class="pd-5"></view>
                                    <view class="min-w-100">
                                        <ut-action-sheet v-model="formData.finalUnit" :tabs="pt_final_unit" title="选择切制单位">
                                            <up-form-item border-bottom prop="finalUnit" class="form-item-top-padding-0">
                                                <view class="flex1" style="line-height: 24px">
                                                    <view v-if="formData?.finalUnit" class="f-s-30 c-#333 f-w-5 flex1">{{ selectDictLabel(pt_final_unit, formData?.finalUnit) }}</view>
                                                    <view v-else class="f-s-30 c-ccc f-w-4 flex1">单位</view>
                                                </view>
                                                <template #right>
                                                    <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                                                </template>
                                            </up-form-item>
                                        </ut-action-sheet>
                                    </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="210rpx" height="210rpx" style="card"></ut-upload>
                            </up-form-item>
                        </template>
                    </up-form>
                </view>
            </scroll-view>

            <!-- 底部按钮 -->
            <view class="d-flex gap-20 pd-24">
                <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 { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_final_form_type, pt_final_unit } = toRefs<any>(proxy?.useDict('pt_final_form_type', 'pt_final_unit'));
const props = defineProps<{
    show: boolean;
    type: number; // 1: 初加工，2: 趁鲜切制
    processId: string | number; // 加工任务 ID
    isEdit: boolean; // 是否编辑模式
    editData: any; // 要编辑的数据
}>();
const emit = defineEmits<{
    'update:show': [value: boolean];
    confirm: [data: any];
}>();
setTimeout(() => {
    console.log(pt_final_unit);
}, 2000);
const formRef = ref();
const unitList = ref<any[]>([
    {
        label: 'kg',
        value: 'kg',
    },
    {
        label: '吨',
        value: '吨',
    },
]); // 单位列表（先空着）
const finalFormTypeList = ref<any[]>([]); // 切制形态列表 (pt_final_form_type)

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

// 监听 editData 变化，初始化表单数据
watch(
    () => props.editData,
    (newVal) => {
        if (newVal && props.isEdit) {
            formData.value = {
                specnLevel: newVal?.specnLevel || '',
                capacity: newVal?.capacity || '',
                unit: newVal?.unit || '',
                imgs: newVal?.imgs ? newVal.imgs.split(',').map((url: string) => ({ url })) : [],
                examinReport: newVal?.examinReport || [],
                finalFormType: newVal?.finalFormType || '',
                finalFormOther: newVal?.finalFormOther || '',
                finalSpecn: newVal?.finalSpecn || '',
                finalUnit: newVal?.finalUnit || '',
                id: newVal?.id || '',
            };
        }
    },
    { immediate: true },
);

// 动态生成校验规则
const getRules = () => {
    const baseRules = {
        specnLevel: [{ required: true, message: '请选择规格等级', trigger: 'change' }],
        capacity: [
            { required: true, message: '请输入产量', trigger: 'blur' },
            { type: 'number', message: '产量必须为数字', trigger: 'blur' },
        ],
        unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
    };

    if (type.value === 2) {
        // 类型 2（趁鲜切制）所有字段必填
        return {
            ...baseRules,
            finalFormType: [{ required: true, message: '请选择切制形态', trigger: 'change' }],
            finalFormOther: [{ required: true, message: '请输入具体切制形态', trigger: 'blur' }],
            finalSpecn: [{ required: true, message: '请输入切制尺寸', trigger: 'blur' }],
            finalUnit: [{ required: true, message: '请选择切制单位', trigger: 'change' }],
        };
    } else {
        // 类型 1（初加工）只有前三个必填
        return baseRules;
    }
};

// 根据 type 动态设置校验规则
const type = ref(+props.type);
const rules = ref(getRules());

// 监听 type 变化，重新生成规则
watch(
    () => props.type,
    (newVal) => {
        type.value = newVal;
        rules.value = getRules();
    },
);

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

// 获取标题
const getTitle = () => {
    return props.isEdit ? '修改产出信息' : '添加产出信息';
};

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

// 处理统货 checkbox 点击事件
const handleSpecnLevelChange = (checked: boolean) => {
    if (checked) {
        formData.value.specnLevel = '统货';
    } else {
        formData.value.specnLevel = '';
    }
};

// 跳转到规格等级选择页面
const goToSpecLevel = () => {
    uni.$once('updateSpecificationLevel', (res) => {
        if (res?.data) {
            formData.value.specnLevel = res.data;
        }
    });
    uni.navigateTo({
        url: '/tools/specification-level/index',
    });
};

// 提交表单
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,
        };

        let res: any;
        // 编辑模式调用修改接口
        if (props.isEdit && formData.value.id) {
            (submitData as any).id = formData.value.id;
            res = await useClientRequest.post('/plt-api/app/processOutPut/outputEdit', submitData);
        } else {
            // 新增模式调用新增接口
            res = await useClientRequest.post('/plt-api/app/processOutPut/output', submitData);
        }

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

<style scoped lang="scss">
.search-select-item {
    height: 86rpx;
    background-color: #fff;
    border-radius: 10rpx;
    box-sizing: border-box;
    padding-left: 16rpx;
    padding-right: 16rpx;
    padding-top: 14rpx;
    padding-bottom: 14rpx;
}
</style>
