<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="'新增农资入库'" :fixed="false" border></ut-navbar>
        </template>
        <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
            <!-- 农资信息 -->
            <view class="pd-24">
                <view class="startline-title">农资信息</view>
            </view>
            <view class="pd-24 bg-#fff">
                <!-- TODO: 后续按 agroProductInfoList 设计农资信息明细，此处先留空结构避免表单错误 -->
                <up-form-item borderBottom label="添加农资信息" required prop="agroProductInfoList">
                    <view class="flex1">
                        <template v-for="(item, index) in form.agroProductInfoList" :key="index">
                            <view class="bg-#FBFDFB card-info-block pd-24 p-rtv mb-12">
                                <view class="d-flex flex1 mb-10">
                                    <view class="flex1">
                                        <span class="f-s-34 c-#333 f-w-500 mr-10">{{ uidMapData[item]?.materialName
                                            }}</span>
                                        <span class="f-s-24 c-#666">{{ selectDictLabel(pt_material_type, uidMapData[item]?.materialType) }}</span>
                                    </view>
                                    <view class="pr-60">
                                        <view v-if="uidMapData[item]?.examinReport?.length"
                                            class="tag-span c-primary bg-#EBF6EE">已检</view>
                                        <view v-else class="tag-span c-danger bg-#F9ECEA">未检</view>
                                    </view>
                                </view>
                                <view v-if="uidMapData[item]?.supplierId && ['1'].includes(uidMapData[item]?.sourceType as string)" class="f-s-28 pr-10 pd2-4-0">
                                    <span class="c-#666">供应商：</span>
                                    <span class="c-#333 f-w-500">{{ uidMapData[item]?.supplierInfo?.cusName }}</span>
                                </view>
                                <view class="d-flex">
                                    <view class="d-flex flex1 ov-hd mr-10">

                                        <view class="flex1 f-s-28 pd2-4-0">
                                            <span class="c-#666">入库量：</span>
                                            <span class="c-#333 f-w-500">{{ uidMapData[item]?.capacity }}{{
                                                uidMapData[item]?.unit }}</span>
                                        </view>
                                        <view v-if="!['kg', 'L'].includes(uidMapData[item]?.unit)"
                                            class="flex1 f-s-28 pr-10 pd2-4-0">
                                            <span class="c-#666">规格：</span>
                                            <span class="c-#333 f-w-500">{{ uidMapData[item]?.spec }} {{
                                                uidMapData[item]?.specUnit }}/{{ uidMapData[item]?.unit }}</span>
                                        </view>
                                    </view>
                                    <view class="d-flex a-ed" @click="navigateToAddAgroProduct(item, 'edit')">
                                        <view class="pd-10 c-primary f-s-20">去编辑{{ '>' }}</view>
                                    </view>
                                </view>
                                <view class="close-icon pd-16" @click.stop="deleteRow(index, item)">
                                    <up-icon color="#F81242" name="close" size="32rpx"></up-icon>
                                </view>
                            </view>
                        </template>

                        <up-button type="primary" plain @click="navigateToAddAgroProduct('', 'add')">
                            <up-icon class="mr-10" name="plus" color="#37A954"></up-icon>
                            <span>添加农资入库信息</span>
                        </up-button>
                    </view>
                </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 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-333 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 { AgroProductInstoreAddTypeEnum } from '../models/type';
import { formItemBtnStyle } from '@/assets/styles/uview-plus';
import { generateUniqueId } from '@/utils/public';
import { parseTime } from '@/utils/ruoyi';
import SelectWarehouseInput from '@/models/select-warehouse-input/select-warehouse-input.vue';
import { useInfoStore } from '@/store';
const infoStore = useInfoStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 仅使用到的字典：入库类型、库房类型、显示农资卡片中的种类和来源
const { pt_seed_instore_type, pt_warehouse_type, pt_material_type, pt_source_type } = toRefs<any>(
    proxy?.useDict('pt_seed_instore_type', 'pt_warehouse_type', 'pt_material_type', 'pt_source_type'),
);
// 表单与分页等基础状态（参考 base-edit 风格）
const paging = ref<any>(null);
const upFormRef = ref<any>(null);
// 农资入库汇总表单
const form = ref<AgroProductInstoreAddTypeEnum>({
    instoreType: '2',
    storageType: '1',
    agroProductInfoList: [],
    warehouses: [],
    instoreBizInfo: {
        instoreDate: parseTime(new Date(), '{y}-{m}-{d}'),
        instoreMg: infoStore.userInfo?.name || '',
        remark: '',
    },
});
const rules = reactive({
    
    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 () => {
    console.log(form.value);

    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: '提交中...',
            });
            const params = form.value.agroProductInfoList.map((uid) => {
                return {
                    ...uidMapData.value[uid],
                    ...form.value,
                    instoreBizInfo: {
                        ...form.value.instoreBizInfo,
                        ...uidMapData.value[uid]?.instoreBizInfo,
                    }
                };
            })
            try {
                const res = await useClientRequest.post('/plt-api/app/material/batchInstore', params);
                if (!res || res.code !== 200) return;
                uni.hideLoading();
                uni.showToast({
                    title: '提交成功',
                    icon: 'success',
                });
                uni.$emit('refreshStorageRoomList');
                // 返回上一页
                setTimeout(() => {
                    uni.navigateBack({
                        delta: 1,
                    });
                }, 1500);
            } catch (error) {
                uni.hideLoading();
            }
        },
        500,
        true,
    );
};
// 点击随机生成服务端生成唯一的批号
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 uidMapData = ref({} as any);
// 添加农资入库跳转
const navigateToAddAgroProduct = (uid = '', mode = 'add') => {
    uni.$on('submitForm', (data: any) => {
        uidMapData.value[data.uid] = data.form;
        if (data?.mode == 'add') {
            form.value.agroProductInfoList.push(data.uid);
        }
        uni.$off('submitForm');
    });
    uni.navigateTo({
        url: '/plant/storage/agro-product/info-edit/index',
        success(res) {
            res.eventChannel.emit('optionsParam', {
                uid: uid || generateUniqueId(),
                mode: mode,
                form: uid ? uidMapData.value[uid] : {}
            });
        }
    });
};
const deleteRow = (index: number, uid: string) => {
    form.value.agroProductInfoList.splice(index, 1);
    delete uidMapData.value[uid];
};
// 编辑时加载详情
onLoad((optins: any) => {

});
</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>
