<template>
    <z-paging ref="paging" bgColor="#f7f7f7" safe-area-inset-bottom scroll-with-animation>
        <template #top>
            <ut-navbar :title="'创建包装任务'" :fixed="false" border></ut-navbar>
        </template>
        <up-form class="p-rtv bg-#fff" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
            <view class="pd-24 bg-#fff mb-10">
                <view class="h-1" id="inputStorageIdpppp"></view>
                <up-form-item borderBottom label="选择包装对象" prop="inputStorageId" required>
                    <view class="flex1">
                        <up-button v-if="!form.inputStorageId" @click="selectStorage" 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 p-rtv border-#A9D7B4 b-radius">
                            <ObjectCardStorage :item="form.stroeObject"></ObjectCardStorage>
                            <view class="close-icon pd-16" @click="deleteStorage">
                                <up-icon color="#F81242" name="close" size="32rpx"></up-icon>
                            </view>
                        </view>
                    </view>
                </up-form-item>
                <view class="h-1" id="storageUseAmountpppp"></view>
                <up-form-item borderBottom label="本次包装用量" prop="storageUseAmount" required>
                    <up-input v-model="form.storageUseAmount" placeholder="请输入本次包装用量" border="none" clearable></up-input>
                    <template #right>
                        <span class="f-s-30 f-w-5 c-#333">{{ form?.storageUseUnit || 'kg' }}</span>
                    </template>
                </up-form-item>
                <view class="h-1" id="capacitypppp"></view>
                <view class="h-1" id="unitpppp"></view>
                <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="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="w-200">
                            <up-form-item prop="storageUseUnit" border-bottom class="form-item-top-padding-0">
                                <up-input v-model="form.storageUseUnit" inputAlign="center" readonly placeholder="单位" border="none" clearable></up-input>
                            </up-form-item>
                        </div>
                        <div class="pd2-0-10 c-#ccc d-flex a-c j-c">/</div>
                        <div class="w-200">
                            <ut-action-sheet v-model="form.unit" :tabs="pt_pack_spec_unit" mode="custom" title="选择单位">
                                <up-form-item prop="unit" border-bottom class="form-item-top-padding-0">
                                    <up-input v-model="form.unit" inputAlign="center" 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-action-sheet>
                        </div>
                    </div>
                </up-form-item>
                <view class="h-1" id="packagingDateStartpppp"></view>
                <view class="h-1" id="packagingDateEndpppp"></view>
                <up-form-item required label="包装日期" class="form-item-bottom-padding-0">
                    <view class="flex1 d-flex">
                        <view class="flex1">
                            <ut-datetime-picker v-model="form.packagingDateStart" :maxDate="form.packagingDateEnd" mode="date">
                                <up-form-item borderBottom prop="packagingDateStart" class="form-item-top-padding-0">
                                    <up-input v-model="form.packagingDateStart" 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.packagingDateEnd" :minDate="form.packagingDateStart" mode="date">
                                <up-form-item borderBottom prop="packagingDateEnd" class="form-item-top-padding-0">
                                    <up-input v-model="form.packagingDateEnd" 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>
                <!-- 包装批号 -->
                <view class="h-1" id="packSnpppp"></view>
                <up-form-item borderBottom label="包装批号" prop="packSn" required>
                    <up-input v-model="form.packSn" placeholder="请输入包装批号" border="none" clearable></up-input>
                    <template #right>
                        <up-button @click="generateBatchCode" type="primary" :customStyle="formItemBtnStyle">随机生成</up-button>
                    </template>
                </up-form-item>
                <view class="h-1" id="batchSnpppp"></view>
                <up-form-item borderBottom label="成品批号" prop="batchSn" required>
                    <up-input v-model="form.batchSn" placeholder="请输入成品批号" border="none" clearable></up-input>
                </up-form-item>
                <!-- 保质期 12月，数字加单位单位两个字段， expireDate，expireDateUnit -->
                <view class="h-1" id="expireDatepppp"></view>
                <view class="h-1" id="expireDateUnitpppp"></view>
                <up-form-item label="保质期" class="form-item-bottom-padding-0">
                    <div class="flex1 d-flex a-c">
                        <div class="flex1 ov-hd">
                            <up-form-item prop="expireDate" border-bottom class="form-item-top-padding-0">
                                <up-input v-model="form.expireDate" placeholder="请输入保质期" border="none" clearable></up-input>
                            </up-form-item>
                        </div>
                        <div class="pd-5"></div>
                        <div class="w-200">
                            <ut-action-sheet v-model="form.expireDateUnit" :tabs="pt_expire_date_unit" mode="custom" title="选择单位">
                                <up-form-item prop="expireDateUnit" border-bottom class="form-item-top-padding-0">
                                    <up-input v-model="form.expireDateUnit" inputAlign="center" 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-action-sheet>
                        </div>
                    </div>
                </up-form-item>
                <!-- 请选择赋码方式 -->
                <view class="h-1" id="refTypepppp"></view>
                <ut-action-sheet v-model="form.refType" :tabs="pt_pack_ref_type" mode="custom" title="请选择赋码方式">
                    <up-form-item borderBottom label="赋码方式" required prop="refType">
                        <view v-if="form.refType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_pack_ref_type, form.refType) }}</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="d-flex a-c pd2-10-0" @click="$u.route({ url: '/tools/view-html/index', params: { url: 'https://yujin-szyy.oss-cn-chengdu.aliyuncs.com/szyy/template/pack_code_type.html', title: '赋码方式区别' } })">
                    <up-icon size="28rpx" name="question-circle" color="#37A954"></up-icon>
                    <span class="c-primary f-s-24">两种赋码方式的区别？怎么选择？</span>
                </view>
            </view>
        </up-form>
        <view class="d-flex flex-cln a-c pd3-40-24-24">
            <view class="f-s-30 c-#333 f-w-5 mb-16">
                <span>预计分包数：</span>
                <span class="f-s-46 c-primary f-w-7">{{ packResult.packNum || '-' }}</span>
                <span>包</span>
            </view>
            <view class="d-flex a-c mb-30">
                <view class="f-s-28 c-#333">包装规格：</view>
                <view class="d-flex a-c gap-24">
                    <view class="bg-#E3EFE6 pd2-12-28 c-primary radius-8 f-s-26">{{ packResult.spec1 || '-' }}</view>
                    <view v-if="packResult.spec2" class="bg-#E3EFE6 pd2-12-28 c-primary radius-8 f-s-26">{{ packResult.spec2 || '-' }}</view>
                </view>
            </view>
            <up-button type="primary" @click="submit">立即分包</up-button>
        </view>
    </z-paging>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import { formItemBtnStyle } from '@/assets/styles/uview-plus';
import type { PackTaskForm } from './types';
import NP from 'number-precision';
import ObjectCardStorage from '@/plant/models/warehouseCard/object-card-storage.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_pack_ref_type, pt_pack_spec_unit, pt_expire_date_unit } = toRefs<any>(proxy?.useDict('pt_pack_ref_type', 'pt_pack_spec_unit', 'pt_expire_date_unit'));
const upFormRef = ref();
const paging = ref();
const form = ref<PackTaskForm>({
    storageUseAmount: '',
    storageUseUnit: 'kg',
    capacity: '',
    unit: '',
    packagingDateStart: '',
    packagingDateEnd: '',
    packSn: '',
    batchSn: '',
    expireDate: '',
    expireDateUnit: '',
    refType: '',
    packCodeType: '3',
});

const rules = reactive<Record<string, any>>({
    storageUseAmount: [
        { required: true, message: '请输入本次包装用量' },
        {
            asyncValidator: (rule: any, value: any) => {
                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');
                // 本次包装用量不能大于剩余可用量
                if (form.value.stroeObject && num > form.value.stroeObject.restAmount) {
                    return Promise.reject(`本次包装用量不能大于剩余量${form.value.stroeObject.restAmount}${form.value.storageUseUnit}`);
                }
                return Promise.resolve();
            },
        },
    ],
    capacity: [
        { required: true, message: '请输入包装规格' },
        {
            asyncValidator: (rule: any, value: any) => {
                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');
                // 包装规格不能大于本次包装用量
                if (form.value.storageUseAmount && num > Number(form.value.storageUseAmount)) {
                    return Promise.reject('包装规格不能大于本次包装用量');
                }
                return Promise.resolve();
            },
        },
    ],
    storageUseUnit: [{ required: true, message: '请选择包装单位' }],
    unit: [{ required: true, message: '请选择单位' }],
    packagingDateStart: [{ required: true, message: '请选择开始日期' }],
    packagingDateEnd: [{ required: true, message: '请选择结束日期' }],
    packSn: [{ required: true, message: '请输入包装批号' }],
    batchSn: [{ required: true, message: '请输入成品批号' }],
    refType: [{ required: true, message: '请选择赋码方式' }],
});

const submit = () => {
    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;
        }

        try {
            await uni.showLoading({ title: '分包中...', mask: true });
            const payload: any = { ...(form.value as any), planCount: packResult.value.packNum };
            delete payload.stroeObject;
            const res = await useClientRequest.post('/plt-api/app/packTask/save', payload);
            uni.hideLoading();
            if (res && res.code === 200) {
                uni.showToast({ title: '操作成功', icon: 'success' });
                uni.$emit('refreshPackTaskList');
                setTimeout(
                    () =>
                        uni.navigateBack({
                            delta: 1,
                        }),
                    300,
                );
            }
        } catch (e) {
            uni.hideLoading();
            console.error('保存往来单位失败:', e);
        }
    }, 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.packSn = res.data;
        uni.showToast({
            title: '批号生成成功',
            icon: 'success',
        });
    }
};
// 去选择包装对象页选择包装对象，选择后返回并赋值
const selectStorage = () => {
    uni.$on('selectStorageObject', (data: any) => {
        console.log(data, '---');
        form.value.inputStorageId = data.id;
        form.value.packTaskType = data.storageType;
        form.value.storageUseUnit = data.unit;
        form.value.storageUseAmount = '';
        form.value.capacity = '';
        form.value.stroeObject = data;
        form.value.batchSn = data?.batchCode;
        uni.$off('selectStorageObject');
    });
    uni.$u.route({
        type: 'navigateTo',
        url: '/plant/packaging/select-object/index',
        params: {
            emitField: 'selectStorageObject',
            storageType: form.value.packTaskType, // 传入当前选择的包装对象类型，种子、苗木、农资等
            id: form.value.inputStorageId, // 传入当前选择的包装对象id，编辑时使用，用于回显选中状态
        },
    });
};
const deleteStorage = () => {
    form.value.inputStorageId = '';
    form.value.storageUseUnit = 'kg';
    form.value.storageUseAmount = '';
    form.value.capacity = '';
    form.value.unit = '';
    form.value.stroeObject = null;
};
// 计算属性分包结果
const packResult = computed(() => {
    // 预计分包数 = 本次包装用量 / 包装规格，向上取整
    // 分包数，包装规格，整除的情况，直接除；不整除的情况，向上取整
    // 包装规格，整除的时候包装规格只有一个，不整除包装规格有两个，第二个是剩余量
    const result: any = {
        packNum: 0,
        spec1: '',
        // 零包规格
        spec2: '',
    };
    if (form.value.storageUseAmount && form.value.capacity) {
        const useAmount = Number(form.value.storageUseAmount);
        const capacity = Number(form.value.capacity);
        if (capacity > 0) {
            result.packNum = Math.ceil(useAmount / capacity);
            result.spec1 = `${capacity}${form.value.storageUseUnit}/${form.value.unit}`;
            if (useAmount % capacity !== 0) {
                const lastAmount = NP.round(useAmount - capacity * Math.floor(useAmount / capacity), 2);
                result.spec2 = `${lastAmount}${form.value.storageUseUnit}/${form.value.unit}`; // 零包规格
            } else {
                result.spec2 = ''; // 没有零包规格
            }
        }
    }
    return result;
});
onLoad((options: any) => {});
</script>
<style lang="scss" scoped>
.close-icon {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
}
</style>
