<template>
    <z-paging ref="paging" bgColor="#F7F7F7" safe-area-inset-bottom paging-class="paging-btm-shadow" scroll-with-animation>
        <template #top>
            <ut-navbar title="库存损耗登记" :fixed="false" border></ut-navbar>
        </template>
        <up-form class="p-rtv pd-24" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
            <view class="bg-fff b-radius-16">
                <view class="pd3-10-24-24 up-border-bottom">
                    <template v-if="info?.stockType === '1'">
                        <view class="d-flex j-ed a-c mb-16">
                            <view class="f-s-22 c-#666">{{ info?.instoreBizInfo?.instoreDate }}</view>
                        </view>
                        <view class="d-flex flex1 mb-10">
                            <view class="flex1">
                                <span class="f-s-34 c-#333 f-w-500 mr-10">{{ info?.materialName }}</span>
                                <span class="f-s-24 c-#666">{{ selectDictLabel(pt_material_type, info?.materialType) }}</span>
                            </view>
                            <view>
                                <view v-if="info?.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="pd2-4-0 f-s-28">
                            <span class="c-#666">入库批号：</span>
                            <span class="c-#333 f-w-500">{{ info?.batchCode }}</span>
                        </view>
                        <view v-if="info?.supplier" class="pd2-4-0 f-s-28">
                            <span class="c-#666">供应商：</span>
                            <span class="c-#333 f-w-500">{{ info?.supplier }}</span>
                        </view>
                        <view class="pd2-4-0 f-s-28">
                            <span class="c-#666">入库量：</span>
                            <span class="c-#333 f-w-500">{{ info?.capacity }}{{ info?.unit }}</span>
                        </view>
                        <view class="d-flex">
                            <view v-if="info?.restAmount" class="pd2-4-0 f-s-28 flex1">
                                <span class="c-#666">出库量：</span>
                                <span class="c-#333 f-w-500">{{ info?.inputAmount || '0' }}{{ info?.unit }}</span>
                            </view>
                            <view v-if="info?.restAmount" class="pd2-4-0 f-s-28 flex1">
                                <span class="c-primary">剩余量：</span>
                                <span class="c-primary f-w-500">{{ info?.restAmount || '0' }}{{ info?.unit }}</span>
                            </view>
                        </view>
                    </template>
                    <template v-if="info?.stockType === '2'">
                        <view class="d-flex j-sb a-c li-item-head mb-16">
                            <view class="li-left-tag" :class="{ [`bg-${selectDictListClass(pt_seed_instore_type, info?.instoreType)}`]: true }">{{ selectDictLabel(pt_seed_instore_type, info?.instoreType) }}</view>
                            <view class="f-s-22 c-#666">{{ info?.updateTime || info?.createTime }}</view>
                        </view>
                        <view class="mb-10">
                            <span class="f-s-34 c-#333 f-w-500 mr-10">{{ info?.variety }}</span>
                            <span class="f-s-24 c-#666">{{ selectDictLabel(pt_seed_type, info?.seedType) }}</span>
                        </view>
                        <view class="pd2-4-0 f-s-28">
                            <span class="c-#666">入库批号：</span>
                            <span class="c-#333 f-w-500">{{ info?.batchCode }}</span>
                        </view>
                        <view v-if="['A3', 'A4'].includes(info?.fungusCodeType)" class="pd2-4-0 f-s-28">
                            <span class="c-#666">菌种/菌株编号：</span>
                            <span class="c-#333 f-w-500">{{ selectDictLabel(pt_fungus_code_type, info?.fungusCodeType) }}/{{ info?.fungusCode }}</span>
                        </view>
                        <view class="pd2-4-0 f-s-28">
                            <span class="c-#666">供应商：</span>
                            <span class="c-#333 f-w-500">{{ info?.supplier }}</span>
                        </view>
                        <view class="pd2-4-0 f-s-28">
                            <span class="c-#666">入库量：</span>
                            <span class="c-#333 f-w-500">{{ info?.capacity }}{{ info?.unit }}</span>
                        </view>
                        <view class="d-flex">
                            <view v-if="info?.restAmount" class="pd2-4-0 f-s-28 flex1">
                                <span class="c-#666">出库量：</span>
                                <span class="c-#333 f-w-500">{{ info?.inputAmount || '0' }}{{ info?.unit }}</span>
                            </view>
                            <view v-if="info?.restAmount" class="pd2-4-0 f-s-28 flex1">
                                <span class="c-primary">剩余量：</span>
                                <span class="c-primary f-w-500">{{ info?.restAmount || '0' }}{{ info?.unit }}</span>
                            </view>
                        </view>
                    </template>
                    <template v-if="info?.stockType === '4'">
                        <view class="d-flex j-sb a-c li-item-head mb-16">
                            <view class="li-left-tag" :class="{ [`bg-${selectDictListClass(pt_seed_instore_type, info?.instoreType)}`]: true }">{{ selectDictLabel(pt_seed_instore_type, info?.instoreType) }}</view>
                            <view class="f-s-22 c-#666">{{ info?.instoreBizInfo?.instoreDate }}</view>
                        </view>
                        <view class="mb-10">
                            <span class="f-s-34 c-#333 f-w-500 mr-10">{{ info?.variety }}</span>
                            <span v-if="info?.partName" class="f-s-24 c-#666">{{ info?.partName }}</span>
                        </view>
                        <view class="pd2-4-0 f-s-28">
                            <span class="c-#666">入库批号：</span>
                            <span class="c-#333 f-w-500">{{ info?.batchCode }}</span>
                        </view>
                        <view v-if="info?.supplierId" class="pd2-4-0 f-s-28">
                            <span class="c-#666">供应商：</span>
                            <span class="c-#333 f-w-500">{{ info?.supplierInfo?.cusName || '-' }}</span>
                        </view>
                        <view v-if="info?.warehouses?.length" class="pd2-4-0 f-s-28">
                            <span class="c-#666">存放库房：</span>
                            <span class="c-#333 f-w-500">{{ getStorageRoomNames(info?.warehouses) || '-' }}</span>
                        </view>
                        <view class="pd2-4-0 f-s-28">
                            <span class="c-#666">入库量：</span>
                            <span class="c-#333 f-w-500">{{ info?.capacity }}{{ info?.unit }}</span>
                        </view>
                        <view class="d-flex">
                            <view v-if="info?.inputAmount" class="pd2-4-0 f-s-28 flex1">
                                <span class="c-#666">出库量：</span>
                                <span class="c-#333 f-w-500">{{ info?.inputAmount || '0' }}{{ info?.unit }}</span>
                            </view>
                            <view v-if="info?.restAmount" class="pd2-4-0 f-s-28 flex1">
                                <span class="c-primary">剩余量：</span>
                                <span class="c-primary f-w-500">{{ info?.restAmount || '0' }}{{ info?.unit }}</span>
                            </view>
                        </view>
                    </template>
                </view>
                <view class="pd3-10-24-24">
                    <!-- 损耗登记日期 -->
                    <!-- 损耗数量 -->
                    <!-- 备注 -->
                    <view class="h-1" id="scrapDatepppp"></view>
                    <ut-datetime-picker v-model="form.scrapDate" :maxDate="new Date()" mode="date">
                        <up-form-item borderBottom label="损耗登记日期" required prop="scrapDate">
                            <up-input v-model="form.scrapDate" 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>
                    <view class="h-1" id="scrapAmountpppp"></view>
                    <up-form-item borderBottom label="损耗数量" required prop="scrapAmount">
                        <up-input v-model="form.scrapAmount" type="number" placeholder="请输入损耗数量" border="none" clearable></up-input>
                        <template #right>
                            <view class="c-#333 f-s-28">{{ info?.unit }}</view>
                        </template>
                    </up-form-item>
                    <view class="h-1" id="remarkpppp"></view>
                    <up-form-item borderBottom label="备注" prop="remark">
                        <up-textarea v-model="form.remark" placeholder="损耗原因等" autoHeight></up-textarea>
                    </up-form-item>
                </view>
                <!-- <view class="h-1" id="contactTelpppp"></view>
                <up-form-item borderBottom label="联系电话" prop="contactTel">
                    <up-input v-model="form.contactTel" placeholder="请输入联系电话" border="none" clearable></up-input>
                </up-form-item> -->
            </view>
        </up-form>
        <template #bottom>
            <view class="pd-20 d-flex">
                <up-button @click="navigateBackOrHome()" class="mr-30" style="color: #333" color="#F2F2F2">取消</up-button>
                <up-button @click="submit" type="primary">确认登记</up-button>
            </view>
        </template>
    </z-paging>
</template>
<script setup lang="ts">
import { getStorageRoomNames } from '@/utils/common';
import { useClientRequest } from '@/utils/request';
import { parseTime, selectDictListClass } from '@/utils/ruoyi';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_material_type, pt_seed_instore_type, pt_seed_type, pt_fungus_code_type } = toRefs<any>(proxy?.useDict('pt_material_type', 'pt_seed_instore_type', 'pt_seed_type', 'pt_fungus_code_type'));
const upFormRef = ref();
const paging = ref();

const form = ref({
    scrapDate: parseTime(new Date(), '{y}-{m}-{d}'),
    scrapAmount: '',
    remark: '',
});
const info = ref<any>(null);

const rules = reactive({
    scrapDate: [{ required: true, message: '请选择损耗登记日期' }],
    scrapAmount: [
        { required: true, message: '请输入损耗数量' },
        {
            validator: (rule: any, value: any) => {
                if (value === undefined || value === null || value === '') return true;
                const amount = Number(value);
                if (Number.isNaN(amount)) return false;
                return amount > 0;
            },
            message: '损耗数量需为大于0的数字',
            trigger: ['blur', 'change'],
        },
        {
            validator: (rule: any, value: any) => {
                if (value === undefined || value === null || value === '') return true;
                const amount = Number(value);
                if (Number.isNaN(amount)) return true;
                const max = Number(info.value?.restAmount ?? 0);
                if (!max) return true;
                return amount <= max;
            },
            message: '损耗数量不能超过剩余量',
            trigger: ['blur', 'change'],
        },
    ],
});

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: '保存中...', mask: true });
        const payload: any = { ...form.value, storageType: info.value?.stockType, targetId: info.value?.id, scrapUnit: info.value?.unit };
        const res = await useClientRequest.post('/plt-api/app/storage/scrap', payload);
        uni.hideLoading();
        if (res && res.code === 200) {
            uni.showToast({ title: '登记成功', icon: 'success' });
            uni.$emit('storage-registered');
            setTimeout(() => uni.navigateBack(), 300);
        }
    } catch (e) {
        uni.hideLoading();
    }
};
onLoad((options: any) => {
    const instance: any = getCurrentInstance()?.proxy;
    const eventChannel = instance?.getOpenerEventChannel();
    eventChannel.on('storage-data', (data: any) => {
        console.log(data);
        info.value = data;
    });
});
</script>
<style lang="scss" scoped>
.startline-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}

.base-bottom-wrap {
    background-color: #fff;
}
.tag-span {
    padding: 4rpx 12rpx;
    font-size: 20rpx;
    border-radius: 18rpx;
}
.li-item-head {
    margin-left: -24rpx;
    margin-top: -24rpx;
}
.li-left-tag {
    padding: 6rpx 16rpx;
    color: #fff;
    border-radius: 0 0 16rpx 0;
    font-size: 20rpx;
    font-weight: 500;
}
</style>
