<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: 后续按 seedInfoList 设计种源信息明细，此处先留空结构避免表单错误 -->
                <up-form-item borderBottom label="添加种源信息" required prop="seedInfoList">
                    <view class="flex1">
                        <template v-for="(item, index) in form.seedInfoList" :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]?.varietyInfo?.varietyName }}</span>
                                        <span class="f-s-24 c-#666">{{ selectDictLabel(pt_seed_type, uidMapData[item]?.seedType) }}</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 class="d-flex">
                                    <view class="flex1 f-s-28 pr-10 pd2-4-0">
                                        <span class="c-#666">来源：</span>
                                        <span class="c-#333 f-w-500">{{ selectDictLabel(pt_seed_source, uidMapData[item]?.seedSource) }}</span>
                                    </view>
                                    <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>
                                <view class="d-flex">
                                    <view class="flex1 ov-hd">
                                        <view 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="f-s-28 pr-10 pd2-4-0">
                                            <span class="c-#666">受托单位：</span>
                                            <span class="c-#333 f-w-500">{{ uidMapData[item]?.entrustInfo?.cusName }}</span>
                                        </view>
                                    </view>
                                    <view class="d-flex a-ed" @click="navigateToAddSeedSource(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="navigateToAddSeedSource('', '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="种源级别" prop="seedLevel">
                    <up-input v-model="form.seedLevel" 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-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="instoreBizInfo.instoreDate">
                        <up-input v-model="form.instoreBizInfo.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="库房类型" 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: '2' }"></select-warehouse-input>
                </up-form-item>
                <!-- 入库人 -->
                <up-form-item borderBottom label="入库人" required prop="instoreBizInfo.instoreMg">
                    <up-input v-model="form.instoreBizInfo.instoreMg" placeholder="请输入入库人" border="none" clearable></up-input>
                </up-form-item>
                <!-- 入库备注 -->
                <up-form-item borderBottom label="入库备注" prop="instoreBizInfo.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 { SeedSourceAddTypeEnum } 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_seed_type, pt_seed_source } = toRefs<any>(proxy?.useDict('pt_seed_instore_type', 'pt_warehouse_type', 'pt_seed_type', 'pt_seed_source'));
// 表单与分页等基础状态（参考 base-edit 风格）
const paging = ref<any>(null);
const upFormRef = ref<any>(null);
const showArea = ref(false);
const form = ref<SeedSourceAddTypeEnum>({
    instoreType: '2',
    storageType: '2',
    seedInfoList: [],
    warehouses: [],
    instoreBizInfo: {
        instoreDate: parseTime(new Date(), '{y}-{m}-{d}'),
        instoreMg: infoStore.userInfo?.name || '',
        remark: '',
    },
});
const rules = reactive({
    seedInfoList: [{ required: true, message: '请添加种源信息', type: 'array', min: 1 }],
    instoreType: [{ required: true, message: '请选择入库类型' }],
    'instoreBizInfo.instoreDate': [{ required: true, message: '请选择入库日期' }],
    batchCode: [{ 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].prop + 'pppp';
                paging.value?.scrollIntoViewById(firstErrorField, 30, true);
                return;
            }
            // 提交表单
            uni.showLoading({
                title: '提交中...',
            });
            const params = form.value.seedInfoList.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/storageSeed/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: 'Z',
        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 navigateToAddSeedSource = (uid = '', mode = 'add') => {
    uni.$on('submitForm', (data: any) => {
        uidMapData.value[data.uid] = data.form;
        if (data?.mode == 'add') {
            form.value.seedInfoList.push(data.uid);
        }
        uni.$off('submitForm');
    });
    uni.navigateTo({
        url: '/plant/storage/seed-source/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.seedInfoList.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>
