<template>
    <z-paging ref="paging" v-model="list" bgColor="#f7f7f7" @query="query" safe-area-inset-bottom>
        <template #top>
            <ut-navbar title="新增采收入库" :fixed="false"> </ut-navbar>
        </template>
        <view class="pt-24">
            <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
                <view class="bg-#fff pd-24 mb-20">
                    <up-form-item borderBottom label="动植物名称">
                        <view class="w-100%">
                            <view class="f-s-24 c-#999 mb-20">此为种养殖的动植物品种，无法更改</view>
                            <view class="pd-24 d-flex flex-cln bg-#FBFDFB border-#37A954 b-radius p-rtv">
                                <view class="mb-20">
                                    <text class="c-#333 f-s-34 f-w-5 mr-5">{{ plantDate?.varietyName }}</text>
                                    <text class="c-#666 f-s-24">{{ plantDate?.latinName }}</text>
                                </view>
                                <view>
                                    <text class="c-#333 f-s-28 f-w-5 mr-5">{{ plantDate?.genusName }}</text>
                                    <text class="c-#666 f-s-24">{{ plantDate?.genusLatinName }}</text>
                                </view>
                            </view>
                        </view>
                    </up-form-item>
                    <!-- 采收类型 -->
                    <view class="h-1" id="outputTypepppp"></view>
                    <template v-if="+taskType == 11 || +taskType == 21 || changeRevisions">
                        <up-form-item borderBottom label="采收类型" required prop="outputType">
                            <view v-if="form?.outputType" class="f-s-30 c-#999 f-w-5 flex1">{{ selectDictLabel(pt_output_type, form?.outputType) }}</view>
                        </up-form-item>
                    </template>
                    <template v-else>
                        <ut-action-sheet v-model="form.outputType" :tabs="pt_output_type" title="选择采收类型">
                            <up-form-item borderBottom label="采收类型" required prop="outputType">
                                <view v-if="form?.outputType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_output_type, form?.outputType) }}</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>
                    <!-- 种源类型 -->
                    <template v-if="+form?.outputType == 1">
                        <ut-action-sheet v-model="form.seedType" :tabs="pt_seed_type" title="选择种源类型" mode="custom">
                            <up-form-item borderBottom label="种源类型" required prop="seedType" id="seedTypepppp">
                                <view v-if="form.seedType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_seed_type, form?.seedType) }}</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>
                        <!-- 菌种/菌株编号 -->
                        <!-- <up-form-item v-if="form?.seedType == 'A4' || form?.seedType == 'A8'" borderBottom label="菌种/菌株编号" required prop="fungusCode" id="fungusCodeppppp">
                            <up-input v-model="form.fungusCode" placeholder="请输入菌种/菌株编号" border="none"></up-input>
                        </up-form-item> -->
                        <up-form-item required v-if="['A4', 'A8'].includes(form.seedType as string)" :label="`${selectDictLabel(pt_seed_type, form.seedType as string)}编号`" class="form-item-bottom-padding-0">
                            <view class="d-flex flex1">
                                <view class="flex1">
                                    <ut-action-sheet v-model="form.fungusCodeType" :tabs="pt_fungus_code_type" mode="custom" title="选择单位">
                                        <up-form-item prop="fungusCodeType" border-bottom class="form-item-top-padding-0">
                                            <view class="flex1" style="line-height: 24px">
                                                <view v-if="form.fungusCodeType" class="f-s-30 c-333 f-w-5">{{ selectDictLabel(pt_fungus_code_type, form.fungusCodeType) }}</view>
                                                <view v-else class="f-s-30 c-ccc f-w-4">选择编号类型</view>
                                            </view>
                                            <template #right>
                                                <up-icon class="pr-20" size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                                            </template>
                                        </up-form-item>
                                    </ut-action-sheet>
                                </view>
                                <view class="pd-5"></view>
                                <view class="flex1">
                                    <up-form-item prop="fungusCode" border-bottom class="form-item-top-padding-0">
                                        <up-input v-model="form.fungusCode" placeholder="输入数字小数点" border="none" clearable></up-input>
                                    </up-form-item>
                                </view>
                            </view>
                        </up-form-item>
                    </template>
                    <!-- 采收日期 -->
                    <up-form-item :borderBottom="false" label="采收日期" required>
                        <up-form-item :borderBottom="false" prop="harvestDate" id="harvestDatepppp">
                            <ut-datetime-picker v-model="form.harvestDate" mode="date" dateFields="day" @change="changeStartTime">
                                <view class="d-flex mr-20">
                                    <up-input v-model="form.harvestDate" placeholder="请选择采收开始时间" border="bottom" :customStyle="{ paddingLeft: '0rpx' }"></up-input>
                                    <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill" style="margin-left: -20rpx"></up-icon>
                                </view>
                            </ut-datetime-picker>
                        </up-form-item>
                        <up-form-item :borderBottom="false" prop="harvestDateEnd" id="harvestDateEndpppp">
                            <ut-datetime-picker v-model="form.harvestDateEnd" mode="date" dateFields="day">
                                <view class="d-flex">
                                    <up-input v-model="form.harvestDateEnd" placeholder="请选择采收结束时间" border="bottom" :customStyle="{ paddingLeft: '0rpx' }"></up-input>
                                    <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill" style="margin-left: -20rpx"></up-icon>
                                </view>
                            </ut-datetime-picker>
                        </up-form-item>
                    </up-form-item>
                    <!-- 采收部位 -->
                    <up-form-item v-if="+form?.outputType == 2" borderBottom label="药用部位/对象" prop="harvestPart" required>
                        <SelectMedicinalPart v-model="form.harvestPart" v-model:value-name="form.harvestPartName" title="选择采收部位">
                            <up-input v-model="form.harvestPartName" placeholder="请选择药用部位/对象" border="none" readonly clearable></up-input>
                        </SelectMedicinalPart>
                    </up-form-item>
                    <!-- 采收批号 -->
                    <up-form-item borderBottom label="采收批号" required prop="harvestCode" id="harvestCodepppp">
                        <view class="d-flex a-c j-sb w-100%">
                            <view class="flex1 d-flex">
                                <up-input v-model="form.harvestCode" placeholder="请输入采收批号" border="none" clearable></up-input>
                                <up-button @click="randomCode" class="c-#fff" type="primary" style="height: 50rpx; width: 130rpx">随机生成</up-button>
                            </view>
                        </view>
                    </up-form-item>
                    <!-- 采收量 -->
                    <up-form-item label="采收量" required class="form-item-bottom-padding-0">
                        <div class="flex1 d-flex">
                            <div class="flex1 ov-hd" id="quantitypppp">
                                <up-form-item prop="quantity" border-bottom class="form-item-top-padding-0">
                                    <up-input v-model="form.quantity" placeholder="请输入采收量" border="none" clearable></up-input>
                                </up-form-item>
                            </div>
                            <div class="pd-5" id="unitpppp"></div>
                            <div class="min-w-200">
                                <ut-action-sheet v-model="form.unit" :tabs="pt_seed_unit" 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_seed_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>
                    <!-- 采收负责人 -->
                    <up-form-item borderBottom label="采收负责人" required prop="mgrName" id="mgr_namepppp">
                        <view class="d-flex a-c j-sb w-100%">
                            <up-input style="padding-left: 0" v-model="form.mgrName" placeholder="请输入采收负责人" border="none"></up-input>
                        </view>
                    </up-form-item>
                    <!-- 采收方式 -->
                    <ut-action-sheet v-model="form.harvestType" :tabs="pt_harvest_type" title="选择采收方式">
                        <up-form-item borderBottom label="采收方式" prop="harvestType" id="harvestTypepppp">
                            <view v-if="form.harvestType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_harvest_type, form.harvestType) }}</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>
                    <!-- 采收地块 -->
                    <up-form-item v-if="+mgMethod !== 2" :borderBottom="false" :label="'采收' + landIdsTitle" prop="landIds" id="landIdspppp">
                        <Go_button v-if="!deawerData?.data.length" @click="openDrawer" :title="'请选择采收的' + landIdsTitle" style="flex: 1" />
                        <view class="w-100%" v-else>
                            <Baseinfo :modeValue="deawerData" @close="handleBaseinfoClose" :baseType="baseType" />
                        </view>
                    </up-form-item>
                    <up-form-item v-else :borderBottom="false" :label="'采收' + landIdsTitle" prop="animalIds" id="animalIdspppp">
                        <view class="flex1">
                            <Individualinfo v-if="individualLandIds?.checkBox?.length > 0" v-model="individualLandIds" v-model:landIds="form.animalIds" />
                            <Go_button @click="goIndividual()" :title="'请选择采收的' + landIdsTitle" style="flex: 1" />
                        </view>
                    </up-form-item>
                    <up-form-item label="过程图片" prop="imgs" borderBottom id="imgspppp">
                        <ut-upload v-model="form.imgs" :max-count="9" accept="image"></ut-upload>
                    </up-form-item>
                    <up-form-item label="过程视频" prop="videos" borderBottom id="videospppp">
                        <ut-upload v-model="form.videos" :max-count="9" accept="video"></ut-upload>
                    </up-form-item>
                    <up-form-item v-if="+form.outputType == 1" label="种源加工处理工艺" prop="ptech" borderBottom id="ptechpppp">
                        <view class="w-100%">
                            <view v-if="form?.ptech?.length !== 0" class="pd-24 d-flex flex-cln bg-#FBFDFB border-#37A954 b-radius p-rtv mb-20">
                                <view class="">
                                    <template v-for="(item, index) in form?.ptech?.split(',')" :key="index">
                                        <span v-if="index !== 0" class="c-#999 f-s-32 ml-10 mr-10">→ </span>
                                        <span class="f-s-32">{{ item }}</span>
                                    </template>
                                </view>
                                <view class="d-flex">
                                    <view class="flex1"></view>
                                    <up-button type="primary" @click="goPtech" style="width: 130rpx; height: 60rpx; border-radius: 10rpx">选择工艺</up-button>
                                </view>
                            </view>
                            <Go_button v-else @click="goPtech" title="请选择种源加工处理工艺" style="flex: 1" />
                        </view>
                    </up-form-item>
                    <up-form-item label="存放库房类型" borderBottom>
                        <view class="d-flex a-c j-sb w-100%">
                            <view v-if="form.outputType" class="f-s-30 c-#999 f-w-5 flex1">{{ selectDictLabel(pt_output_type, form.outputType) }}</view>
                        </view>
                    </up-form-item>
                </view>
            </up-form>
        </view>
        <template #bottom>
            <view class="pd-24 d-flex j-c gap-20 base-bottom-wrap">
                <up-button v-if="changeRevisions" type="primary" @click="change()">确认修改</up-button>
                <up-button v-else type="primary" @click="save()">确认添加</up-button>
            </view>
        </template>
    </z-paging>
    <Drawer v-if="drawerVisible" :baseType="baseType" v-model="drawerVisible" @confirm="onDrawerConfirm" />
    <up-popup :show="showptech" mode="center" @close="showptech = false" @open="showptech = true" closeable>
        <view style="width: 80vw">
            <view class="pd-24">
                <view class="f-s-32 c-#333 f-w-5">请选择种源加工处理工艺</view>
            </view>
            <view class="pd-24" v-if="form?.ptech?.length">
                <view class="c-#999 f-s-26 f-w-5 pb-10">已选择工艺步骤</view>
                <view class="d-flex flex-wrap pd-24 a-c gap-10 border-#37A954 b-radius">
                    <template v-for="(item, index) in form?.ptech?.split(',')" :key="index">
                        <image v-if="index !== 0" src="@/static/images/common/craftArrow.png" class="mr-10 ml-10" style="width: 44rpx; height: 44rpx"> </image>
                        <view class="p-rtv">
                            <up-icon color="red" name="close-circle-fill" @click="removePtech(index)" style="position: absolute; right: -10rpx; top: -10rpx"></up-icon>
                            <view class="pd-16 bg-#37A9541A c-primary b-radius mb-10"> {{ item }}</view>
                        </view>
                    </template>
                </view>
            </view>
            <view class="pd-24 pb-0 c-#999 f-s-26 f-w-5">快捷选择加工工艺</view>
            <template v-if="ptechData?.length == 0">
                <ut-empty class="mg-at" color="#ccc" size="28rpx">暂未配置种源加工工艺，</ut-empty>
                <view class="d-flex j-c c-#ccc f-s-28">请前往 <span class="c-primary">更多-加工工艺字典</span>进行配置,</view>
                <view class="d-flex j-c c-#ccc f-s-28">配置后再来选择</view>
            </template>
            <template v-else>
                <scroll-view class="h-400" scroll-y>
                    <view class="d-flex j-sb flex-wrap pd-24 pb-0">
                        <view v-for="(item, idnex) in ptechData" :key="idnex" class="bg-#f7f7f7 c-#333 radius-10 pd4-16-24-16-24 mb-16" @click="addPtech(item)">
                            {{ item }}
                        </view>
                    </view>
                </scroll-view>
            </template>
        </view>
        <view class="gap-20 d-flex pd-24">
            <up-button @click="emptyPtech" color="#F2F2F2" style="color: #333">清空重选</up-button>
            <up-button type="primary" @click="changePtech">确认选择</up-button>
        </view>
    </up-popup>
</template>
<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance, type ComponentInternalInstance } from 'vue';
import { useClientRequest } from '@/utils/request';
import { useInfoStore } from '@/store';
import Go_button from './models/go_button.vue';
import Baseinfo from './models/baseinfo.vue';
import Drawer from './models/drawer.vue';
import Individualinfo from './models/individualinfo.vue';
import SelectMedicinalPart from '@/models/select-medicinal-part/select-medicinal-part.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_output_type, pt_seed_type, pt_seed_unit, pt_harvest_type, pt_fungus_code_type } = toRefs<any>(proxy?.useDict('pt_output_type', 'pt_seed_type', 'pt_seed_unit', 'pt_harvest_type', 'pt_fungus_code_type'));
const deawerData = ref();
const infoStore = useInfoStore();
const pageTitle = ref('新增采收入库');
// 表单数据
const form = ref({
    taskId: '',
    // 管理类型 - 采收入库
    activityType: '3',
    // 采收类型
    outputType: '',
    // 种源类型
    seedType: '',
    // 菌种/菌株编号
    fungusCode: '',
    // 采收开始时间
    harvestDate: '',
    // 采收结束时间
    harvestDateEnd: '',
    // 采收批号
    harvestCode: '',
    // 采收量
    quantity: '',
    // 采收单位
    unit: '',
    // 采收负责人
    mgrName: infoStore.userInfo?.name || '',
    // 采收方式
    harvestType: '',
    // 操作地块
    landIds: [] as any[],
    // 操作个体
    animalIds: [] as any[],
    // 过程图片
    imgs: null as string | null,
    // 过程视频
    videos: null as string | null,
    ptech: '' as string,
    landFlag: null as string | null,
    //采收部位
    harvestPart: null as string | any,
    //采收部位名称
    harvestPartName: null as string | any,
    fungusCodeType: null as string | any,
});
const baseType = ref();
// 自定义校验函数 - 采收量必须大于0
const validateHarvestAmount = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请输入采收量'));
        return;
    }

    const amount = Number(value);
    if (isNaN(amount) || amount <= 0) {
        callback(new Error('采收量必须大于0'));
        return;
    }

    callback();
};

// 自定义校验函数 - 采收结束时间不能早于开始时间
const validateHarvestDate = (rule: any, value: any, callback: any) => {
    if (!form.value.harvestDate || !form.value.harvestDateEnd) {
        callback();
        return;
    }

    const startDate = new Date(form.value.harvestDate);
    const endDate = new Date(form.value.harvestDateEnd);

    if (endDate < startDate) {
        callback(new Error('采收结束时间不能早于开始时间'));
        return;
    }

    callback();
};

// 自定义校验函数 - 采收批号格式
const validatePlantationCode = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请生成采收批号'));
        return;
    }

    // 简单的批号格式校验：至少包含字母和数字
    if (!/^[A-Za-z0-9_-]+$/.test(value)) {
        callback(new Error('采收批号格式不正确，只能包含字母、数字、下划线和横线'));
        return;
    }

    callback();
};

// 表单验证规则
const rules = reactive({
    outputType: [{ required: true, message: '请选择采收类型' }],
    seedType: [{ required: !!(form?.value?.outputType == '1'), message: '请选择种源类型' }],
    fungusCode: [{ required: !!(form?.value?.seedType == 'A4' || form?.value?.seedType == 'A8'), message: '请输入菌种/菌株编号' }],
    fungusCodeType: [{ required: !!(form?.value?.seedType == 'A4' || form?.value?.seedType == 'A8'), message: '请选择菌种/菌株编号类型' }],
    harvestDate: [{ required: true, message: '请选择采收开始时间' }],
    harvestDateEnd: [
        { required: true, message: '请选择采收结束时间' },
        { validator: validateHarvestDate, trigger: 'blur' },
    ],
    harvestPart: [{ required: !!(form?.value?.outputType == '2'), message: '请选择采收部位' }],
    harvestCode: [
        { required: true, message: '请生成采收批号' },
        { validator: validatePlantationCode, trigger: 'blur' },
    ],
    quantity: [
        { required: true, message: '请输入采收量' },
        { validator: validateHarvestAmount, trigger: 'blur' },
    ],
    unit: [{ required: true, message: '请选择单位' }],
    mgrName: [{ required: true, message: '请输入采收负责人' }],
    harvestType: [{ required: false, message: '请选择采收方式' }],
    landIds: [{ required: false, message: '请选择采收地块' }],
});

const paging = ref();
const list = ref();
const upFormRef = ref<any>();

const query = async (pageNo: number, pageSize: number) => {
    // 这里可以根据需要实现分页查询
    const res = await useClientRequest.get('/plt-api/app/plantationTask/list', {
        pageNo,
        pageSize,
    });
    // return res.data;
};

// 处理开始时间变化
const changeStartTime = (value: string) => {
    form.value.harvestDate = value;
    // 如果结束时间早于开始时间，清空结束时间
    if (form.value.harvestDateEnd && new Date(form.value.harvestDateEnd) < new Date(value)) {
        form.value.harvestDateEnd = '';
    }
};

// 控制抽屉显示状态
const drawerVisible = ref(false);

// 打开抽屉
function openDrawer() {
    drawerVisible.value = true;
}
//去选择个体
const goIndividual = () => {
    uni.$once('updateIndividual', function (data) {
        let flag = false;
        console.log('选择个体', data);
        console.log(individualLandIds.value, '12312');

        data?.checkBox.forEach((item: any) => {
            //判断有没有重复的值，如果有这个就不添加，没有就添加
            if (individualLandIds.value.checkBox.some((item2: any) => item2 === item)) {
                flag = true;
            } else {
                individualLandIds.value.checkBox.push(item);
                form.value.animalIds.push(item);
            }
        });
        if (flag) {
            uni.showToast({
                title: '有重复的个体，已经帮您过滤的',
                icon: 'none',
            });
        }
        paging.value?.scrollIntoViewById('selectanimalId', 30, true);
    });
    uni.$u.route({ type: 'navigateTo', url: '/tools/supervise-individual/index', params: { taskId: form.value.taskId } });
};

// 处理地块选择关闭
const handleBaseinfoClose = () => {
    deawerData.value = null;
    form.value.landIds = [];
};

// 提交表单
const save = () => {
    uni.$u.debounce(
        async () => {
            try {
                console.log('开始提交采收入库记录');
                await upFormRef.value?.validate();
                console.log('校验完成');
                const params = {
                    ...form.value,
                    landFlag: deawerData?.value?.aloneChecked ? '1' : '0',
                };
                console.log('提交参数:', params);
                // 这里需要根据实际 API 进行调整
                const res = await useClientRequest.post('/plt-api/app/harvestRecord/save', params);
                if (res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    setTimeout(() => {
                        // 发送更新事件
                        uni.$emit('updateharvestlist');
                        uni.navigateBack({
                            delta: 1,
                        });
                    }, 1000);
                }
            } catch (error: any) {
                console.log('表单验证错误:', error);
                // 滚动到第一个错误字段
                if (error && error[0]?.field) {
                    const firstErrorField = error[0].field + 'pppp';
                    paging.value?.scrollIntoViewById(firstErrorField, 30, true);
                }
                return;
            }
        },
        1000,
        true,
    );
};

const change = () => {
    uni.$u.debounce(
        async () => {
            try {
                console.log('开始提交采收入库记录');
                await upFormRef.value?.validate();
                console.log('校验完成');
                const params = {
                    ...form.value,
                    landFlag: deawerData?.value?.aloneChecked ? '1' : '0',
                };

                console.log('提交参数:', params);

                // 这里需要根据实际 API 进行调整
                const res = await useClientRequest.post('/plt-api/app/harvestRecord/update', params);
                if (res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    setTimeout(() => {
                        // 发送更新事件
                        uni.$emit('updateharvestdetail');
                        uni.navigateBack({
                            delta: 1,
                        });
                    }, 1000);
                }
            } catch (error: any) {
                console.log('表单验证错误:', error);
                // 滚动到第一个错误字段
                if (error && error[0]?.field) {
                    const firstErrorField = error[0].field + 'pppp';
                    paging.value?.scrollIntoViewById(firstErrorField, 30, true);
                }
                return;
            }
        },
        1000,
        true,
    );
};
// 处理抽屉确认事件
function onDrawerConfirm(data: any) {
    console.log('收到基地选择数据:', data);
    deawerData.value = data;
    form.value.landIds = data?.checkBox;
}
const randomCode = async () => {
    let plType = '';
    if (+taskType.value === 1) {
        plType = 'P';
    } else if (+taskType.value === 2) {
        plType = 'F';
    } else {
        plType = 'C';
    }
    const code = await useClientRequest.post('/plt-api/app/plantationTask/getBatchCode', { plType: plType, linkType: 'R' });
    form.value.harvestCode = code.data;
};
const taskType = ref();
const mgMethod = ref();
const landIdsTitle = ref('');
const variety = ref();
const individualLandIds = ref();
const changeRevisions = ref();
// 获取动植物的品种
const plantDate = ref();
const getVariety = async (varietyCode: any) => {
    const res = await useClientRequest.get(`/plt-api/app/medicine/getMedicineByCode/${varietyCode}`);
    plantDate.value = res.data;
};

//工艺的弹框
const showptech = ref(false);

const ptechData = ref();
//模拟工艺的字典
const getptechData = async () => {
    const res = await useClientRequest.get(`/plt-api/app/process/tech/listAllGroup`);
    ptechData.value = res?.data;
    console.log(ptechData.value, '工艺字典');
};
const goPtech = () => {
    // 跳转到pro-process-steps
    uni.$once('updatePtechTransit', function (data) {
        form.value.ptech = data?.data;
    });
    uni.$u.route({ type: 'navigateTo', url: '/tools/pro-process-steps/index', params: { ptechTransit: form?.value?.ptech } });
};
onLoad(async (options: any) => {
    form.value.taskId = options?.taskId || '';
    baseType.value = options?.baseType || '';
    taskType.value = options?.taskType || '';
    mgMethod.value = options?.mgMethod;
    variety.value = options?.variety;
    individualLandIds.value = {
        checkBox: [],
        variety: variety.value,
    };
    if (options?.change) {
        pageTitle.value = '修改采收记录';
        //重选获取一下
        const res = await useClientRequest.get(`/plt-api/app/harvestRecord/getInfo/${options?.recordId}`);
        changeRevisions.value = true;
        form.value = res.data;
        individualLandIds.value.checkBox = res.data?.animalIds;
        taskType.value = res.data?.taskType || '';
        baseType.value = res.data?.baseInfo?.baseType;
        deawerData.value = {};
        deawerData.value.baseName = res.data?.baseInfo?.baseName;
        deawerData.value.areaUnit = res.data?.baseInfo?.gapInfo.areaUnit;
        deawerData.value.area = res.data?.baseInfo?.gapInfo.area;
        deawerData.value.address = res.data?.baseInfo?.gapInfo.address;
        if (+res.data?.landFlag) {
            deawerData.value.aloneChecked = true;
        } else {
            deawerData.value.aloneChecked = false;
        }
        deawerData.value.data = res.data?.lands;
        console.log(deawerData.value, 'deawerData.value');
    } else {
        if (+taskType?.value == 11) {
            form.value.outputType = '1';
        } else if (+taskType?.value == 21) {
            form.value.outputType = '1';
        } else if (+taskType?.value == 1) {
            form.value.outputType = '2';
        } else {
            form.value.outputType = '2';
        }
    }
    getptechData();
    getVariety(options?.varietyCode);
    //判断溯源级别
    if (+options?.mgMethod == 2) {
        landIdsTitle.value = '个体';
    } else {
        if (+baseType.value == 1) {
            landIdsTitle.value = '地块';
        } else if (+baseType.value == 2) {
            landIdsTitle.value = '圈舍';
        } else {
            landIdsTitle.value = '培养架';
        }
    }
    // 监听地块选择事件
    uni.$on('selectBaseInfo', (data: any) => {
        deawerData.value = data;
        if (data && data.id) {
            form.value.landIds = [data.id];
        }
    });
});
</script>
