<template>
    <z-paging ref="paging" bgColor="#fff" safe-area-inset-bottom paging-class="paging-btm-shadow" scroll-with-animation>
        <template #top>
            <ut-navbar :title="did ? '编辑包装任务' : '创建包装任务'" :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 bg-#fff mb-10">
                <view class="h-1" id="inputStorageIdpppp"></view>
                <up-form-item borderBottom label="选择包装对象" prop="inputStorageId" required>
                     
                </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?.stroeUnit || '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="stroeUnit" border-bottom class="form-item-top-padding-0">
                                <up-input v-model="form.stroeUnit" 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 prop="packagingDateStart" 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 || new Date()" 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" :maxDate="new Date()" 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="保质期" prop="expireDate" required 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="packCodeTypepppp"></view>
                <ut-action-sheet v-model="form.packCodeType" :tabs="pt_pack_code_type" mode="custom" title="请选择赋码方式">
                    <up-form-item borderBottom label="赋码方式" required prop="packCodeType">
                        <view v-if="form.packCodeType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_pack_code_type, form.packCodeType) }}</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://ta.zycpzs.cn/oss-file/smart-trace/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>
        <template #bottom>
            <view class="pd-20">
                <up-button type="primary" @click="submit">
                    <text>{{ did ? '保存' : '提交' }}</text>
                </up-button>
            </view>
        </template>
    </z-paging>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import { formItemBtnStyle } from '@/assets/styles/uview-plus';
import type { PackTaskForm } from './types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_pack_code_type, pt_pack_spec_unit, pt_expire_date_unit } = toRefs<any>(proxy?.useDict('pt_pack_code_type', 'pt_pack_spec_unit', 'pt_expire_date_unit'));
const upFormRef = ref();
const paging = ref();
const did = ref<string>('');

const form = ref<PackTaskForm>({
    storageUseAmount: '',
    stroeUnit: 'kg',
    capacity: '',
    unit: '',
    packagingDateStart: '',
    packagingDateEnd: '',
    packSn: '',
    batchSn: '',
    expireDate: '',
    expireDateUnit: '',
    packCodeType: '',
});

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');
                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');
                return Promise.resolve();
            },
        },
    ],
    stroeUnit: [{ required: true, message: '请选择包装单位' }],
    unit: [{ required: true, message: '请选择单位' }],
    packagingDateStart: [{ required: true, message: '请选择开始日期' }],
    packagingDateEnd: [{ required: true, message: '请选择结束日期' }],
    packSn: [{ required: true, message: '请输入包装批号' }],
    batchSn: [{ required: true, message: '请输入成品批号' }],
    expireDate: [{ required: true, message: '请输入保质期' }],
    expireDateUnit: [{ required: true, message: '请选择保质期单位' }],
    packCodeType: [{ required: true, message: '请选择赋码方式' }],
});

const loadDetail = async (id: string) => {
    if (!id) return;
    const res = await useClientRequest.get(`/plt-api/app/packTask/getInfo/${id}`);
    if (res && res.code === 200) {
        const data = res.data || {};
        console.log(data);
    }
};

const submit = async () => {
    try {
        await upFormRef.value?.validate();
    } catch (error: any) {
        const firstErrorField = error && error[0].prop + 'pppp';
        paging.value?.scrollIntoViewById(firstErrorField, 30, true);
        return;
    }

    try {
        await uni.showLoading({ title: did.value ? '保存中...' : '提交中...', mask: true });
        const url = did.value ? '/plt-api/app/packTask/edit' : '/plt-api/app/packTask/save';
        const payload: any = { ...(form.value as any) };
        if (did.value) payload.id = did.value;
        const res = await useClientRequest.post(url, payload);
        uni.hideLoading();
        if (res && res.code === 200) {
            uni.showToast({ title: did.value ? '保存成功' : '新增成功', icon: 'success' });
            uni.$emit('refreshContactUnitDetail');
            uni.$emit('refreshContactUnitList');
            setTimeout(() => uni.navigateBack(), 300);
        }
    } catch (e) {
        uni.hideLoading();
        console.error('保存往来单位失败:', e);
    }
};
// 点击随机生成服务端生成唯一的批号
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 confirmArea = (area: any) => {
    form.value.adcdCodeName = area.fullName;
};

onLoad((options: any) => {});
</script>
<style lang="scss" scoped></style>
