<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="varietyIdpppp"></view>
                <up-form-item borderBottom label="动植物名称" required prop="varietyId">
                    <view class="flex1">
                        <up-button v-if="!form.varietyId" @click="selectVarietyId" type="primary" plain>
                            <image class="w-36 h-36 mr-10" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/common/select_push_icon.png" mode="widthFix" />
                            <span>请选择动植物名称</span>
                        </up-button>
                        <view v-else class="bg-#FBFDFB card-info-block pd-24 p-rtv">
                            <view class="mb-16">
                                <span class="f-s-34 c-#333 f-w-5 mr-16">{{ form?.varietyInfo?.varietyName }}</span>
                                <span class="f-s-24 c-#666">{{ form?.varietyInfo?.latinName }}</span>
                            </view>
                            <view class="mb-16">
                                <span class="f-s-28 c-#333 f-w-5 mr-16">{{ form?.varietyInfo?.genusName }}</span>
                                <span class="f-s-24 c-#666">{{ form?.varietyInfo?.genusLatinName }}</span>
                            </view>
                            <view class="f-s-24 c-#666">产出：{{ form?.varietyInfo?.medicineName }}</view>
                            <view
                                class="close-icon pd-16"
                                @click="
                                    form.varietyId = '';
                                    form.varietyInfo = null;
                                "
                            >
                                <up-icon color="#F81242" name="close" size="32rpx"></up-icon>
                            </view>
                        </view>
                    </view>
                </up-form-item>
                <view class="h-1" id="partpppp"></view>
                <SelectMedicinalPart v-model="form.part" v-model:value-name="form.partName">
                    <up-form-item borderBottom label="药用部位/对象" prop="part" required>
                        <up-input v-model="form.partName" placeholder="请选择药用部位/对象" border="none" readonly clearable></up-input>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>
                </SelectMedicinalPart>

                <view class="h-1" id="sourceTypepppp"></view>
                <ut-action-sheet :tabs="pt_medicine_source" 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_medicine_source, 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>
                <!-- 入库数量与单位 -->
                <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_medicine_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_medicine_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>

                <template v-if="['2'].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="examinReport">
                    <ut-upload v-model="form.examinReport" :max-count="50" valueType="array" accept="image,file"></ut-upload>
                </up-form-item>
                <!-- 鲜货产地 -->
                <PickerAreaInput v-model="form.producePlace" v-model:full-name="form.producePlaceName" title="选择鲜货产地">
                    <view class="h-1" id="producePlacepppp"></view>
                    <up-form-item borderBottom label="鲜货产地" prop="producePlace" required>
                        <view v-if="form.producePlace" class="f-s-30 c-333 f-w-5 flex1">{{ form.producePlaceName }}</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>
                </PickerAreaInput>
                <view class="h-1" id="productDatepppp"></view>
                <view class="h-1" id="productDateEndpppp"></view>
                <up-form-item prop="productDate" required label="采收日期" class="form-item-bottom-padding-0">
                    <view class="flex1 d-flex">
                        <view class="flex1">
                            <ut-datetime-picker v-model="form.productDate" :maxDate="form.productDateEnd || new Date()" mode="date">
                                <up-form-item borderBottom prop="productDate" class="form-item-top-padding-0">
                                    <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>
                        </view>
                        <view class="pd2-0-20"></view>
                        <view class="flex1">
                            <ut-datetime-picker v-model="form.productDateEnd" :minDate="form.productDate" :maxDate="new Date()" mode="date">
                                <up-form-item borderBottom prop="productDateEnd" class="form-item-top-padding-0">
                                    <up-input v-model="form.productDateEnd" 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>
                    </view>
                </up-form-item>

                <!-- 媒体与附件 -->
                <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>
        </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 { FreshGoodsInstoreItemForm } from '../models/type';
import ContactUnitInput from '@/models/contact-unit-input/contact-unit-input.vue';
import PickerAreaInput from '@/models/picker-area-input/picker-area-input.vue';
import SelectMedicinalPart from '@/models/select-medicinal-part/select-medicinal-part.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_medicine_source, pt_medicine_unit, yes_no } = toRefs<any>(proxy?.useDict('pt_medicine_source', 'pt_medicine_unit', 'yes_no'));
const paging = ref<any>(null);
const upFormRef = ref<any>(null);

const createDefaultForm = (): FreshGoodsInstoreItemForm => ({
    uid: '',
    varietyId: '',
    varietyInfo: null,
    part: '',
    partName: '',
    sourceType: '',
    capacity: '',
    unit: '',
    supplierId: undefined,
    supplierProducerFlag: '',
    producer: '',
    examinReport: [],
    producePlace: '',
    producePlaceName: '',
    productDate: '',
    imgs: '',
    vedios: '',
    productDateEnd: '',
});

const form = ref<FreshGoodsInstoreItemForm>(createDefaultForm());

const rules = reactive({
    varietyId: [{ required: true, message: '请选择动植物名称' }],
    part: [{ required: true, message: '请选择药用部位/对象' }],
    sourceType: [{ required: true, message: '请选择鲜货来源' }],
    capacity: [
        { required: true, message: '请输入入库量' },
        {
            asyncValidator: (rule: any, value: any) => {
                if (value === 0 || value === '0') return Promise.reject('入库量需大于0');
                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();
            },
        },
    ],
    unit: [{ required: true, message: '请选择单位' }],
    supplierId: [
        {
            asyncValidator: (rule: any, value: any) => {
                if (['2'].includes(form.value.sourceType as string)) {
                    if (!value) return Promise.reject('请选择供应商');
                }
                return Promise.resolve();
            },
        },
    ],
    producePlace: [{ required: true, message: '请选择鲜货产地' }],
    productDate: [{ required: true, message: '请选择开始日期' }],
    productDateEnd: [{ 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.$emit('submitForm', {
                ...optionsParam.value,
                form: { ...form.value, uid: optionsParam.value?.uid || '' },
            });
            uni.navigateBack({
                delta: 1,
            });
            try {
            } catch (error) {
                uni.hideLoading();
            }
        },
        500,
        true,
    );
};
// 去选择动植物名称
const selectVarietyId = () => {
    uni.$once('updateBiologicalname', function (data) {
        form.value.varietyId = data.msg.id;
        form.value.varietyInfo = data.msg;
    });
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/por-torganism/index',
        params: {
            title: '选择动植物名称',
        },
    });
};
const changeSupplierProducerFlag = (value: string) => {
    if (value === '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 = {
            ...createDefaultForm(),
            ...data?.form,
            uid: data?.uid || data?.form?.uid || '',
        };
    });
});
</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>
