<template>
    <view>
        <cu-custom :backUrl="'/pages/index/index?id=apps'" :isBack="true" bgColor="bg-gradual-blue">
            <block slot="content">建筑垃圾清运处理</block>
        </cu-custom>

        <!-- First Section: 巡查工单 to 联系方式 -->
        <view class="form-section">
            <!-- 遮罩层 -->
            <view v-if="isProcessing" class="mask"></view>
            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="!nodeFlag">

                <u-form-item label="清运编号" prop="no">
                    <u--input v-model="inputForm.no" :disabled="true" placeholder="工单编号" clearable></u--input>
                </u-form-item>

                <u-form-item label="所属单位" prop="processingUnitName" :required="true" v-if="disFlag">
                    <u--input v-model="inputForm.processingUnitName" :disabled="true" placeholder="所属单位" clearable></u--input>
                </u-form-item>

                <u-form-item label="村负责人" prop="clearUserName">
                    <u--input v-model="inputForm.clearUserName" :disabled="true" placeholder="村负责人" clearable></u--input>
                </u-form-item>

                <u-form-item label="联系方式" prop="clearUserMobile">
                    <u--input v-model="inputForm.clearUserMobile" :disabled="true" placeholder="联系方式" clearable></u--input>
                </u-form-item>

                <u-form-item label="处理方式" prop="disposeType" :required="true">
                    <jp-picker v-model="inputForm.disposeType" rangeKey="label" rangeValue="value" :range="[
                    { label: '转运调剂处理', value: '1' },
                    { label: '自行处理', value: '2' },
                ]" ></jp-picker>
                </u-form-item>

                <u-form-item label="垃圾站点" prop="rubbishStation">
                    <u--input v-model="inputForm.rubbishStation" :disabled="true" placeholder="垃圾站点" clearable></u--input>
                </u-form-item>


                <template>
                    <div>
                        <u-form-item
                                v-for="(item, index_workOver) in inputForm.workOverNoList"
                                :key="index_workOver"
                                :label="`巡查工单 ${index_workOver + 1}`"
                                :required="true"
                                :prop="'workOverNoList[' + index_workOver + '].no'"
                        >
                            <div style="width: 100%" @click="showWorkOver(index_workOver)">
                                <u--input v-model="inputForm.workOverNoList[index_workOver].no" readonly
                                          style="pointer-events: none;"
                                          placeholder="请选择巡查工单编号" @focus="showWorkOver(index_workOver)" clearable></u--input>

                                <view >
                                    <text class="u-demo-block__title">{{inputForm.workOverNoList[index_workOver].no}}清理前照片</text>
                                    <view class="u-page__upload-item">
                                        <u-upload
                                                :disabled="true"
                                                :fileList="getFileList(index_workOver)"
                                                @afterRead="afterRead"
                                                name="1"
                                                multiple
                                                :maxCount="10"
                                        ></u-upload>
                                    </view>
                                </view>

                                <u-button type="error" text="删除" @click="removeRow(index_workOver)"></u-button>
                            </div>
                        </u-form-item>

                    </div>
                </template>

                <u-form-item label="" >
                    <u-button style="width: 100%" type="primary"  @click="addRow()" plain>新增巡查工单</u-button>
                </u-form-item>


            </u--form>

            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="nodeFlag">

                <u-form-item label="清运编号" prop="no">
                    <u--input v-model="inputForm.no" :disabled="true" placeholder="工单编号" clearable></u--input>
                </u-form-item>

                <u-form-item label="所属单位" prop="processingUnitName" :required="true" v-if="disFlag">
                    <u--input v-model="inputForm.processingUnitName" :disabled="true" placeholder="所属单位" clearable></u--input>
                </u-form-item>

                <u-form-item label="村负责人" prop="clearUserName">
                    <u--input v-model="inputForm.clearUserName" :disabled="true" placeholder="村负责人" clearable></u--input>
                </u-form-item>

                <u-form-item label="联系方式" prop="clearUserMobile">
                    <u--input v-model="inputForm.clearUserMobile" :disabled="true" placeholder="联系方式" clearable></u--input>
                </u-form-item>

                <u-form-item label="处理方式" prop="disposeType" :required="true" >
                    <jp-picker v-model="inputForm.disposeType" rangeKey="label" :disabled="true" rangeValue="value" :range="[
                    { label: '转运调剂处理', value: '1' },
                    { label: '自行处理', value: '2' },
                ]" ></jp-picker>
                </u-form-item>

                <u-form-item label="垃圾站点" prop="rubbishStation">
                    <u--input v-model="inputForm.rubbishStation" :disabled="true" placeholder="垃圾站点" clearable></u--input>
                </u-form-item>


                <template>
                    <div>
                        <u-form-item
                                v-for="(item, index_workOver) in inputForm.workOverNoList"
                                :key="index_workOver"
                                :label="`巡查工单 ${index_workOver + 1}`"
                                :required="true"
                                :prop="'workOverNoList[' + index_workOver + '].no'"
                        >
                            <u--input
                                    v-model="inputForm.workOverNoList[index_workOver].no"
                                    :disabled="true"
                                    placeholder="请选择巡查工单编号">
                            </u--input>
                            <u-button type="primary" style="width: 20%" text="处理" @click="disposeWorkOver(inputForm.workOverNoList[index_workOver].id)" v-if="!weighFlag"></u-button>
                        </u-form-item>
                    </div>
                </template>


            </u--form>
        </view>

        <!-- Second Section: 上传图片 -->
        <view class="form-section" v-if="nodeFlag">
            <text class="u-demo-block__title">清理前照片</text>
            <view class="u-page__upload-item">
                <u-upload
                        :disabled="true"
                        :fileList="fileList1"
                        @afterRead="afterRead"
                        name="1"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
        </view>

        <!-- Second Section: 上传图片 -->
        <view class="form-section" v-if="nodeFlag">
            <text class="u-demo-block__title">清理中照片</text>
            <view class="u-page__upload-item">
                <u-upload
                        :disabled="true"
                        :fileList="fileList2"
                        @afterRead="afterRead"
                        name="2"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
        </view>

        <!-- Second Section: 上传图片 -->
        <view class="form-section" v-if="nodeFlag">
            <text class="u-demo-block__title">清理后照片</text>
            <view class="u-page__upload-item">
                <u-upload
                        :disabled="true"
                        :fileList="fileList3"
                        @afterRead="afterRead"
                        name="3"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
        </view>

        <!-- Third Section: 备注 -->
        <view class="form-section" v-if="!nodeFlag">
            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" >
                <u-form-item label="备注" borderBottom prop="remarks">
                    <u--textarea placeholder='请填写备注' :maxlength="500" v-model="inputForm.remarks"></u--textarea>
                </u-form-item>

                <!--<view class="button-container">
                    <u-button
                            text="提交"
                            size="large"
                            type="primary"
                            @click="saveForm"
                    ></u-button>
                </view>-->
            </u--form>
        </view>
        <!-- Third Section: 备注 -->
        <view class="form-section" v-if="nodeFlag || weighFlag">
            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" >
                <u-form-item label="备注" borderBottom prop="remarks">
                    <u--textarea placeholder='请填写备注' :disabled="true" :maxlength="500" v-model="inputForm.remarks"></u--textarea>
                </u-form-item>
            </u--form>
        </view>

        <view class="form-section" v-if="weighFlag">
            <span style="color: #4396fd;">现场信息登记</span>
            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm">

                <u-form-item label="重量（t）" prop="weight" :required="true">
                    <u--input
                            @change="weightChange"
                            v-model="inputForm.weight"
                            @input="handleInput('weight', $event)"
                            placeholder="重量"
                            clearable
                    ></u--input>
                </u-form-item>

                <u-form-item label="运输里程（km）" prop="transportMileage" :required="true">
                    <u--input
                            :disabled="true"
                            v-model="inputForm.transportMileage"
                            @input="handleInput('transportMileage', $event)"
                            placeholder="运输里程"
                            clearable
                    ></u--input>
                </u-form-item>

                <u-form-item label="补贴（元）" prop="subsidy" :required="true">
                    <u--input
                            :disabled="true"
                            v-model="inputForm.subsidy"
                            @input="handleInput('subsidy', $event)"
                            placeholder="补贴"
                            clearable
                    ></u--input>
                </u-form-item>
            </u--form>
        </view>
        <!-- Second Section: 上传图片 -->
        <view class="form-section" v-if="weighFlag">
            <text style="color: black">过磅现场照片</text>
            <view class="u-page__upload-item" >
                <text class="u-demo-block__title">照片上传</text>
                <u-upload
                        :fileList="fileList4"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        name="4"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
        </view>
        <WorkOverChoose ref="workOverChoose" @input="selectWorkOverChange" title="报告项目选择"/>
    </view>
</template>

<script>
    import disposeRubbishService from '@/api/garbageClearance/disposeRubbishService'
    import overService from '@/api/garbageClearance/overService'
    import WorkOverChoose from './WorkOverChoose'
    import taskService from "@/api/flowable/taskService"
    import {mapState, mapMutations, mapActions} from 'vuex'
    import * as $auth from "../../common/auth";
    import { EventBus } from '@/store/eventBus.js';
    export default {
        components: {
            WorkOverChoose,
        },
        computed: mapState({
            userInfo: (state) => state.user.userInfo,
            avatar: (state) => state.user.avatar
        }),
        data () {
            return {
                disFlag: true,  // 启用动态获取处理单位则设置为false
                isProcessing: false,  // 遮罩层
                uploadFlag: true,  // 上传判定值
                processingUnits: [],
                taskName: '',   //当前节点处理人节点名称
                fileList1: [],
                fileList2: [],
                fileList3: [],
                fileList4: [],
                nodeFlag: false,
                weighFlag: false,  // 过磅管理员看到的信息
                inputForm: {
                    programId: '',
                    programIds: [],
                    no: '',
                    processingUnit: '',
                    processingUnitName: '',
                    clearUserId: '',
                    clearUserName: '',
                    clearUserMobile: '',
                    remarks: '',
                    status: '',
                    workOverNoList: [],
                    disposeType: '',
                    rubbishStation: '',
                    weight: '',
                    transportMileage: '',
                    subsidy: '',
                    subsidyUnitPrice: '',
                },
                rules: {
                    'processingUnit': [
                        {
                            required: true,
                            message: '处理单位不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                }
            }
        },
        // 页面加载时执行
        async created() {
            EventBus.$on('refreshPhoto', this.refreshPhoto);

            if(!this.nodeFlag){
                let data = await disposeRubbishService.getMaxNo();
                if (data) {
                    let newNo = parseInt(data, 10) + 1;
                    this.inputForm.no = newNo;
                } else {
                    // 获取当前年份
                    let nowY = new Date().getFullYear();
                    this.inputForm.no = nowY + '0001';
                }
                //获取垃圾站点信息
                let rubbishStation = await disposeRubbishService.getRubbishStation();
                this.inputForm.rubbishStation = rubbishStation;

                this.inputForm.processingUnit = this.userInfo.officeDTO.id
                this.inputForm.processingUnitName = this.userInfo.officeDTO.name
                // 不动态获取  根据当前登录人去查
                await overService.getUserInfoByOffId(this.userInfo.officeDTO.id)
                    .then(data => {
                        this.inputForm.clearUserId = data.id
                        this.inputForm.clearUserName = data.name
                        this.inputForm.clearUserMobile = data.mobile
                    })
                    .catch(e => {
                        throw e;
                    });
            }



        },
        props: {
            businessId: {
                type: String,
                default: ''
            },
            formReadOnly: {
                type: Boolean,
                default: false
            },
            status: {
                type: String,
                default: ''
            }
        },
        watch: {
            'businessId': {
                handler (newVal) {
                    if (this.businessId) {
                        this.init(this.businessId)
                    } else {
                        this.$nextTick(() => {
                            // this.$refs.inputForm.reset()
                        })
                    }
                },
                immediate: true,
                deep: false
            },
        },
        methods: {
            weightChange(weight) {
                const product = parseFloat(weight) * parseFloat(this.inputForm.transportMileage) * parseFloat(this.inputForm.subsidyUnitPrice);
                this.inputForm.subsidy = Math.round(product * 100) / 100;

            },
            handleMouseDown(event) {
                event.preventDefault(); // 防止选择文本
                this.$refs.input.focus(); // 使 input 获得焦点
            },
            getFileList(index_workOver) {
                // 返回当前行的文件列表
                return this.inputForm.workOverNoList[index_workOver].photos || [];
            },
            handleInput(field, value) {
                // Ensure value is a string and sanitize input
                value = value.toString();

                // Regular expression to match numbers with up to 2 decimal places and ensure positive value
                const regex = /^(?!.*[a-zA-Z])\-?\d+(\.\d{0,2})?$/;

                // Format the value based on regex
                const match = value.match(regex);
                let formattedValue = (match && match[0]) || '';

                // Ensure the value is positive
                if (parseFloat(formattedValue) < 0) {
                    formattedValue = '';
                }

                // Update input form based on the field
                this.inputForm[field] = formattedValue;
            },
            async init(id) {
                this.nodeFlag = true;
                this.inputForm.id = id;

                if (id) {
                    // 使用 await 等待查询结果
                    const data = await disposeRubbishService.queryById(id);

                    // 获取当前节点流程信息，并等待其执行完成
                    const taskName = await taskService.getTaskNameByProcInsId(data.procInsId);
                    this.taskName = taskName

                    // 根据任务名称处理逻辑
                    if (this.isNotEmpty(taskName)) {
                        if (taskName === '发起人重新申请' || this.isEmpty(taskName)) {
                            this.nodeFlag = false;
                        } else if (taskName === '过磅专员处理') {
                            this.nodeFlag = true;
                            this.weighFlag = true;
                            //在此处获取发起地区的距离以及计算方式

                        }
                    }

                    // 恢复表单数据
                    this.inputForm = this.recover(this.inputForm, data);

                    // 处理文件列表
                    if (data.fileList1) {
                        this.fileList1 = data.fileList1.map(item => ({
                            attachmentName: item.name,
                            fileSize: item.size,
                            url: item.temporaryUrl,
                            type: item.type // 如果不需要，可以不写
                        }));
                    }

                    if (data.fileList2) {
                        this.fileList2 = data.fileList2.map(item => ({
                            attachmentName: item.name,
                            fileSize: item.size,
                            url: item.temporaryUrl,
                            type: item.type // 如果不需要，可以不写
                        }));
                    }

                    if (data.fileList3) {
                        this.fileList3 = data.fileList3.map(item => ({
                            attachmentName: item.name,
                            fileSize: item.size,
                            url: item.temporaryUrl,
                            type: item.type // 如果不需要，可以不写
                        }));
                    }
                }
            }
            ,
            async selectWorkOverChange(rows, index) {
                //判定index所在行是否有数据，若有数据，则需要将数据从programIds 和 workOverNoList 进行删除
                var flag = false;
                if(this.inputForm.programIds.length>index ){
                    var result= this.inputForm.programIds[index]
                    if(result){
                        flag = true
                    }
                }

                if (rows.length > 0) {
                    // 遍历 rows 数组
                    for (const [rowIndex, item] of rows.entries()) {
                        if(flag) {
                            flag = false
                            this.inputForm.programIds[index] = item.id
                        }

                        const uniqueIds = [...new Set([...this.inputForm.programIds, item.id])];

                        // 更新 programIds 数组
                        this.inputForm.programIds = uniqueIds;
                        console.log(this.inputForm.programIds)
                    }

                    const programIdString = this.inputForm.programIds.join(','); // 用逗号分隔
                    await overService.getPhotoListByIdAndAttachmentFlag(programIdString,'before').then(data => {
                        this.inputForm.workOverNoList = [];
                        // 将数据填充到 workOverNoList
                        data.forEach((item) => {
                            // 创建新的工作项
                            let workOverItem = { no: item.no };

                            // 处理 fileList1 数据
                            if (item.fileList1) {
                                workOverItem.photos = item.fileList1.map(file => ({
                                    url: file.temporaryUrl,
                                    type: file.type
                                }));
                            }

                            // 将新的工作项添加到 workOverNoList
                            this.inputForm.workOverNoList.push(workOverItem);
                        });
                    }).catch(() => {
                        reject('数据错误');
                    });

                }

            },

            addRow() {
                this.inputForm.workOverNoList.push({ recipientAgent: this.userInfo.name,
                    recipientAgentId: this.userInfo.id, recipientOffice: this.userInfo.officeDTO.name });
            },

            // 显示  项目选择器
            showWorkOver(index) {
                this.$refs.workOverChoose.init(index);

            },

            // 显示  项目选择器
            disposeWorkOver(id) {
                if(this.inputForm.status === '2'){
                    uni.navigateTo({
                        url: '/pages/edt/PatrolWorkOrderForm?id='+id
                    })
                }else{
                    this.toEdit(this.inputForm)
                }

            },
            //刷信photo获取对应的id
            refreshPhoto() {
                disposeRubbishService.queryById(this.inputForm.id).then((data) => {

                    if (data.fileList1) {
                        this.fileList1 = []
                        data.fileList1.forEach(
                            (item) => {
                                const newItem = {
                                    attachmentName: item.name,
                                    fileSize: item.size,
                                    url: item.temporaryUrl,
                                    type: item.type,      // 如果不需要，可以不写
                                };
                                this.fileList1.push(newItem);
                            }
                        );
                    }
                    if (data.fileList2) {
                        this.fileList2 = []
                        data.fileList2.forEach(
                            (item) => {
                                const newItem = {
                                    attachmentName: item.name,
                                    fileSize: item.size,
                                    url: item.temporaryUrl,
                                    type: item.type,      // 如果不需要，可以不写
                                };
                                this.fileList2.push(newItem);
                            }
                        );
                    }
                    if (data.fileList3) {
                        this.fileList3 = []
                        data.fileList3.forEach(
                            (item) => {
                                const newItem = {
                                    attachmentName: item.name,
                                    fileSize: item.size,
                                    url: item.temporaryUrl,
                                    type: item.type,      // 如果不需要，可以不写
                                };
                                this.fileList3.push(newItem);
                            }
                        );
                    }
                })
            },

            removeRow(index) {
                // 点击删除按钮时，从表格中移除指定行
                this.inputForm.programIds.splice(index, 1);
                this.inputForm.workOverNoList.splice(index, 1);
                //重新获取巡查工单信息
                this.insertRefreshPhoto()
            },

            //刷信photo获取对应的id
            insertRefreshPhoto() {
                disposeRubbishService.getByWorkOverId(this.inputForm.programIds).then((data) => {
                    if (data) {
                        this.fileList1 = []
                        data.forEach(
                            (item) => {
                                const newItem = {
                                    attachmentName: item.name,
                                    fileSize: item.size,
                                    url: item.temporaryUrl,
                                    type: item.type,      // 如果不需要，可以不写
                                };
                                this.fileList1.push(newItem);
                            }
                        );
                    }
                })
            },

            formatDate(date) {
                const dateNew = new Date(date); // 将日期字符串转换为 Date 对象
                const year = dateNew.getFullYear();
                const month = (dateNew.getMonth() + 1).toString().padStart(2, '0');
                const day = dateNew.getDate().toString().padStart(2, '0');
                return `${year}-${month}-${day}`;
            },
            isEmpty(value) {
                let result = false;
                if (value == null || value == undefined) {
                    result = true;
                }
                if (typeof value == 'string' && (value.replace(/\s+/g, "") == "" || value == "")) {
                    result = true;
                }
                if (typeof value == "object" && value instanceof Array && value.length === 0) {
                    result = true;
                }
                return result;
            },
            isNotEmpty (value) {
                return !this.isEmpty(value)
            },
            /**
             * 判断是否为空
             */
            isNull(val) {
                if (val instanceof Array) {
                    if (val.length === 0) return true;
                } else if (val instanceof Object) {
                    if (JSON.stringify(val) === "{}") return true;
                } else {
                    if (
                        val === "null" ||
                        val == null ||
                        val === "undefined" ||
                        val === undefined ||
                        val === ""
                    )
                        return true;
                    return false;
                }
                return false;
            },

            formatDateNew(date) {
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                const seconds = date.getSeconds().toString().padStart(2, '0');

                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            saveForm(callback) {
                this.isProcessing = true; // 显示遮罩层

                return new Promise((resolve, reject) => {
                    // 表单规则验证
                    // ...

                    let errors = [];

                    if(!this.uploadFlag){
                        errors.push("图片未上传完成，请等待上传完后在提交")
                    }

                    if(!this.inputForm.disposeType){
                        errors.push("请选择处理方式")
                    }
                    if(this.inputForm.programId && !this.inputForm.programIds){
                        this.inputForm.programIds = []
                        let fruitsArray = this.inputForm.programId.split(',');
                        this.inputForm.programIds = fruitsArray
                    }
                    if(!this.inputForm.programId && this.inputForm.programIds){
                        const programIdString = this.inputForm.programIds.join(','); // 用逗号分隔
                        this.inputForm.programId = programIdString
                    }
                    if(this.inputForm.programIds.length == 0){
                        errors.push("请选择巡查工单")
                    }
                    if(this.weighFlag){
                        if(!this.inputForm.weight){
                            errors.push("请填写重量")
                        }
                        if(!this.inputForm.transportMileage){
                            errors.push("请填写运输里程")
                        }
                        if(!this.inputForm.subsidy){
                            errors.push("请填写补贴金额")
                        }
                    }

                    if (errors.length > 0) {
                        // 存在错误，显示提示信息
                        errors.forEach(error => {
                            this.isProcessing = false; // 显示遮罩层
                            uni.showToast({
                                title: error,
                                icon: 'none',
                                duration: 2000
                            });
                        });
                        this.isProcessing = false;
                        reject('Form validation failed');
                    } else {
                        // 所有验证通过，执行保存操作
                        this.$refs.inputForm.validate().then(() => {
                            uni.showLoading();
                            if(this.weighFlag){
                                this.inputForm.status = '5'
                            }else{
                                if(this.inputForm.disposeType === '1'){
                                    this.inputForm.status = '2'
                                }else if(this.inputForm.disposeType === '2'){
                                    if(this.taskName){
                                        this.inputForm.status = '5'
                                    }else{
                                        this.inputForm.status = '2'
                                    }
                                }else{
                                    this.inputForm.status = '2'
                                }
                            }
                            this.inputForm.fileList4 = this.fileList4
                            disposeRubbishService.save(this.inputForm).then(data => {
                                uni.showToast({
                                    title: "提交成功",
                                    icon: "success",
                                    duration: 1000  // 提示持续时间为1秒（1000毫秒）
                                });

                                // 延迟1秒后再跳转到上一页
                                setTimeout(() => {
                                    this.isProcessing = false; // 显示遮罩层
                                    callback(data.businessTable, data.businessId,this.inputForm,this.inputForm.disposeType);
                                    uni.navigateBack({
                                        delta: 1
                                    });
                                }, 1000);
                                resolve('Form saved successfully');
                            }).catch(error => {
                                reject('Save operation failed');
                            });
                        }).catch(() => {
                            reject('Form validation failed');
                        });
                    }
                });
            },

            // 删除图片
            deletePic(event) {
                this[`fileList${event.name}`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                try {
                    this.uploadFlag = false
                    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
                    let lists = [].concat(event.file)
                    let fileListLen = this[`fileList${event.name}`].length
                    lists.map((item) => {
                        this[`fileList${event.name}`].push({
                            ...item,
                            status: 'uploading',
                            message: '上传中'
                        })
                    })
                    for (let i = 0; i < lists.length; i++) {
                        const result = await this.uploadFilePromise(lists[i].url, fileListLen)
                        let item = this[`fileList${event.name}`][fileListLen]
                        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                            status: 'success',
                            message: '',
                            url: result
                        }))
                        fileListLen++
                    }
                    this.uploadFlag = true
                } catch (error) {
                    console.error('上传失败:', error);
                } finally {
                    this.uploadFlag = true
                }
            },
            uploadFilePromise(url, index) {
                return new Promise((resolve, reject) => {
                    let a = uni.uploadFile({
                        url: 'http://dttz.xgccpm.cn/api/app/file/webUpload/fileUpload', // 仅为示例，非真实的接口地址
                        filePath: url,
                        name: 'file',
                        formData: {
                            user: this.$store.state.user.userInfo
                        },
                        header: {
                            'token': $auth.getUserToken(),
                        },
                        success: (res) => {

                            // this.fileList1[index].url = url

                            setTimeout(() => {
                                const dataObj = JSON.parse(res.data);
                                const url = dataObj.url;
                                resolve(url);
                            }, 1000);
                        },
                        fail: (err) => {
                            console.error('Upload failed:', err);
                        }
                    });
                })
            },
            getUserInfoByOffId(){
                // 根据组织ID 获取 该村的 村支书
                overService.getUserInfoByOffId(this.inputForm.processingUnit)
                    .then(data => {
                        this.inputForm.clearUserId = data.id
                        this.inputForm.clearUserName = data.name
                        this.inputForm.clearUserMobile = data.mobile
                    })
                    .catch(e => {
                        throw e;
                    });
            }
        }
    }
</script>

<style>
    .form-section {
        padding: 10px 15px;
        margin-bottom: 10px;
        background-color: #ffffff;
        border-radius: 5px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .u-page__upload-item {
        margin-top: 10px;
    }

    .button-container {
        margin-top: 20px;
        text-align: center;
    }

    .cu-form-group .title {
        min-width: 100px;
    }
    /* 遮罩层样式 */
    .mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.05); /* 半透明遮罩 */
        z-index: 9999; /* 确保遮罩层在最顶层 */
    }
</style>
