<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 && mode === 'copy' ? '新增农资入库' : did ? '编辑农资入库' : '新增农资入库'" :fixed="false" border></ut-navbar>
        </template>
        <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
            <!-- 农资信息（复制自 info-edit 字段与顺序） -->
            <view class="pd-24">
                <view class="startline-title">农资信息</view>
            </view>
            <view class="pd-24 bg-#fff">
                <view class="h-1" id="materialNamepppp"></view>
                <up-form-item borderBottom label="产品名称" prop="materialName" required>
                    <up-input v-model="form.materialName" placeholder="请输入产品名称" border="none" clearable></up-input>
                </up-form-item>
                <view class="h-1" id="materialTypepppp"></view>
                <ut-action-sheet :tabs="pt_material_type" mode="custom" title="农资类别" v-model="form.materialType">
                    <up-form-item borderBottom label="农资类别" required prop="materialType">
                        <view v-if="form.materialType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_material_type, form.materialType) }}</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>
                <!-- 入库数量与单位 -->
                <template v-if="mode === 'copy'">
                    <up-form-item label="入库量" required class="form-item-bottom-padding-0">
                        <div class="flex1 d-flex">
                            <div class="flex1 ov-hd">
                                <up-form-item prop="capacity" border-bottom class="form-item-top-padding-0">
                                    <up-input v-model="form.capacity" placeholder="请输入入库量" border="none" clearable></up-input>
                                </up-form-item>
                            </div>
                            <div class="pd-5"></div>
                            <div class="min-w-200">
                                <ut-action-sheet v-model="form.unit" :tabs="pt_materail_unit" mode="custom" title="选择单位">
                                    <up-form-item prop="unit" border-bottom class="form-item-top-padding-0">
                                        <view class="flex1" style="line-height: 24px">
                                            <view v-if="form.unit" class="f-s-30 c-333 f-w-5 text-center">{{ selectDictLabel(pt_materail_unit, form.unit) }}</view>
                                            <view v-else class="f-s-30 c-ccc f-w-4 text-center">单位</view>
                                        </view>
                                        <template #right>
                                            <up-icon size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                                        </template>
                                    </up-form-item>
                                </ut-action-sheet>
                            </div>
                        </div>
                    </up-form-item>
                </template>
                <template v-else>
                    <up-form-item label="入库量" prop="capacity" required class="form-item-bottom-padding-0">
                        <view class="f-s-30 c-333 f-w-5 flex1">{{ form?.capacity }}{{ form?.unit }}</view>
                    </up-form-item>
                </template>
                <view class="h-1" id="specpppp"></view>
                <view class="h-1" id="specUnitpppp"></view>
                <template v-if="!['kg', 'L'].includes(form?.unit as string)">
                    <up-form-item label="规格" prop="spec" required class="form-item-bottom-padding-0">
                        <div class="flex1 d-flex">
                            <div class="flex1 ov-hd">
                                <up-form-item prop="spec" border-bottom class="form-item-top-padding-0">
                                    <up-input v-model="form.spec" placeholder="请输入规格" border="none" clearable></up-input>
                                </up-form-item>
                            </div>
                            <div class="pd-5"></div>
                            <div class="min-w-200">
                                <ut-action-sheet v-model="form.specUnit" :tabs="pt_materail_spec_unit" mode="custom" title="选择单位">
                                    <up-form-item prop="specUnit" border-bottom class="form-item-top-padding-0">
                                        <view class="flex1" style="line-height: 24px">
                                            <view v-if="form.specUnit" class="f-s-30 c-333 f-w-5 text-center">{{ selectDictLabel(pt_materail_spec_unit, form.specUnit) }}</view>
                                            <view v-else class="f-s-30 c-ccc f-w-4 text-center">单位</view>
                                        </view>
                                        <template #right>
                                            <up-icon class="mr-10" size="22rpx" color="#37A954" name="arrow-down-fill"></up-icon>
                                        </template>
                                    </up-form-item>
                                </ut-action-sheet>
                            </div>
                            <div class="pd2-0-10 c-#ccc">/</div>
                            <div class="min-w-200">
                                <up-form-item prop="unit" border-bottom class="form-item-top-padding-0">
                                    <view class="flex1" style="line-height: 24px">
                                        <view v-if="form.unit" class="f-s-30 c-333 f-w-5 text-center">{{ selectDictLabel(pt_materail_unit, form.unit) }}</view>
                                        <view v-else class="f-s-30 c-ccc f-w-4 text-center">单位</view>
                                    </view>
                                    <template #right>
                                        <up-icon size="22rpx" color="#fff" name="arrow-down-fill"></up-icon>
                                    </template>
                                </up-form-item>
                            </div>
                        </div>
                    </up-form-item>
                </template>
                <view class="h-1" id="sourceTypepppp"></view>
                <ut-action-sheet :tabs="pt_source_type" 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_source_type, 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>
                <template v-if="['1'].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="productCode">
                    <up-input v-model="form.productCode" placeholder="请输入生产批号" border="none" clearable></up-input>
                </up-form-item>
                <ut-datetime-picker v-model="form.productDate" :maxDate="new Date()" mode="date">
                    <up-form-item borderBottom label="生产日期" prop="productDate">
                        <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>
                <up-form-item borderBottom label="品牌" prop="brand">
                    <up-input v-model="form.brand" placeholder="请输入品牌" border="none" clearable></up-input>
                </up-form-item>
                <!-- 登记证号 肥料和农药才有登记证号 -->
                <template v-if="['1', '2'].includes(form.materialType as string)">
                    <up-form-item borderBottom label="登记证号" prop="materialCode">
                        <up-input v-model="form.materialCode" placeholder="请输入登记证号" border="none" clearable></up-input>
                    </up-form-item>
                </template>
                <!-- 媒体与附件 -->
                <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>
                <!-- 检验报告 -->
                <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>

            <view class="pd-24">
                <view class="startline-title">入库信息</view>
            </view>
            <view class="pd-24 bg-#fff">
                <!-- 入库类型 -->
                <up-form-item borderBottom label="入库类型" required prop="instoreType">
                    <view v-if="form.instoreType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_seed_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" 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>
              
                    <!-- 入库批号 -->
                <up-form-item v-if="mode === 'copy'" 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 v-else borderBottom label="入库批号" required prop="batchCode">
                    <view class="f-s-30 c-333 f-w-5 flex1">{{ form.batchCode }}</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: '1' }"></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>
        </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 { formItemBtnStyle } from '@/assets/styles/uview-plus';
import { AgroProductInstoreAddTypeEnum } from '../models/type';
import ContactUnitInput from '@/models/contact-unit-input/contact-unit-input.vue';
import SelectWarehouseInput from '@/models/select-warehouse-input/select-warehouse-input.vue';
import { parseTime } from '@/utils/ruoyi';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_material_type, pt_materail_unit, pt_materail_spec_unit, pt_source_type, yes_no, pt_seed_instore_type, pt_warehouse_type } = toRefs<any>(proxy?.useDict('pt_material_type', 'pt_materail_unit', 'pt_materail_spec_unit', 'pt_source_type', 'yes_no', 'pt_seed_instore_type', 'pt_warehouse_type') || {});
const paging = ref<any>(null);
const upFormRef = ref<any>(null);
// 单条农资信息 + 入库信息的合并表单
const form = ref<AgroProductInstoreAddTypeEnum | any>({
    materialName: '',
    materialType: '',
    capacity: '',
    unit: '',
    spec: '',
    specUnit: '',
    sourceType: '',
    supplierId: undefined,
    supplierInfo: undefined,
    supplierProducerFlag: '',
    producer: '',
    productCode: '',
    productDate: '',
    brand: '',
    materialCode: '',
    imgs: undefined,
    vedios: undefined,
    examinReport: [],
    instoreType: '2',
    storageType: '1',
    agroProductInfoList: [],
    warehouses: [],
    instoreBizInfo: {
        instoreDate: parseTime(new Date(), '{y}-{m}-{d}'),
        instoreMg: '',
        remark: '',
    },
});
const rules = reactive({
    materialName: [{ required: true, message: '请输入产品名称' }],
    materialType: [{ required: true, message: '请选择农资类别' }],
    capacity: [{ required: true, message: '请输入入库量' }],
    unit: [{ required: true, message: '请选择单位' }],
    sourceType: [{ required: true, message: '请选择农资来源' }],
    // 规格与规格单位仅在单位为 kg/L 时必填
    spec: [
        {
            asyncValidator: (rule: any, value: any) => {
                if (!['kg', 'L'].includes(form.value.unit as string) && !value) {
                    return Promise.reject('请输入规格');
                }
                return Promise.resolve();
            },
        },
    ],
    specUnit: [
        {
            asyncValidator: (rule: any, value: any) => {
                if (!['kg', 'L'].includes(form.value.unit as string) && !value) {
                    return Promise.reject('请选择规格单位');
                }
                return Promise.resolve();
            },
        },
    ],
    // 供应商仅在来源为“采购”等特定来源时必选（目前为来源=1）
    supplierId: [
        {
            asyncValidator: (rule: any, value: any) => {
                if (['1'].includes(form.value.sourceType as string) && !value) {
                    return Promise.reject('请选择供应商');
                }
                return Promise.resolve();
            },
        },
    ],
    agroProductInfoList: [{ required: true, message: '请添加农资信息', type: 'array', min: 1 }],
    instoreType: [{ required: true, message: '请选择入库类型' }],
    'instoreBizInfo.instoreDate': [{ required: true, message: '请选择入库日期' }],
    batchCode: [{ required: true, message: '请输入入库批号' }],
    storageType: [{ required: true, message: '请选择库房类型' }],
    'instoreBizInfo.instoreMg': [{ required: true, message: '请输入入库人' }],
});

// 提交：当前页面改为单条农资信息，直接提交合并后的对象
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 = mode.value === 'copy' ? await useClientRequest.post('/plt-api/app/material/instore', form.value) : await useClientRequest.post('/plt-api/app/material/edit', form.value);
                uni.hideLoading();
                if (!res || res.code !== 200) return;
                uni.showToast({
                    title: '提交成功',
                    icon: 'success',
                });
                uni.$emit('seed-agro-detail-refresh');
                uni.$emit('refreshStorageRoomList');
                setTimeout(() => {
                    uni.navigateBack({
                        delta: 1,
                    });
                }, 1500);
            } catch (error) {
                uni.hideLoading();
            }
        },
        500,
        true,
    );
};
// 点击随机生成服务端生成唯一的批号（与 add 一致）
const generateBatchCode = async () => {
    uni.showLoading({
        title: '生成中...',
    });
    const res = await useClientRequest.post('/plt-api/app/plantationTask/getBatchCode', {
        plType: 'M',
        linkType: 'I',
    });
    if (res && res.code === 200) {
        uni.hideLoading();
        form.value.batchCode = res.data;
        uni.showToast({
            title: '批号生成成功',
            icon: 'success',
        });
    }
};

const did = ref('');
const mode = ref('');
// 获取详情（仓库信息）
const getDetailById = async (id: string) => {
    if (!id) return;
    const res = await useClientRequest.get(`/plt-api/app/material/getInfo/${id}`);
    if (res && res.code === 200) {
        form.value = {
            ...form.value,
            ...res.data,
            instoreBizInfo: {
                ...form.value.instoreBizInfo,
                ...res.data.instoreBizInfo,
            },
        };
        if (mode.value === 'copy') {
            form.value.batchCode = '';
            form.value.id = undefined;
            form.value.instoreBizInfo.instoreDate = parseTime(new Date(), '{y}-{m}-{d}');
            form.value.warehouses = [];
            form.value.capacity = '';
            form.value.spec = '';
            form.value.specUnit = '';
        }
    }
};
const changeSupplierProducerFlag = () => {
    if (form.value.supplierProducerFlag === '1') {
        form.value.producer = form.value.supplierInfo?.cusName || '';
    } else {
        form.value.producer = '';
    }
};
// 页面入参解析并加载
onLoad((options: any) => {
    did.value = options?.id || '';
    mode.value = options?.mode || '';
    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;
}
:deep(.form-item-top-padding-0) {
    > .u-form-item__body {
        padding-top: 0rpx;
    }
}

:deep(.form-item-bottom-padding-0) {
    > .u-form-item__body {
        padding-bottom: 0rpx;
    }
}
</style>
