<template>
    <z-paging class="" ref="paging" bgColor="#f7f7f7" paging-class="paging-btm-shadow" safe-area-inset-bottom scroll-with-animation>
        <template #top>
            <ut-navbar :title="did ? '编辑鲜货入库' : '新增鲜货入库'" :fixed="false" border></ut-navbar>
        </template>
        <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
            <!-- 鲜货信息（复制自 info-edit 字段与顺序） -->
            <template v-if="form.instoreType == '2'">
                <view class="pd-24">
                    <view class="startline-title">鲜货信息</view>
                </view>
                <view class="pd-24 bg-#fff">
                    <!-- 基本信息 -->
                    <view class="h-1" id="varietyIdpppp"></view>
                    <up-form-item borderBottom label="动植物名称" required prop="varietyId">
                        <view class="flex1">
                            <up-button v-if="!form.varietyId" @click="selectVarietyId" type="primary" plain>
                                <image class="w-36 h-36 mr-10" src="https://yujin-szyy.oss-cn-chengdu.aliyuncs.com/szyy/images-plt/common/select_push_icon.png" mode="widthFix" />
                                <span>请选择动植物名称</span>
                            </up-button>
                            <view v-else class="bg-#FBFDFB card-info-block pd-24 p-rtv">
                                <view class="mb-16">
                                    <span class="f-s-34 c-#333 f-w-5 mr-16">{{ form?.varietyInfo?.varietyName }}</span>
                                    <span class="f-s-24 c-#666">{{ form?.varietyInfo?.latinName }}</span>
                                </view>
                                <view class="mb-16">
                                    <span class="f-s-28 c-#333 f-w-5 mr-16">{{ form?.varietyInfo?.genusName }}</span>
                                    <span class="f-s-24 c-#666">{{ form?.varietyInfo?.genusLatinName }}</span>
                                </view>
                                <view v-if="form?.varietyInfo?.medicineName" class="f-s-24 c-#666">产出：{{ form?.varietyInfo?.medicineName }}</view>
                                <view
                                    class="close-icon pd-16"
                                    @click="
                                        form.varietyId = '';
                                        form.varietyInfo = null;
                                    "
                                >
                                    <up-icon color="#F81242" name="close" size="32rpx"></up-icon>
                                </view>
                            </view>
                        </view>
                    </up-form-item>
                    <view class="h-1" id="partpppp"></view>
                    <SelectMedicinalPart v-model="form.part" v-model:value-name="form.partName">
                        <up-form-item borderBottom label="药用部位/对象" prop="part" required>
                            <up-input v-model="form.partName" placeholder="请选择药用部位/对象" border="none" readonly clearable></up-input>
                            <template #right>
                                <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                            </template>
                        </up-form-item>
                    </SelectMedicinalPart>

                    <view class="h-1" id="sourceTypepppp"></view>
                    <ut-action-sheet :tabs="pt_medicine_source" mode="custom" title="鲜货来源" v-model="form.sourceType">
                        <up-form-item borderBottom label="鲜货来源" required prop="sourceType">
                            <view v-if="form.sourceType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_medicine_source_tag, form.sourceType) }}</view>
                            <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择鲜货来源</view>
                            <template #right>
                                <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                            </template>
                        </up-form-item>
                    </ut-action-sheet>
                    <!-- 入库数量与单位 -->
                    <view class="h-1" id="capacitypppp"></view>
                    <view class="h-1" id="unitpppp"></view>
                    <up-form-item label="入库量" prop="capacity" required class="form-item-bottom-padding-0">
                        <view class="f-s-30 c-999 f-w-5 flex1">{{ form?.capacity }}{{ form?.unit }}</view>
                    </up-form-item>

                    <template v-if="['2'].includes(form.sourceType as string)">
                        <up-form-item borderBottom label="供应商" prop="supplierId" required>
                            <view class="flex1">
                                <ContactUnitInput v-model="form.supplierId" v-model:info="form.supplierInfo" :params="{ cpyType: '4' }" title="选择供应商" placeholder="请选择供应商信息"></ContactUnitInput>
                            </view>
                        </up-form-item>
                        <up-form-item borderBottom label="供应商是否是生产商" prop="supplierProducerFlag">
                            <up-radio-group v-model="form.supplierProducerFlag" @change="changeSupplierProducerFlag">
                                <up-radio :customStyle="{ marginRight: '60rpx' }" v-for="(item, index) in yes_no" :key="index" :label="item.label" :name="item.value"></up-radio>
                            </up-radio-group>
                        </up-form-item>
                        <up-form-item borderBottom label="生产商" prop="producer">
                            <up-input v-model="form.producer" placeholder="请输入生产商名称" border="none" clearable></up-input>
                        </up-form-item>
                    </template>
                    <!-- 检验报告与供应商信息 -->
                    <up-form-item borderBottom label="检验报告" prop="examinReport">
                        <ut-upload v-model="form.examinReport" :max-count="50" valueType="array" accept="image,file"></ut-upload>
                    </up-form-item>
                    <!-- 鲜货产地 -->
                    <view class="h-1" id="producePlacepppp"></view>
                    <PickerAreaInput v-model="form.producePlace" v-model:full-name="form.producePlaceName" title="选择鲜货产地">
                        <up-form-item borderBottom label="鲜货产地" prop="producePlace" required>
                            <view v-if="form.producePlace" class="f-s-30 c-333 f-w-5 flex1">{{ form.producePlaceName }}</view>
                            <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择鲜货产地</view>
                            <template #right>
                                <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                            </template>
                        </up-form-item>
                    </PickerAreaInput>
                    <view class="h-1" id="productDatepppp"></view>
                    <view class="h-1" id="productDateEndpppp"></view>
                    <up-form-item prop="productDate" required label="采收日期" class="form-item-bottom-padding-0">
                        <view class="flex1 d-flex">
                            <view class="flex1">
                                <ut-datetime-picker v-model="form.productDate" :maxDate="form.productDateEnd || new Date()" mode="date">
                                    <up-form-item borderBottom prop="productDate" class="form-item-top-padding-0">
                                        <up-input v-model="form.productDate" readonly placeholder="请选择开始日期" border="none" clearable></up-input>
                                        <template #right>
                                            <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                                        </template>
                                    </up-form-item>
                                </ut-datetime-picker>
                            </view>
                            <view class="pd2-0-20"></view>
                            <view class="flex1">
                                <ut-datetime-picker v-model="form.productDateEnd" :minDate="form.productDate" :maxDate="new Date()" mode="date">
                                    <up-form-item borderBottom prop="productDateEnd" class="form-item-top-padding-0">
                                        <up-input v-model="form.productDateEnd" readonly placeholder="请选择结束日期" border="none" clearable></up-input>
                                        <template #right>
                                            <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                                        </template>
                                    </up-form-item>
                                </ut-datetime-picker>
                            </view>
                        </view>
                    </up-form-item>
                    <!-- 媒体与附件 -->
                    <up-form-item borderBottom label="鲜货图片" prop="imgs">
                        <ut-upload v-model="form.imgs" :max-count="9" valueType="string"></ut-upload>
                    </up-form-item>
                    <up-form-item borderBottom label="鲜货视频" prop="vedios">
                        <ut-upload v-model="form.vedios" :max-count="3" accept="video" valueType="string"></ut-upload>
                    </up-form-item>
                </view>

                <view class="pd-24">
                    <view class="startline-title">入库信息</view>
                </view>
                <view class="pd-24 bg-#fff">
                    <up-form-item borderBottom label="鲜货级别" prop="level">
                        <up-input v-model="form.level" placeholder="请输入鲜货级别" border="none" clearable></up-input>
                    </up-form-item>
                    <!-- 入库类型 -->
                    <up-form-item borderBottom label="入库类型" required prop="instoreType">
                        <view v-if="form.instoreType" class="f-s-30 c-999 f-w-5 flex1">{{ selectDictLabel(pt_fresh_instore_type, form.instoreType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择入库类型</view>
                    </up-form-item>
                    <!-- 入库日期 -->
                    <view class="h-1" id="instoreDatepppp"></view>
                    <ut-datetime-picker v-model="form.instoreBizInfo.instoreDate" :maxDate="new Date()" mode="date">
                        <up-form-item borderBottom label="入库日期" required prop="instoreDate">
                            <up-input v-model="form.instoreBizInfo.instoreDate" placeholder="请选择入库日期" border="none" clearable></up-input>
                            <template #right>
                                <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                            </template>
                        </up-form-item>
                    </ut-datetime-picker>
                    <!-- 入库批号 -->
                    <up-form-item borderBottom label="入库批号" required prop="batchCode">
                        <up-input v-model="form.batchCode" placeholder="请输入入库批号" border="none" clearable></up-input>
                        <template #right>
                            <up-button @click="generateBatchCode" type="primary" :customStyle="formItemBtnStyle">随机生成</up-button>
                        </template>
                    </up-form-item>
                    <!-- 库房类型 -->
                    <up-form-item borderBottom label="库房类型" prop="storageType" required>
                        <view v-if="form.storageType" class="f-s-30 c-999 f-w-5 flex1">{{ selectDictLabel(pt_warehouse_type, form.storageType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择库房类型</view>
                    </up-form-item>
                    <!-- 存放库房（具体库房/货架信息稍后补充为选择器） -->
                    <up-form-item borderBottom label="存放库房" prop="warehouses">
                        <select-warehouse-input v-model="form.warehouses" title="添加鲜货存放库房" :params="{ type: '4' }"></select-warehouse-input>
                    </up-form-item>
                    <!-- 入库人 -->
                    <up-form-item borderBottom label="入库人" required prop="instoreMg">
                        <up-input v-model="form.instoreBizInfo.instoreMg" placeholder="请输入入库人" border="none" clearable></up-input>
                    </up-form-item>
                    <!-- 入库备注 -->
                    <up-form-item borderBottom label="入库备注" prop="remark">
                        <up-textarea v-model="form.instoreBizInfo.remark" placeholder="请输入入库备注" autoHeight></up-textarea>
                    </up-form-item>
                </view>
            </template>
            <template v-if="form.instoreType == '3'">
                <view class="pd-24">
                    <view class="startline-title">鲜货信息</view>
                </view>
                <view class="pd-24 bg-#fff">
                    <!-- 基本信息 -->
                    <view class="h-1" id="varietyIdpppp"></view>
                    <up-form-item borderBottom label="动植物名称" required prop="varietyId">
                        <view class="flex1">
                            <up-button v-if="!form.varietyId" @click="selectVarietyId" type="primary" plain>
                                <image class="w-36 h-36 mr-10" src="https://yujin-szyy.oss-cn-chengdu.aliyuncs.com/szyy/images-plt/common/select_push_icon.png" mode="widthFix" />
                                <span>请选择动植物名称</span>
                            </up-button>
                            <view v-else class="bg-#FBFDFB card-info-block pd-24 p-rtv">
                                <view class="mb-16">
                                    <span class="f-s-34 c-#333 f-w-5 mr-16">{{ form?.varietyInfo?.varietyName }}</span>
                                    <span class="f-s-24 c-#666">{{ form?.varietyInfo?.latinName }}</span>
                                </view>
                                <view class="mb-16">
                                    <span class="f-s-28 c-#333 f-w-5 mr-16">{{ form?.varietyInfo?.genusName }}</span>
                                    <span class="f-s-24 c-#666">{{ form?.varietyInfo?.genusLatinName }}</span>
                                </view>
                                <view v-if="form?.varietyInfo?.medicineName" class="f-s-24 c-#666">产出：{{ form?.varietyInfo?.medicineName }}</view>
                            </view>
                        </view>
                    </up-form-item>
                    <view class="h-1" id="partpppp"></view>
                    <SelectMedicinalPart v-model="form.part" v-model:value-name="form.partName">
                        <up-form-item borderBottom label="药用部位/对象" prop="part" required>
                            <up-input v-model="form.partName" placeholder="请选择药用部位/对象" border="none" readonly clearable></up-input>
                        </up-form-item>
                    </SelectMedicinalPart>

                    <view class="h-1" id="sourceTypepppp"></view>
                    <up-form-item borderBottom label="鲜货来源" required prop="sourceType">
                        <view v-if="form.sourceType" class="f-s-30 c-999 f-w-5 flex1">{{ selectDictLabel(pt_medicine_source_tag, form.sourceType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择鲜货来源</view>
                    </up-form-item>
                    <!-- 入库数量与单位 -->
                    <view class="h-1" id="capacitypppp"></view>
                    <view class="h-1" id="unitpppp"></view>
                    <up-form-item label="采收量" prop="capacity" required class="form-item-bottom-padding-0">
                        <view class="f-s-30 c-999 f-w-5 flex1">{{ form?.capacity }}{{ form?.unit }}</view>
                    </up-form-item>

                    <!-- 检验报告与供应商信息 -->
                    <up-form-item borderBottom label="检验报告" prop="examinReport">
                        <ut-upload v-model="form.examinReport" :max-count="50" valueType="array" accept="image,file"></ut-upload>
                    </up-form-item>
                    <!-- 鲜货产地 -->
                    <view class="h-1" id="producePlacepppp"></view>
                    <PickerAreaInput v-model="form.producePlace" v-model:full-name="form.producePlaceName" title="选择鲜货产地">
                        <up-form-item borderBottom label="鲜货产地" prop="producePlace" required>
                            <view v-if="form.producePlace" class="f-s-30 c-333 f-w-5 flex1">{{ form.producePlaceName }}</view>
                            <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择鲜货产地</view>
                            <template #right>
                                <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                            </template>
                        </up-form-item>
                    </PickerAreaInput>
                    <view class="h-1" id="productDatepppp"></view>
                    <view class="h-1" id="productDateEndpppp"></view>
                    <up-form-item prop="productDate" required label="采收日期" class="form-item-bottom-padding-0">
                        <view class="flex1 d-flex">
                            <view class="flex1">
                                <ut-datetime-picker v-model="form.productDate" :maxDate="form.productDateEnd || new Date()" mode="date">
                                    <up-form-item borderBottom prop="productDate" class="form-item-top-padding-0">
                                        <up-input v-model="form.productDate" readonly placeholder="请选择开始日期" border="none" clearable></up-input>
                                        <template #right>
                                            <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                                        </template>
                                    </up-form-item>
                                </ut-datetime-picker>
                            </view>
                            <view class="pd2-0-20"></view>
                            <view class="flex1">
                                <ut-datetime-picker v-model="form.productDateEnd" :minDate="form.productDate" :maxDate="new Date()" mode="date">
                                    <up-form-item borderBottom prop="productDateEnd" class="form-item-top-padding-0">
                                        <up-input v-model="form.productDateEnd" readonly placeholder="请选择结束日期" border="none" clearable></up-input>
                                        <template #right>
                                            <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                                        </template>
                                    </up-form-item>
                                </ut-datetime-picker>
                            </view>
                        </view>
                    </up-form-item>
                    <!-- 媒体与附件 -->
                    <up-form-item borderBottom label="鲜货图片" prop="imgs">
                        <ut-upload v-model="form.imgs" :max-count="9" valueType="string"></ut-upload>
                    </up-form-item>
                    <up-form-item borderBottom label="鲜货视频" prop="vedios">
                        <ut-upload v-model="form.vedios" :max-count="3" accept="video" valueType="string"></ut-upload>
                    </up-form-item>
                </view>

                <view class="pd-24">
                    <view class="startline-title">入库信息</view>
                </view>
                <view class="pd-24 bg-#fff">
                    <up-form-item borderBottom label="鲜货级别" prop="level">
                        <up-input v-model="form.level" placeholder="请输入鲜货级别" border="none" clearable></up-input>
                    </up-form-item>
                    <!-- 入库类型 -->
                    <up-form-item borderBottom label="入库类型" required prop="instoreType">
                        <view v-if="form.instoreType" class="f-s-30 c-999 f-w-5 flex1">{{ selectDictLabel(pt_fresh_instore_type, form.instoreType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择入库类型</view>
                    </up-form-item>
                    <!-- 库房类型 -->
                    <up-form-item borderBottom label="库房类型" prop="storageType" required>
                        <view v-if="form.storageType" class="f-s-30 c-999 f-w-5 flex1">{{ selectDictLabel(pt_warehouse_type, form.storageType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择库房类型</view>
                    </up-form-item>
                    <!-- 存放库房（具体库房/货架信息稍后补充为选择器） -->
                    <up-form-item borderBottom label="存放库房" prop="warehouses">
                        <select-warehouse-input v-model="form.warehouses" title="添加鲜货存放库房" :params="{ type: '4' }"></select-warehouse-input>
                    </up-form-item>
                    <!-- 入库人 -->
                    <up-form-item borderBottom label="入库人" required prop="instoreMg">
                        <up-input v-model="form.instoreBizInfo.instoreMg" placeholder="请输入入库人" border="none" clearable></up-input>
                    </up-form-item>
                    <!-- 入库备注 -->
                    <up-form-item borderBottom label="入库备注" prop="remark">
                        <up-textarea v-model="form.instoreBizInfo.remark" placeholder="请输入入库备注" autoHeight></up-textarea>
                    </up-form-item>
                </view>
            </template>
        </up-form>
        <template #bottom>
            <view class="pd-20 d-flex">
                <up-button @click="submitForm" type="primary">保存</up-button>
            </view>
        </template>
    </z-paging>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import { FreshGoodsInfoType } from '../models/type';
import ContactUnitInput from '@/models/contact-unit-input/contact-unit-input.vue';
import PickerAreaInput from '@/models/picker-area-input/picker-area-input.vue';
import SelectWarehouseInput from '@/models/select-warehouse-input/select-warehouse-input.vue';
import SelectMedicinalPart from '@/models/select-medicinal-part/select-medicinal-part.vue';
import { parseTime } from '@/utils/ruoyi';
import { formItemBtnStyle } from '@/assets/styles/uview-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_fresh_instore_type, pt_warehouse_type, pt_medicine_source, yes_no, pt_medicine_source_tag } = toRefs<any>(proxy?.useDict('pt_fresh_instore_type', 'pt_warehouse_type', 'pt_medicine_source', 'yes_no', 'pt_medicine_source_tag'));
const paging = ref<any>(null);
const upFormRef = ref<any>(null);
// 单条鲜货信息 + 入库信息的合并表单
const form = ref<FreshGoodsInfoType | any>({
    storageType: '4',
    instoreBizInfo: {
        instoreDate: parseTime(new Date(), '{y}-{m}-{d}'),
        instoreMg: '',
        remark: '',
    },
});
const rules = reactive({
    varietyId: [{ required: true, message: '请选择动植物名称' }],
    part: [{ required: true, message: '请选择药用部位/对象' }],
    sourceType: [{ required: true, message: '请选择鲜货来源' }],
    capacity: [
        { required: true, message: '请输入入库量' },
        {
            asyncValidator: (rule: any, value: any) => {
                if (value === 0 || value === '0') return Promise.reject('入库量需大于0');
                if (value === undefined || value === null || value === '') return Promise.resolve();
                const num = Number(value);
                if (Number.isNaN(num)) return Promise.reject('入库量请输入数字');
                if (num <= 0) return Promise.reject('入库量需大于0');
                return Promise.resolve();
            },
        },
    ],
    unit: [{ required: true, message: '请选择单位' }],
    supplierId: [
        {
            asyncValidator: (rule: any, value: any) => {
                if (['2'].includes(form.value.sourceType as string)) {
                    if (!value) return Promise.reject('请选择供应商');
                }
                return Promise.resolve();
            },
        },
    ],
    producePlace: [{ required: true, message: '请选择鲜货产地' }],
    productDate: [{ required: true, message: '请选择开始日期' }],
    productDateEnd: [{ required: true, message: '请选择结束日期' }],
    'instoreBizInfo.instoreMg': [{ required: true, message: '请输入入库人' }],
});
// 点击随机生成服务端生成唯一的批号
const generateBatchCode = async () => {
    uni.showLoading({
        title: '生成中...',
    });
    const res = await useClientRequest.post('/plt-api/app/plantationTask/getBatchCode', {
        plType: 'X',
        linkType: 'I',
    });
    if (res && res.code === 200) {
        uni.hideLoading();
        form.value.batchCode = res.data;
        uni.showToast({
            title: '批号生成成功',
            icon: 'success',
        });
    }
};
// 提交：当前页面改为单条鲜货信息，直接提交合并后的对象
const submitForm = async () => {
    uni.$u.debounce(
        async () => {
            try {
                await upFormRef.value?.validate();
            } catch (error: any) {
                const firstErrorField = error && error[0].field + 'pppp';
                paging.value?.scrollIntoViewById(firstErrorField, 30, true);
                return;
            }
            uni.showLoading({
                title: '提交中...',
            });
            try {
                // 这里使用单条入库接口，后端若仍要求 batch，可根据需要包装成数组
                const res = await useClientRequest.post('/plt-api/app/storage/edit', form.value);
                if (!res || res.code !== 200) return;
                uni.hideLoading();
                uni.showToast({
                    title: '提交成功',
                    icon: 'success',
                });
                uni.$emit('fresh-goods-detail-refresh');
                uni.$emit('refreshStorageRoomList');
                setTimeout(() => {
                    uni.navigateBack({
                        delta: 1,
                    });
                }, 1500);
            } catch (error) {
                // uni.hideLoading();
            }
        },
        500,
        true,
    );
};
// 选择物种、父母本逻辑保持与 info-edit 一致
const selectVarietyId = () => {
    uni.$once('updateBiologicalname', function (data) {
        form.value.varietyId = data.msg.id;
        form.value.varietyInfo = data.msg;
    });
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/por-torganism/index',
        params: {
            title: '选择物种基原',
        },
    });
};

const did = ref('');
// 获取详情（仓库信息）
const getDetailById = async (id: string) => {
    if (!id) return;
    const res = await useClientRequest.get(`/plt-api/app/storage/getInfo/${id}`);
    if (res && res.code === 200) {
        form.value = {
            ...form.value,
            ...res.data,
            instoreBizInfo: {
                ...form.value.instoreBizInfo,
                ...res.data.instoreBizInfo,
            },
        };
    }
};
const changeSupplierProducerFlag = (value: string) => {
    if (value === '1') {
        form.value.producer = form.value.supplierInfo?.cusName || '';
    } else {
        form.value.producer = '';
    }
};
// 页面入参解析并加载
onLoad((options: any) => {
    did.value = options?.id || '';
    getDetailById(did.value);
});
</script>
<style lang="scss" scoped>
.card-info-block {
    border: 1rpx solid #afddbb;
    border-radius: 10rpx;
}

.tag-span {
    padding: 4rpx 12rpx;
    font-size: 20rpx;
    border-radius: 18rpx;
}
.close-icon {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 10;
}
</style>
