<template>
    <z-paging class="" ref="paging" bgColor="#fff" paging-class="paging-btm-shadow" safe-area-inset-bottom scroll-with-animation>
        <template #top>
            <ut-navbar :title="optionsParam?.mode == 'edit' ? '编辑农资入库信息' : '添加农资入库信息'" :fixed="false" border></ut-navbar>
        </template>
        <view class="pd-24">
            <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
                <!-- 基本信息 -->
                <view class="h-1" id="materialNamepppp"></view>
                <up-form-item borderBottom label="产品名称" prop="materialName" required>
                    <up-input v-model="form.materialName" placeholder="请输入产品名称" border="none" clearable></up-input>
                </up-form-item>
                <view class="h-1" id="materialTypepppp"></view>
                <ut-action-sheet :tabs="pt_material_type" mode="custom" title="农资类别" v-model="form.materialType">
                    <up-form-item borderBottom label="农资类别" required prop="materialType">
                        <view v-if="form.materialType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_material_type, form.materialType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择农资类别</view>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>
                </ut-action-sheet>

                <!-- 入库数量与单位 -->
                <view class="h-1" id="capacitypppp"></view>
                <view class="h-1" id="unitpppp"></view>
                <up-form-item label="入库量" 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="min-w-200">
                            <ut-action-sheet v-model="form.unit" :tabs="pt_materail_unit" mode="custom" title="选择单位">
                                <up-form-item prop="unit" border-bottom class="form-item-top-padding-0">
                                    <view class="flex1" style="line-height: 24px">
                                        <view v-if="form.unit" class="f-s-30 c-333 f-w-5 text-center">{{ selectDictLabel(pt_materail_unit, form.unit) }}</view>
                                        <view v-else class="f-s-30 c-ccc f-w-4 text-center">单位</view>
                                    </view>
                                    <template #right>
                                        <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                                    </template>
                                </up-form-item>
                            </ut-action-sheet>
                        </div>
                    </div>
                </up-form-item>
                <view class="h-1" id="specpppp"></view>
                <view class="h-1" id="specUnitpppp"></view>
                <template v-if="!['kg', 'L'].includes(form?.unit as string)">
                    <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="spec" border-bottom class="form-item-top-padding-0">
                                    <up-input v-model="form.spec" placeholder="请输入规格" border="none" clearable></up-input>
                                </up-form-item>
                            </div>
                            <div class="pd-5"></div>
                            <div class="min-w-200">
                                <ut-action-sheet v-model="form.specUnit" :tabs="pt_materail_spec_unit" mode="custom" title="选择单位">
                                    <up-form-item prop="specUnit" border-bottom class="form-item-top-padding-0">
                                        <view class="flex1" style="line-height: 24px">
                                            <view v-if="form.specUnit" class="f-s-30 c-333 f-w-5 text-center">{{ selectDictLabel(pt_materail_spec_unit, form.specUnit) }}</view>
                                            <view v-else class="f-s-30 c-ccc f-w-4 text-center">单位</view>
                                        </view>
                                        <template #right>
                                            <up-icon class="mr-10" size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                                        </template>
                                    </up-form-item>
                                </ut-action-sheet>
                            </div>
                            <div class="pd2-0-10 c-#ccc">/</div>
                            <div class="min-w-200">
                                <up-form-item prop="unit" border-bottom class="form-item-top-padding-0">
                                    <view class="flex1" style="line-height: 24px">
                                        <view v-if="form.unit" class="f-s-30 c-333 f-w-5 text-center">{{ selectDictLabel(pt_materail_unit, form.unit) }}</view>
                                        <view v-else class="f-s-30 c-ccc f-w-4 text-center">单位</view>
                                    </view>
                                    <template #right>
                                        <up-icon size="22rpx" color="#fff" name="arrow-down-fill"></up-icon>
                                    </template>
                                </up-form-item>
                            </div>
                        </div>
                    </up-form-item>
                </template>

                <view class="h-1" id="sourceTypepppp"></view>
                <ut-action-sheet :tabs="pt_source_type" mode="custom" title="农资来源" v-model="form.sourceType">
                    <up-form-item borderBottom label="农资来源" required prop="sourceType">
                        <view v-if="form.sourceType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_source_type, form.sourceType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择农资来源</view>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>
                </ut-action-sheet>
                <template v-if="['1'].includes(form.sourceType as string)">
                    <up-form-item borderBottom label="供应商" prop="supplierId" required>
                        <view class="flex1">
                            <ContactUnitInput v-model="form.supplierId" v-model:info="form.supplierInfo" :params="{ cpyType: '4' }" title="选择供应商" placeholder="请选择供应商信息"></ContactUnitInput>
                        </view>
                    </up-form-item>
                    <up-form-item borderBottom label="供应商是否是生产商" prop="supplierProducerFlag">
                        <up-radio-group v-model="form.supplierProducerFlag" @change="changeSupplierProducerFlag">
                            <up-radio :customStyle="{ marginRight: '60rpx' }" v-for="(item, index) in yes_no" :key="index" :label="item.label" :name="item.value"></up-radio>
                        </up-radio-group>
                    </up-form-item>
                    <up-form-item borderBottom label="生产商" prop="producer">
                        <up-input v-model="form.producer" placeholder="请输入生产商名称" border="none" clearable></up-input>
                    </up-form-item>
                </template>
                <up-form-item borderBottom label="生产批号" prop="productCode">
                    <up-input v-model="form.productCode" placeholder="请输入生产批号" border="none" clearable></up-input>
                </up-form-item>
                <ut-datetime-picker v-model="form.productDate" :maxDate="new Date()" mode="date">
                    <up-form-item borderBottom label="生产日期" prop="productDate">
                        <up-input v-model="form.productDate" 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="品牌" prop="brand">
                    <up-input v-model="form.brand" placeholder="请输入品牌" border="none" clearable></up-input>
                </up-form-item>
                <!-- 登记证号 肥料和农药才有登记证号 -->
                <template v-if="['1', '2'].includes(form.materialType as string)">
                    <up-form-item borderBottom label="登记证号" prop="materialCode">
                        <up-input v-model="form.materialCode" placeholder="请输入登记证号" border="none" clearable></up-input>
                    </up-form-item>
                </template>
                <!-- 媒体与附件 -->
                <up-form-item borderBottom label="农资图片" prop="imgs">
                    <ut-upload v-model="form.imgs" :max-count="9" valueType="string"></ut-upload>
                </up-form-item>
                <up-form-item borderBottom label="农资视频" prop="vedios">
                    <ut-upload v-model="form.vedios" :max-count="3" accept="video" valueType="string"></ut-upload>
                </up-form-item>
                <!-- 检验报告 -->
                <up-form-item borderBottom label="检验报告" prop="examinReport">
                    <ut-upload v-model="form.examinReport" :max-count="50" valueType="array" accept="image,file"></ut-upload>
                </up-form-item>
            </up-form>
        </view>
        <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 { AgroProductInstoreType } from '../models/type';
import ContactUnitInput from '@/models/contact-unit-input/contact-unit-input.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_material_type, pt_source_type, pt_materail_unit, pt_materail_spec_unit, yes_no } = toRefs<any>(proxy?.useDict('pt_material_type', 'pt_source_type', 'pt_materail_unit', 'pt_materail_spec_unit', 'yes_no'));
const paging = ref<any>(null);
const upFormRef = ref<any>(null);
// 农资入库单明细表单
const form = ref<AgroProductInstoreType>({
    materialName: '',
    materialType: '',
    capacity: '',
    unit: '',
    spec: '',
    specUnit: '',
    sourceType: '',
    supplierId: undefined,
    supplierInfo: undefined,
    supplierProducerFlag: '',
    producer: '',
    productCode: '',
    productDate: '',
    brand: '',
    materialCode: '',
    imgs: undefined,
    vedios: undefined,
    examinReport: [],
});
// 表单校验规则：以 template 中 required 与业务条件为准
const rules = reactive({
    materialName: [{ required: true, message: '请输入产品名称' }],
    materialType: [{ required: true, message: '请选择农资类别' }],
    capacity: [{ required: true, message: '请输入入库量' }],
    unit: [{ required: true, message: '请选择单位' }],
    sourceType: [{ required: true, message: '请选择农资来源' }],
    // 规格与规格单位仅在单位为 kg/L 时必填
    spec: [
        {
            asyncValidator: (rule: any, value: any) => {
                if (!['kg', 'L'].includes(form.value.unit as string) && !value) {
                    return Promise.reject('请输入规格');
                }
                return Promise.resolve();
            },
        },
    ],
    specUnit: [
        {
            asyncValidator: (rule: any, value: any) => {
                if (!['kg', 'L'].includes(form.value.unit as string) && !value) {
                    return Promise.reject('请选择规格单位');
                }
                return Promise.resolve();
            },
        },
    ],
    // 供应商仅在来源为“采购”等特定来源时必选（目前为来源=1）
    supplierId: [
        {
            asyncValidator: (rule: any, value: any) => {
                if (['1'].includes(form.value.sourceType as string) && !value) {
                    return Promise.reject('请选择供应商');
                }
                return Promise.resolve();
            },
        },
    ],
});
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.$emit('submitForm', {
                ...optionsParam.value,
                form: { ...form.value, uid: optionsParam.value?.uid || '' },
            });
            uni.navigateBack({
                delta: 1,
            });
            try {
            } catch (error) {
                uni.hideLoading();
            }
        },
        500,
        true,
    );
};
const changeSupplierProducerFlag = () => {
    if (form.value.supplierProducerFlag === '1') {
        form.value.producer = form.value.supplierInfo?.cusName || '';
    } else {
        form.value.producer = '';
    }
};
const optionsParam = ref({} as any);
onLoad((options: any) => {
    const instance: any = getCurrentInstance()?.proxy;
    const eventChannel = instance?.getOpenerEventChannel();
    eventChannel.on('optionsParam', (data: any) => {
        console.log(data);
        optionsParam.value = {
            uid: data?.uid || '',
            mode: data?.mode || 'add',
        };
        form.value = {
            ...form.value,
            ...data?.form,
        };
    });
});
</script>
<style lang="scss" scoped>
.card-info-block {
    border: 1rpx solid #afddbb;
    border-radius: 10rpx;
}

.close-icon {
    position: absolute;
    top: 0rpx;
    right: 0rpx;
}

:deep(.form-item-top-padding-0) {
    > .u-form-item__body {
        padding-top: 0rpx;
    }
}

:deep(.form-item-bottom-padding-0) {
    > .u-form-item__body {
        padding-bottom: 0rpx;
    }
}
</style>
