<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">
                <up-form-item borderBottom label="添加种源信息" required prop="processOutPutIds">
                    <view class="flex1">
                        <template v-for="(item, index) in selectedSeeds" :key="item.id">
                            <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">{{ item.specnLevel }}</span>
                                        <span class="f-s-24 c-#666">{{ item.finalSpecn }}{{ item.finalUnit }}{{ selectDictLabel(pt_final_form_type, item.finalFormType) }}</span>
                                    </view>
                                    <view class="pr-60">
                                        <view v-if="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 class="d-flex flex-cln">
                                    <view class="flex1 f-s-28 pr-10 pd2-4-0">
                                        <span class="c-#666">加工批号：</span>
                                        <span class="c-#333 f-w-500">{{ item?.processCode || '-' }}</span>
                                    </view>
                                    <view class="flex1 f-s-28 pd2-4-0">
                                        <span class="c-#666">产量：</span>
                                        <span class="c-#333 f-w-500">{{ item.capacity }}{{ item.unit }}</span>
                                    </view>
                                </view>
                                <view class="close-icon pd-16" @click.stop="deleteSeed(index)">
                                    <up-icon color="#F81242" name="close" size="32rpx"></up-icon>
                                </view>
                            </view>
                        </template>

                        <up-button type="primary" plain @click="showSelectDialog = true">
                            <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.instoreDate" :maxDate="new Date()" mode="date">
                    <up-form-item borderBottom label="入库日期" required prop="instoreDate">
                        <up-input v-model="form.instoreDate" readonly placeholder="请选择入库日期" border="none" clearable></up-input>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" 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="库房类型" required>
                    <view class="f-s-30 c-ccc f-w-4 flex1">种源库</view>
                </up-form-item>
                <!-- 存放库房 -->
                <up-form-item borderBottom label="存放库房" prop="warehouses" required>
                    <select-warehouse-input v-model="form.warehouses" title="请选择种源存放库房" :params="{ type: '2' }"></select-warehouse-input>
                </up-form-item>
                <!-- 入库人 -->
                <up-form-item borderBottom label="入库人" required prop="instorer">
                    <up-input v-model="form.instorer" placeholder="请输入入库人" border="none" clearable></up-input>
                </up-form-item>
                <!-- 入库备注 -->
                <up-form-item label="入库备注" prop="remark">
                    <up-textarea v-model="form.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>

    <!-- 选择种子弹窗 -->
    <select-seed-dialog v-model="showSelectDialog" :process-id="processId" @confirm="handleSeedConfirm" />
</template>

<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import { formItemBtnStyle } from '@/assets/styles/uview-plus';
import { parseTime } from '@/utils/ruoyi';
import SelectWarehouseInput from '@/models/select-warehouse-input/select-warehouse-input.vue';
import SelectSeedDialog from './models/select-seed-dialog.vue';
import { useInfoStore } from '@/store';

const infoStore = useInfoStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_seed_instore_type, pt_warehouse_type, pt_final_form_type } = toRefs<any>(proxy?.useDict('pt_seed_instore_type', 'pt_warehouse_type', 'pt_final_form_type'));

// 表单与分页等基础状态
const paging = ref<any>(null);
const upFormRef = ref<any>(null);

// 表单数据
const form = ref({
    instoreType: '4',
    storageType: '2',
    batchCode: '',
    warehouses: [] as any[],
    instoreDate: parseTime(new Date(), '{y}-{m}-{d}'),
    instorer: infoStore.userInfo?.name || '',
    remark: '',
    processOutPutIds: [] as any[],
});

const rules = reactive({
    processOutPutIds: [{ required: true, message: '请选择要入库的种子' }],
    instoreType: [{ required: true, message: '请选择入库类型' }],
    instoreDate: [{ required: true, message: '请选择入库日期' }],
    batchCode: [{ required: true, message: '请输入入库批号' }],
    instorer: [{ required: true, message: '请输入入库人' }],
    warehouses: [{ required: true, message: '请选择存放库房' }],
});

// 选中的种子列表
const selectedSeeds = ref<any[]>([]);
const showSelectDialog = ref(false);

// 处理种子选择确认（直接接收完整数据）
const handleSeedConfirm = (items: any[]) => {
    selectedSeeds.value = items;
};

// 删除种子
const deleteSeed = (index: number) => {
    selectedSeeds.value.splice(index, 1);
};

// 提交表单
const submitForm = async () => {
    uni.$u.debounce(
        async () => {
            try {
                form.value.processOutPutIds = selectedSeeds.value.map((item) => item.id);
                await upFormRef.value?.validate();
            } catch (error: any) {
                // 滚动到第一个错误字段
                const firstErrorField = error && error[0].field + 'pppp';
                paging.value?.scrollIntoViewById(firstErrorField, 30, true);
                return;
            }

            // 验证是否选择了种子
            if (selectedSeeds.value.length === 0) {
                uni.showToast({
                    title: '请选择要入库的种子',
                    icon: 'none',
                });
                return;
            }

            uni.showLoading({
                title: '提交中...',
            });

            // 构建提交参数
            const params = {
                processOutPutIds: selectedSeeds.value.map((item) => item.id),
                batchCode: form.value.batchCode,
                warehouses: form.value.warehouses.map((w) => ({
                    warehouseId: w.warehouseId,
                    shelfId: w.shelfId,
                })),
                instoreType: form.value.instoreType,
                instorer: form.value.instorer,
                remark: form.value.remark,
                instoreMg: form.value.instorer,
                instoreDate: form.value.instoreDate,
            };

            try {
                const res = await useClientRequest.post('/plt-api/app/processOutPut/outPutInstore', 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: 'Z',
        linkType: 'I',
    });
    if (res && res.code === 200) {
        uni.hideLoading();
        form.value.batchCode = res.data;
        uni.showToast({
            title: '批号生成成功',
            icon: 'success',
        });
    }
};

const processId = ref<any>();
onLoad((optins: any) => {
    processId.value = optins?.processId;
    console.log(optins, 'processId.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>
