<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>
            <view class="pd-24 bg-#fff">
                <up-alert title="注意：投入物料记录可用于记录此次任务投入过的物料，不分管理具体事务、圈舍和时间记录。" type="info" class="b-radius"></up-alert>
            </view>
            <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
                <view class="bg-#fff pd-24 pt-0 mb-20">
                    <!-- 使用物料 -->
                    <up-form-item borderBottom label="使用物料" required prop="inputs" id="inputsgpppp">
                        <view class="d-flex flex-cln w-100%">
                            <view v-if="!isAdd" class="c-#F19F18 f-s-24">因物料修改涉及退库操作，不支持修改!物料信息如有错误，请删除此条管理记录，重新添加。</view>
                            <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>
                    <!-- 操作日期 -->
                    <view class="h-1" id="operationDatepppp"></view>
                    <!-- 记录人 -->
                    <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="备注/说明" 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_activity_input_material } = toRefs<any>(proxy?.useDict('yes_no', 'pt_activity_input_material'));
const deawerData = ref();
const infoStore = useInfoStore();
// 表单数据
const form = ref({
    taskId: '',
    //管理类型 1-农事管理 2-投料
    activityType: '2',
    opRemark: '',
    mgName: infoStore.userInfo?.name,
    inputFlag: '1',
    //物料列表
    inputs: [] as any,
    remark: '',
    imgs: null as string | null,
    videos: null as string | null,
});
const baseId = ref('');
const Material = ref();
//判断是新增还是修改
const isAdd = ref(true);

// 自定义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();
};
// 表单验证规则
const rules = reactive({
    mgName: [{ required: true, message: '请输入记录人' }],
    remark: [{ required: false, message: '请输入备注' }],
    inputs: [{ validator: validateInputs, trigger: 'blur' }],
});

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 MaterialData = ref([]);
// 提交表单
const save = () => {
    uni.$u.debounce(
        async () => {
            try {
                console.log('开始提交管理记录');
                await upFormRef.value?.validate();
                console.log('校验完成');
                const params = {
                    ...form.value,
                };
                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,
                };

                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 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;
        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>
