<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="startline-title pl-24 ml-24 mb-16">管理记录信息</view>
                <view class="bg-#fff pd-24 mb-20">
                    <!-- 操作日期 -->
                    <view class="h-1" id="operationDatepppp"></view>
                    <up-form-item :borderBottom="false" label="操作日期" required prop="operationDate">
                        <ut-datetime-picker v-model="form.operationDate.activityStart" mode="date" dateFields="day" @change="changeStartTime">
                            <view class="d-flex mr-20">
                                <up-input v-model="form.operationDate.activityStart" 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>
                        <ut-datetime-picker v-model="form.operationDate.activityEnd" mode="date" dateFields="day">
                            <view class="d-flex">
                                <up-input v-model="form.operationDate.activityEnd" 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>
                    <!-- 操作类型 -->
                    <ut-action-sheet v-model="form.opMethod" :tabs="pt_op_method" title="选择操作类型" mode="custom">
                        <up-form-item borderBottom label="操作类型" required prop="opMethod" id="opMethodpppp">
                            <view v-if="form.opMethod" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_op_method, form.opMethod) }}</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.opMethod == '99'" borderBottom label="自填操作类型" required prop="cusOp" id="cusOppppp">
                        <up-input v-model="form.cusOp" placeholder="请输入自填操作类型" border="none"></up-input>
                    </up-form-item>
                    <!-- 操作地块 -->
                    <up-form-item :borderBottom="false" label="操作地块" prop="landIds" id="baseIdpppp">
                        <view v-if="!deawerData" class="w-100% d-flex a-c j-c pd-24 b-radius bg-#FBFDFB border-#AFDDBB" @click="goSelectBase()">
                            <view class=""></view>
                            <view class="f-s-34 c-primary">请选择操作地块</view>
                        </view>
                        <view class="w-100%" v-else>
                            <Baseinfo :modeValue="deawerData" @close="handleBaseinfoClose" :baseType="'1'" />
                        </view>
                    </up-form-item>
                    <!-- 操作方式 -->
                    <up-form-item borderBottom label="操作方式" prop="opRemark" id="opRemarkpppp">
                        <up-input v-model="form.opRemark" placeholder="如:人工锄草、机械中耕、喷雾器叶面喷施等" border="none"></up-input>
                    </up-form-item>
                    <!-- 记录人 -->
                    <up-form-item borderBottom label="记录人" required prop="mgName" id="mgNamepppp">
                        <up-input v-model="form.mgName" placeholder="请输入记录人" border="none"></up-input>
                    </up-form-item>
                    <!-- 是否使用物料 -->
                    <up-form-item borderBottom label="是否使用物料" required prop="inputFlag" id="inputFlagpppp">
                        <view class="d-flex flex-cln">
                            <view v-if="!isAdd" class="c-#F19F18 f-s-24">因物料修改涉及退库操作，不支持修改!物料信息如有错误，请删除此条管理记录，重新添加。</view>
                            <up-radio-group v-model="form.inputFlag">
                                <up-radio :disabled="!+isAdd" :customStyle="{ marginRight: '60rpx' }" v-for="(item, index) in yes_no" :key="index" :label="item.label" :name="item.value"></up-radio>
                            </up-radio-group>
                        </view>
                    </up-form-item>
                    <!-- 使用物料 -->
                    <up-form-item v-if="+form.inputFlag" borderBottom label="使用物料" required prop="inputs" id="inputspppp">
                        <view class="d-flex flex-cln w-100%">
                            <view class="w-100%">
                                <Materialinfo :showClose="isAdd" v-model:datas="MaterialData" v-model:inputs="form.inputs" />
                            </view>
                            <view v-if="isAdd" class="d-flex a-c j-c pd-24 b-radius bg-#FBFDFB border-#AFDDBB" @click="goMaterial()">
                                <view class=""></view>
                                <view class="f-s-34 c-primary">请选择此次农事使用的物料</view>
                            </view>
                        </view>
                    </up-form-item>
                    <!-- 备注 -->
                    <up-form-item borderBottom label="备注/说明" prop="remark" id="remarkpppp">
                        <up-input v-model="form.remark" placeholder="如：“防治阔叶杂草”、“花期追肥”" border="none"></up-input>
                    </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>
                </view>
            </up-form>
        </view>
        <template #bottom>
            <view class="pd-24 d-flex j-c gap-20 base-bottom-wrap">
                <up-button v-if="+isAdd" type="primary" @click="save()">确认添加</up-button>
                <up-button v-else type="primary" @click="change()">确认修改</up-button>
            </view>
        </template>
    </z-paging>
</template>
<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance, type ComponentInternalInstance } from 'vue';
import { useClientRequest } from '@/utils/request';
import { useInfoStore } from '@/store';
import Baseinfo from '../models/baseinfo.vue';
import Materialinfo from '../models/materialinfo.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { yes_no, pt_op_method } = toRefs<any>(proxy?.useDict('yes_no', 'pt_op_method'));
const deawerData = ref();
const infoStore = useInfoStore();
// 表单数据
const form = ref({
    taskId: '',
    //管理类型 1-农事管理 2-投料
    activityType: '1',
    operationDate: {
        activityStart: null as string | null,
        activityEnd: null as string | null,
    },
    //作用对象类型 1-地块 2-动物
    targetType: '1',
    opMethod: null as string | null,
    cusOp: null as string | null,
    //操作地块
    landIds: [],
    opRemark: '',
    mgName: infoStore.userInfo?.name,
    //是否使用物料
    inputFlag: '0' as '0' | '1',
    //物料列表
    inputs: [] as any,
    remark: '',
    imgs: null as string | null,
    videos: null as string | null,
    landFlag: '0' as '0' | '1',
});
const baseId = ref('');
const Material = ref();
//判断是新增还是修改
const isAdd = ref(true);
// 自定义校验函数：操作日期校验
const validateOperationDate = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请选择操作日期'));
        return;
    }
    const { activityStart, activityEnd } = value;
    if (!activityStart) {
        callback(new Error('请选择操作开始时间'));
        return;
    }
    if (!activityEnd) {
        callback(new Error('请选择操作结束时间'));
        return;
    }
    const start = new Date(activityStart);
    const end = new Date(activityEnd);
    if (end < start) {
        callback(new Error('操作结束时间必须晚于开始时间'));
        return;
    }
    callback();
};
// 自定义inputs校验函数
const validateInputs = (rule: any, value: any, callback: any) => {
    // value 应该是 inputs 数组
    if (!value || !Array.isArray(value) || value.length === 0) {
        callback(new Error('请至少添加一个物料并填写用量'));
        return;
    }

    // 检查每个物料
    for (const item of value) {
        if (!item || typeof item !== 'object') {
            callback(new Error('物料数据格式错误'));
            return;
        }

        const { id, inputAmount } = item;

        if (!id) {
            callback(new Error('物料ID缺失'));
            return;
        }

        if (inputAmount === undefined || inputAmount === null || inputAmount === '') {
            callback(new Error('请填写物料用量'));
            return;
        }

        const amount = Number(inputAmount);
        if (isNaN(amount) || amount <= 0) {
            callback(new Error('物料用量必须大于0'));
            return;
        }
    }

    callback();
};
// 自定义校验函数：自填操作类型校验（当opMethod为99时必填）
const validateCusOp = (rule: any, value: any, callback: any) => {
    if (form.value.opMethod === '99' && !value) {
        callback(new Error('请输入自填操作类型'));
        return;
    }
    callback();
};

// 表单验证规则
const rules = reactive({
    operationDate: [{ validator: validateOperationDate, trigger: 'blur' }],
    opMethod: [{ required: true, message: '请选择操作类型' }],
    cusOp: [{ validator: validateCusOp, trigger: 'blur' }],
    opRemark: [{ required: false, message: '请输入操作方式' }],
    mgName: [{ required: true, message: '请输入记录人' }],
    inputFlag: [{ required: true, message: '请选择是否使用物料' }],
    remark: [{ required: false, message: '请输入备注' }],
    inputs: [{ validator: validateInputs, trigger: 'blur' }],
});
const changeStartTime = () => {
    if (!form.value?.operationDate?.activityEnd) {
        form.value.operationDate.activityEnd = form.value.operationDate.activityStart;
    }
};
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 handleBaseinfoClose = () => {
    deawerData.value = null;
};
// 提交表单
const save = () => {
    uni.$u.debounce(
        async () => {
            try {
                console.log('开始提交管理记录');
                await upFormRef.value?.validate();
                console.log('校验完成');
                const params = {
                    ...form.value,
                    ...form.value.operationDate,
                    landFlag: deawerData?.value?.aloneChecked ? '1' : '0',
                };
                console.log('提交参数:', params);
                // 这里需要根据实际 API 进行调整
                const res = await useClientRequest.post('/plt-api/app/plantationActivity/saveActivity', params);
                if (res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    setTimeout(() => {
                        //发送emit
                        uni.$emit('updatesuperviselist');
                        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,
                    ...form.value.operationDate,
                    landFlag: deawerData?.value?.aloneChecked ? '1' : '0',
                };

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

                // 这里需要根据实际 API 进行调整
                const res = await useClientRequest.post('/plt-api/app/plantationActivity/updateActivity', params);
                if (res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    setTimeout(() => {
                        //发送emit
                        uni.$emit('updatesuperviselist');
                        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 goSelectBase = () => {
    uni.$once('updatelands', function (data) {
        deawerData.value = data;
        form.value.landIds = deawerData.value.checkBox;
    });
    uni.$u.route({ type: 'navigateTo', url: '/tools/supervise-plot/index', params: { baseId: baseId.value } });
};
const MaterialData = ref([]);
//去选择物料
const goMaterial = () => {
    if (!+isAdd.value) {
        return;
    }
    uni.$once('updateMaterial', function (data) {
        MaterialData.value = data?.data;
        data?.data.forEach((i) => {
            //判断 MaterialData.value中的id是否有i.id
            if (!MaterialData.value.find((item) => item.id === i.id)) {
                MaterialData.value.push(i);
            }
        });
    });
    uni.$u.route({ type: 'navigateTo', url: '/tools/supervise-material/index', params: { baseId: baseId.value } });
};
onLoad(async (options: any) => {
    baseId.value = options?.baseId;
    form.value.taskId = options?.taskId;
    isAdd.value = Boolean(+options?.add);
    if (!+isAdd.value) {
        const res = await useClientRequest.get(`/plt-api/app/plantationActivity/getInfo/${options.id}`);
        if (!res || res.code !== 200) return;
        form.value = res.data;
        form.value.operationDate = {
            activityStart: res.data.activityStart,
            activityEnd: res.data.activityEnd,
        };
        deawerData.value = {
            ...res.data.baseInfo,
            area: res?.data?.baseInfo?.gapInfo?.area,
            areaUnit: res?.data?.baseInfo?.gapInfo?.areaUnit,
            adcodeName: res?.data?.baseInfo?.gapInfo?.adcodeName,
            medicineName: res?.data?.baseInfo?.gapInfo?.medicineName,
            aloneChecked: res?.data?.inputFlag == '1' ? true : false,
            data: res.data.lands,
            checkBox: res.data.landIds,
        };
        MaterialData.value = res.data.inputMaterialList;
        res.data.inputMaterialList.forEach((i) => {
            if (!form.value.inputs) {
                form.value.inputs = [];
            }
            form.value.inputs.push({
                id: i.id,
                inputAmount: +i.quantity,
            });
        });
    }
});
</script>
