<template>
    <home-container>
        <view class="report-container">
            <!-- 表单区域 -->
            <uni-forms ref="form" :rules="rules" :modelValue="formData" label-position="top" err-show-type="modal">
                <!-- 基本信息分组 (默认展开) -->
                <view class="card">
                    <uni-collapse :accordion="false" :value="['group1']">
                        <h-collapse-item name="group1" :show-animation="true"
                            :iconUrl="'../../static/images/icon/jiben.png'" :title="'基本信息'">
                            <uni-forms-item label="任务编号" name="taskCode">
                                <uni-easyinput v-model="formData.taskCode" placeholder="系统自动生成"
                                    :disabled="true"></uni-easyinput>
                            </uni-forms-item>
                            <uni-forms-item label="检查人" name="checkerName">
                                <uni-easyinput v-model="formData.checkerName" placeholder="请输入检查人姓名" :disabled="true" />
                            </uni-forms-item>
                            <uni-forms-item label="执行频率" name="frequency">
                                <uni-easyinput :value="`${formData.ruleTypeDesc}${formData.ruleTypeNum}次`"
                                    placeholder="请输入执行频率" :disabled="true" />
                            </uni-forms-item>
                            <uni-forms-item label="任务简介" name="description">
                                <uni-easyinput type="textarea" v-model="formData.description" placeholder="请输入任务简介"
                                    :disabled="true" />
                            </uni-forms-item>
                            <uni-forms-item :label="getCheckLabel" :name="getCheckFieldName" required>
                                <uni-data-picker v-if="getCheckLabel == '被检查主管'" :localdata="departments"
                                    :popup-title="`请选择${getCheckLabel}`" v-model="formData.checkedDepartmentId"
                                    @change="handlecheckedDepartmentIdChange" :readonly="formDisabled" />
                                <uni-data-picker v-if="getCheckLabel == '被检查大队'" :localdata="brigades"
                                    :popup-title="`请选择${getCheckLabel}`" v-model="formData.checkedBrigadeId"
                                    @change="handlecheckedBrigadeIdChange" :readonly="formDisabled" />
                                <uni-data-picker v-if="getCheckLabel == '被检查班组'" :localdata="teams"
                                    :popup-title="`请选择${getCheckLabel}`" v-model="formData.checkedTeamId"
                                    @change="handlecheckedTeamIdChange" :readonly="formDisabled" />

                                <fuzzy-select v-if="getCheckLabel == '被检查人'" v-model="formData.checkedPersonnelId"
                                    :options="userOptions" placeholder="请输入被检查人姓名搜索" data-value="userId"
                                    data-text="nickName" @change="handleCheckedSelect" :disabled="formDisabled" />
                            </uni-forms-item>
                            <uni-forms-item label="检查地点" name="checkLocation" required>
                                <uni-data-picker :localdata="location_options" popup-title="请选择检查地点"
                                    v-model="formData.checkLocation" @change="handleCheckLocationChange"
                                    :readonly="formDisabled" />
                            </uni-forms-item>
                            <uni-forms-item label="检查时间" name="checkTime" required>
                                <uni-datetime-picker type="datetime" :start="startDate" v-model="formData.checkTime"
                                    :disabled="formDisabled" />
                            </uni-forms-item>
                        </h-collapse-item>
                    </uni-collapse>
                </view>

                <!-- 巡检项目分组 -->
                <view class="card">
                    <uni-collapse :accordion="false" :value="['group2']">
                        <h-collapse-item title="巡检项目" name="group2" :show-animation="true"
                            :iconUrl="'../../static/images/icon/xunjian.png'" ref="xunjianCollapseItem">
                            <view style="padding: 0 15px 15px 15px;">
                                <!-- 巡检项目描述卡片 -->
                                <list-card v-for="(item, index) in formData.checkProjectItemList" :key="item.id">
                                    <template #title>
                                        <view class="item-title">
                                            {{ item.categoryNameOne }}/{{ item.categoryNameTwo }}
                                        </view>
                                    </template>
                                    <view v-for="(ele, i) in item.children" :key="ele.id">
                                        <view class="list-row-space-between">
                                            <view class="list-label">
                                                {{ ele.projectName }}
                                            </view>
                                            <view class="list-value">
                                                <TextSwitch class="text-switch" v-model="ele.scoreLevel"
                                                    uncheck_text="不符合" uncheck_value="UNQUALIFIED" checked_text="符合"
                                                    checked_value="QUALIFIED" :disabled="formDisabled" />
                                            </view>
                                        </view>
                                        <!-- 不合格人员组件 -->
                                        <view v-if="ele.scoreLevel == 'UNQUALIFIED'">
                                            <unqualified-personnel v-model="ele.problemDescription" :formData="formData"
                                                :personnel-data="ele.checkUserList || []" :parent-index="index"
                                                :child-index="i" @personnel-change="handlePersonnelChange"
                                                :disabled="formDisabled" />
                                        </view>
                                    </view>
                                </list-card>


                                <!-- 不合格图片上传 -->
                                <view class="upload-section" v-if="!allItemsQualified">
                                    <text class="upload-title">上传不合格图片</text>
                                    <uni-file-picker v-model="formData.baseAttachmentList" limit="8" title="最多上传8张"
                                        style="height: 350rpx;" :image-styles="imageStyles" fileMediatype="image"
                                        mode="grid" @select="onSelect" :disabled="formDisabled"
                                        :readonly="formDisabled" />
                                </view>
                            </view>
                        </h-collapse-item>
                    </uni-collapse>
                </view>

                <!-- 整改要求分组 -->
                <view class="card" v-if="rectificationSuggestionsRequired">
                    <uni-collapse :accordion="false" :value="['group3']">
                        <h-collapse-item title="整改要求" name="group3" :show-animation="true"
                            :iconUrl="'../../static/images/icon/zhenggai.png'">
                            <uni-forms-item label="责任人" name="responsibleUserId" required>
                                <fuzzy-select v-model="formData.responsibleUserId" :options="userOptions"
                                    placeholder="请输入责任人姓名搜索" data-value="userId" data-text="nickName"
                                    @change="handleUserSelect" :disabled="formDisabled" />
                            </uni-forms-item>

                            <uni-forms-item label="整改期限" name="rectificationDeadline" required>
                                <uni-datetime-picker type="datetime" :start="startDate"
                                    v-model="formData.rectificationDeadline" :disabled="formDisabled" />
                            </uni-forms-item>

                            <uni-forms-item label="整改要求" name="rectificationSuggestions" required>
                                <uni-easyinput type="textarea" v-model="formData.rectificationSuggestions"
                                    placeholder="请输入整改要求" :disabled="formDisabled" />
                            </uni-forms-item>
                        </h-collapse-item>
                    </uni-collapse>
                </view>

                <!-- 提交按钮 -->
                <view class="button-group" v-if="formData.checkRecordStatus == 'DRAFT' || type == 'task'">
                    <view class="custom-btn-white" @click="saveDraft">保存草稿</view>
                    <view class="custom-btn-normal" @click="submitForm">立刻提交</view>
                </view>
            </uni-forms>
        </view>

        <SubmitResult ref="submitResult" @continue-submit="handleContinueSubmit" />
    </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import ListCard from "@/components/list-card/list-card.vue";
import { getCheckTask } from "@/api/check/checkTask.js"
import TextSwitch from "@/components/text-switch/text-switch.vue"
import { checkedLevelEnums } from "@/utils/enums.js"
import UnqualifiedPersonnel from "./components/unqualified.vue"
import { treeSelectByType } from "@/api/system/common"
import { buildTeamOptions, buildDepartmentOptions, buildBrigadeOptions, buildManagerOptions } from '@/utils/common'
import useDictMixin from '@/utils/dict'
import { getDeptRoleUser } from "@/api/check/checklist.js"
import { addDraftInspection, submitInspection, getInspectionListById } from '@/api/check/checkReward.js'
import SubmitResult from './components/SubmitResult.vue'
import { selectDeptLeaderByUserId } from '@/api/approve/approve.js'
import config from '@/config'
import { getToken } from '@/utils/auth'
import { listAllUser } from "@/api/system/user.js"
import { formatTime } from '@/utils/formatUtils'
import { getDeptList, getDeptManager } from "@/api/system/dept/dept.js"
import FuzzySelect from "@/components/fuzzy-select/fuzzy-select.vue"
export default {
    components: { HomeContainer, ListCard, TextSwitch, UnqualifiedPersonnel, FuzzySelect, SubmitResult },
    mixins: [useDictMixin],
    computed: {
        currentUser() {
            return this.$store.state.user;
        },
        notkezhang() {
            let roles = this.$store.state.user.roles
            return !roles || !roles.includes('kezhang')
        },
        roles() {
            return this.$store.state.user.roles
        },
        rectificationSuggestionsRequired() {
            let res = this.formData.checkProjectItemList || []
            if (res.length == 0) {
                return false
            }
            return res.some(item => {
                return item.children.some(child => child.scoreLevel == 'UNQUALIFIED')
            })
        },
        // 判断是否所有检查项都符合
        allItemsQualified() {
            let res = this.formData.checkProjectItemList || []
            if (res.length == 0) {
                return false
            }
            return res.every(item => {
                return item.children.every(child => child.scoreLevel == 'QUALIFIED')
            })
        },
        formDisabled() {
            return this.formData.checkRecordStatus != 'DRAFT' && this.type == 'document'
        },
        getCheckLabel() {
            if (this.formData.checkedLevel == checkedLevelEnums.TEAM_LEVEL) {
                return '被检查班组'
            }
            if (this.formData.checkedLevel == checkedLevelEnums.PERSONNEL_LEVEL) {
                this.getDeptLeader()
                return '被检查人'
            }
            if (this.formData.checkedLevel == checkedLevelEnums.DEPARTMENT_LEVEL) {
                return '被检查主管'
            }
            if (this.formData.checkedLevel == checkedLevelEnums.BRIGADE_LEVEL) {
                return '被检查大队'
            }
        },
        // 获取验证字段名
        getCheckFieldName() {
            if (this.formData.checkedLevel == checkedLevelEnums.TEAM_LEVEL) {
                return 'checkedTeamId'
            }
            if (this.formData.checkedLevel == checkedLevelEnums.PERSONNEL_LEVEL) {
                return 'checkedPersonnelId'
            }
            if (this.formData.checkedLevel == checkedLevelEnums.DEPARTMENT_LEVEL) {
                return 'checkedDepartmentId'
            }
            if (this.formData.checkedLevel == checkedLevelEnums.BRIGADE_LEVEL) {
                return 'checkedBrigadeId'
            }
        },
        // 验证规则
        rules() {
            let changeRule = {}
            if (this.formData.checkedLevel == checkedLevelEnums.TEAM_LEVEL) {
                changeRule = {
                    checkedTeamId: {
                        rules: [{ required: true, errorMessage: '请选择被检查班组' }]
                    }
                }
            }
            if (this.formData.checkedLevel == checkedLevelEnums.PERSONNEL_LEVEL) {
                changeRule = {
                    checkedPersonnelId: {
                        rules: [{ required: true, errorMessage: '请选择被检查人' }]
                    }
                }
            }
            if (this.formData.checkedLevel == checkedLevelEnums.DEPARTMENT_LEVEL) {
                changeRule = {
                    checkedDepartmentId: {
                        rules: [{ required: true, errorMessage: '请选择被检查主管' }]
                    }
                }
            }
            if (this.formData.checkedLevel == checkedLevelEnums.BRIGADE_LEVEL) {
                changeRule = {
                    checkedBrigadeId: {
                        rules: [{ required: true, errorMessage: '请选择被检查大队' }]
                    }
                }
            }
            return {
                ...changeRule,
                checkLocation: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择检查地点'
                        },
                        {
                            validateFunction: (rule, value, data, callback) => {
                                console.log(value, "value")
                                if (!value) {
                                    // 检查是否选择了完整的检查地点（终端、区域、通道）
                                    callback('请选择完整的检查地点');
                                } else {
                                    callback();
                                }
                            }
                        }
                    ]
                },
                checkTime: {
                    rules: [{ required: true, errorMessage: '请选择检查时间' }]
                },
                responsibleUserId: {
                    rules: [{ required: true, errorMessage: '请输入责任人姓名' }]
                },
                rectificationDeadline: {
                    rules: [{ required: true, errorMessage: '请选择整改期限' }]
                },
                rectificationSuggestions: {
                    rules: [{ required: true, errorMessage: '请输入整改要求' }]
                }
            }
        },
    },
    data() {
        return {
            teams: [],//被检查班组选项
            departments: [],//被检查主管选项
            userOptions: [],//全部的人
            brigades: [],
            checkcheckedTeamIdOptions: [],
            // 表单数据
            formData: {
                // 基本信息
                checkerName: '',
                checkerId: '',
                frequency: '',
                problemDescription: '',
                checkedTeamId: '',
                checkLocation: '',
                checkTime: formatTime(new Date(), 'YYYY-MM-DD hh:mm:ss'),

                // 巡检项目
                baseAttachmentList: [],
                // 整改要求
                responsibleUserId: '',
                rectificationDeadline: '',
                rectificationSuggestions: ''
            },

            location_options: [],
            // 其他数据
            startDate: '2020-01-01',

            imageStyles: {
                width: 80,
                height: 80,
                border: {
                    color: '#eee',
                    width: '1px',
                    style: 'solid'
                }
            },
            taskId: '',
            type: '',
            deptTree: [],
            //被检查人的对象，在检查级别为班组的时候，需要塞到checkUserList里传给后端
            checkedUserObj: {}
        }
    },
    onLoad(options) {

        this.taskId = options.id; // 获取路由参数中的id
        this.type = options.type; // 获取路由参数中的type

        this.initPageData();
    },
    mounted() {


    },
    methods: {
        getDeptLeader() {
            selectDeptLeaderByUserId({
                userId: this.currentUser.id,
                deptType: 'DEPARTMENT'
            }).then(res => {

                if (res.code == 200) {
                    this.formData.responsibleUserId = res.data.userId;
                    this.formData.responsibleUserName = res.data.nickName;
                }
            })
        },
        // 被检查人选择
        handleCheckedSelect(e) {
            this.formData.checkedPersonnelId = e;
            let checkedUser = this.userOptions.find(item => item.userId == e);
            this.formData.checkedPersonnelName = checkedUser?.nickName;
            this.checkedUserObj = checkedUser;
        },
        // 继续提交
        handleContinueSubmit() {
            // 清空表单数据
            this.formData.checkedTeamId = '';
            this.formData.checkLocation = [];
            this.formData.checkTime = '';

            // 清空巡检项目数据
            if (this.formData.checkProjectItemList && this.formData.checkProjectItemList.length > 0) {
                this.formData.checkProjectItemList.forEach(group => {
                    if (group.children && group.children.length > 0) {
                        group.children.forEach(ele => {
                            // 清空检查人员列表
                            ele.checkUserList = [];
                            // 将评分等级设置为符合
                            ele.scoreLevel = 'QUALIFIED';
                        });
                    }
                });
            }

            // 清空附件列表
            this.formData.baseAttachmentList = [];

            // 清空整改要求数据
            this.formData.responsibleUserId = '';
            this.formData.rectificationDeadline = '';
            //  this.formData.rectificationSuggestions = '';
            this.$set(this.formData, 'rectificationSuggestions', '')

            // 重置相关字段
            this.formData.checkedTeamName = '';
            this.formData.responsibleUserName = '';
            this.formData.terminlName = '';
            this.formData.terminlCode = '';
            this.formData.regionalName = '';
            this.formData.regionalCode = '';
            this.formData.channelName = '';
            this.formData.channelCode = '';

            // 如果被检查主管有值，重新执行handlecheckedDepartmentIdChange
            if (this.formData.checkedDepartmentId) {
                this.handlecheckedDepartmentIdChange({
                    detail: {
                        value: [{
                            text: this.formData.checkedDepartmentName,
                            value: this.formData.checkedDepartmentId
                        }]
                    }
                });
            }

            // 重新赋值整改期限（当前时间加4天）
            const currentDate = new Date();
            currentDate.setDate(currentDate.getDate() + 4);
            const fourDaysLater = currentDate.toISOString().replace('T', ' ').substring(0, 19);
            this.formData.rectificationDeadline = fourDaysLater;

            console.log('表单已清空，可以继续提交新数据');
        },
        // 检查地点选择
        handleCheckLocationChange(e) {
            let res = e.detail.value;
            this.formData.terminlName = res[0]?.text;
            this.formData.terminlCode = res[0]?.value;
            this.formData.regionalName = res[1]?.text;
            this.formData.regionalCode = res[1]?.value;
            this.formData.channelName = res[2]?.text;
            this.formData.channelCode = res[2]?.value;
        },
        // 检查班组选择
        handlecheckedTeamIdChange(e) {
            const { text, value } = e.detail.value[0];
            let newText = text.split('/')
            this.$set(this.formData, 'checkedDeptId', value);
            this.$set(this.formData, 'checkedDeptName', newText[newText.length - 1].trim());
            this.$set(this.formData, 'checkedTeamName', newText[newText.length - 1]);

            // 在树状结构中查找指定id的上一级id
            const findParentIdInTree = (tree, targetId, parent = null) => {
                for (const node of tree) {
                    // 如果当前节点就是目标节点，返回父级信息
                    if (node.id === targetId) {
                        return parent ? {
                            label: parent.label,
                            id: parent.id
                        } : null;
                    }
                    // 如果当前节点有子节点，递归查找
                    if (node.children && node.children.length > 0) {
                        const result = findParentIdInTree(node.children, targetId, node);
                        if (result !== null) {
                            return result;
                        }
                    }
                }
                return null;
            };



            // 直接从teams数据中查找
            const { label, id } = findParentIdInTree(this.deptTree, value);


            // 如果有找到上一级DEPARTMENT对象，可以在这里使用它
            if (label && id) {
                // 可以根据需要将部门信息设置到formData中
                this.$set(this.formData, 'checkedDepartmentId', id);
                this.$set(this.formData, 'checkedDepartmentName', label.trim());
            } else {
                console.log('未找到符合条件的上一级DEPARTMENT对象');
            }

            getDeptManager(value).then(res => {
                console.log(res?.data?.userId, "111res")
                this.$set(this.formData, 'responsibleUserId', res?.data?.userId || '');
                this.$set(this.formData, 'responsibleUserName', res?.data?.nickName || '');
            })
        },
        // 检查科选择
        handlecheckedDepartmentIdChange(e) {

            const { text, value } = e.detail.value[0];

            let newText = text.split('/')
            this.$set(this.formData, 'checkedDeptId', value);
            this.$set(this.formData, 'checkedDeptName', newText[newText.length - 1].trim());
            this.$set(this.formData, 'checkedDepartmentName', newText[newText.length - 1].trim());
            getDeptManager(value).then(res => {
                console.log(res?.data?.userId, "111res")
                this.$set(this.formData, 'responsibleUserId', res?.data?.userId || '');
                this.$set(this.formData, 'responsibleUserName', res?.data?.nickName || '');
            })
        },
        handlecheckedBrigadeIdChange(e) {
            const { text, value } = e.detail.value[0];
            let newText = text.split('/')
            this.$set(this.formData, 'checkedBrigadeName', newText[newText.length - 1].trim());
            this.$set(this.formData, 'checkedDeptId', value);

            this.$set(this.formData, 'checkedDeptName', newText[newText.length - 1].trim());
            this.$set(this.formData, 'checkedDepartmentId', value);
            this.$set(this.formData, 'checkedDepartmentName', newText[newText.length - 1].trim());
            getDeptRoleUser(value, ['xingzheng']).then(res => {

                this.$set(this.formData, 'responsibleUserId', res?.data[0].userId || '');
                this.$set(this.formData, 'responsibleUserName', res?.data[0].nickName || '');
            })
        },
        // 加载字典数据
        async loadDictData() {
            const user = await listAllUser();
            this.userOptions = user.data.map(item => ({
                ...item,
                nickName: `${item.nickName}(${item.userName})`,
            })) || [];
            const deptTree = await getDeptList();
            this.deptTree = deptTree.data || [];
            this.teams = buildTeamOptions(deptTree.data || []);
            this.departments = buildManagerOptions(deptTree.data || []);
            this.brigades = buildBrigadeOptions(deptTree.data || []);
            console.log(this.departments, "this.departments")
            const [positionRes] = await Promise.all([
                treeSelectByType("POSITION", 3),
            ]);

            const convertTree = (list = []) =>
                list.map(node => ({
                    text: node.label,
                    value: node.code,
                    children: node.children ? convertTree(node.children) : null
                }))

            this.location_options = convertTree(positionRes.data || []);
            // console.log(this.location_options, this.teams)
            const dict = await this.useDict('check_checked_level');
            this.checkcheckedTeamIdOptions = dict.check_checked_level || [];
        },
        async initPageData() {
            try {
                uni.showLoading({ title: '加载中...', mask: true });

                // 如果有任务ID，获取巡检任务详情
                if (this.taskId) {
                    //如果是任务就调任务的详情接口，如果是检查单就调用检查单的接口
                    let api = this.type === 'task' ? getCheckTask : getInspectionListById;
                    const inspectionDetail = await api(this.taskId);
                    this.fillFormData(inspectionDetail);
                }
                await this.loadDictData();

                // // 获取部门列表
                // const deptTree = await getDeptList();
                // this.teams = this.buildDepartmentOptions(deptTree.data || []);

                // // 获取位置列表
                // const positionRes = await treeSelectByType("POSITION", 3);
                // this.location_options = this.convertTree(positionRes.data || []);

                uni.hideLoading();
            } catch (err) {
                uni.hideLoading();
                uni.showToast({ title: '加载失败', icon: 'none' });
                console.error('初始化数据失败:', err);
            }
        },
        // buildDepartmentOptions(tree = []) {
        //     const result = [];

        //     function dfs(node, path = []) {
        //         const currentPath = [...path, node.label];
        //         // 如果是部门或班组节点
        //         if (node.deptType === 'DEPARTMENT' || node.deptType === 'TEAMS') {
        //             result.push({
        //                 text: currentPath.join(' / '),
        //                 value: node.id
        //             });
        //         }
        //         // 继续递归子节点
        //         if (node.children && Array.isArray(node.children)) {
        //             node.children.forEach(child => dfs(child, currentPath));
        //         }
        //     }

        //     tree.forEach(root => dfs(root));
        //     return result;
        // },
        convertTree(list = []) {
            return list.map(node => ({
                text: node.label,
                value: node.code,
                children: node.children ? this.convertTree(node.children) : null
            }));
        },
        // 选择文件后手动上传
        async onSelect(event) {
            const files = await this.uploadFile(event);
            console.log(files, "file", this.formData)
            let fileArr = files.map(file => ({
                url: file.url,
                name: file.newFileName,
                attachmentName: file.newFileName,
                attachmentUrl: file.url,
                extname: file.newFileName.split('.').pop()
            }))
            // 直接替换而不是追加，因为限制只能上传1张
            this.formData.baseAttachmentList = [
                ...this.formData.baseAttachmentList,
                ...fileArr
            ];

        },
        // 封装上传
        uploadFile(event) {
            return Promise.all(event.tempFilePaths.map(filePath => {
                return new Promise((resolve, reject) => {
                    uni.uploadFile({
                        url: `${config.baseUrl}/common/upload`,
                        filePath: filePath,
                        name: 'file',
                        header: { Authorization: 'Bearer ' + getToken() },
                        formData: {
                            // 可添加其他参数
                        },
                        success: (res) => resolve(JSON.parse(res.data)),
                        fail: reject
                    });
                });
            }));
        },
        // 填充表单数据
        fillFormData(inspectionDetail) {
            if (!inspectionDetail || !inspectionDetail.data) return;

            const data = inspectionDetail.data;

            // 计算当前时间加4天
            const currentDate = new Date();
            currentDate.setDate(currentDate.getDate() + 4);
            const fourDaysLater = currentDate.toISOString().replace('T', ' ').substring(0, 19);

            // 按categoryCodeOne和categoryCodeTwo分组处理checkProjectItemList
            const groupedCheckProjectItemList = data.checkProjectItemList && data.checkProjectItemList.reduce((groups, item) => {
                const groupKey = `${item.categoryCodeOne}_${item.categoryCodeTwo}`;
                if (!groups[groupKey]) {
                    groups[groupKey] = {
                        categoryCodeOne: item.categoryCodeOne,
                        categoryCodeTwo: item.categoryCodeTwo,
                        categoryNameOne: item.categoryNameOne,
                        categoryNameTwo: item.categoryNameTwo,
                        children: []
                    };
                }
                groups[groupKey].children.push({
                    ...item,
                    scoreLevel: item.scoreLevel || 'QUALIFIED'
                });
                return groups;
            }, {});

            // 将分组对象转换为数组
            const checkProjectItemListArray = groupedCheckProjectItemList ? Object.values(groupedCheckProjectItemList) : [];

            // 填充基本信息
            this.formData = {
                ...data,
                checkTime: data.checkTime || formatTime(new Date(), 'YYYY-MM-DD hh:mm:ss'),
                checkerName: this.currentUser.userInfo.nickName || this.currentUser.userInfo.userName || '',
                checkerId: this.currentUser.userInfo.userId || '',
                rectificationDeadline: data.rectificationDeadline || fourDaysLater,
                baseAttachmentList: (data.baseAttachmentList && data.baseAttachmentList.map(item => ({
                    ...item,
                    url: item.attachmentUrl,
                    name: item.attachmentName,
                    extname: item.extname
                }))) || [],
                checkedTeamId: Number(data.checkedTeamId),
                checkLocation: [{ text: data.terminlName, value: data.terminlCode }, { text: data.regionalName, value: data.regionalCode }, { text: data.channelName, value: data.channelCode }],
                checkProjectItemList: checkProjectItemListArray
            }



            console.log(this.formData, "this.formData回显")
        },

        // 处理添加不合格人员
        handleAddPersonnel(index) {
            console.log('添加不合格人员，项目索引:', index);

            this.$nextTick(() => {
                this.$refs.xunjianCollapseItem.updateCollapseHeight();
            })
            // 这里可以打开人员选择弹窗或跳转到人员选择页面
            uni.showToast({ title: '打开人员选择', icon: 'none' });
        },

        // 处理人员数据变更
        handlePersonnelChange(changeData) {
            const { parentIndex, childIndex, personnelData, problemDescription } = changeData;
            console.log(personnelData, "personnelData")
            if (parentIndex >= 0 && childIndex >= 0 &&
                this.formData.checkProjectItemList &&
                this.formData.checkProjectItemList[parentIndex] &&
                this.formData.checkProjectItemList[parentIndex].children &&
                this.formData.checkProjectItemList[parentIndex].children[childIndex]) {

                // 更新对应子项目的检查人员列表和任务简介
                this.formData.checkProjectItemList[parentIndex].children[childIndex].checkUserList = personnelData;
                this.formData.checkProjectItemList[parentIndex].children[childIndex].problemDescription = problemDescription;
                console.log('更新不合格人员数据:', parentIndex, childIndex, personnelData, problemDescription);
            }
        },

        // 处理用户选择
        handleUserSelect(value) {

            const selectedUser = this.userOptions.find(user => user.userId === value);

            if (selectedUser) {
                this.formData.responsibleUserId = selectedUser.userId;
                this.formData.responsibleUserName = selectedUser.nickName;
            }
        },
        formateData() {
            let checkedUserObj = {}
            if (JSON.stringify(this.checkedUserObj) !== '{}') {
                checkedUserObj = {
                    ...this.checkedUserObj,
                    userName: this.checkedUserObj.nickName.split('(')[0] || '',
                }
            }


            const originalCheckProjectItemList = this.formData.checkProjectItemList
                ? this.formData.checkProjectItemList.flatMap(group =>
                    group.children.map(child => ({
                        ...child,
                        categoryCodeOne: group.categoryCodeOne,
                        categoryCodeTwo: group.categoryCodeTwo,
                        categoryNameOne: group.categoryNameOne,
                        categoryNameTwo: group.categoryNameTwo,
                        //如果是班组，自动赋值被检查人给checkUserList
                        ...(this.formData.checkLevel == 'TEAM_LEVEL' && child.scoreLevel == "UNQUALIFIED" ? { checkUserList: [checkedUserObj] } : {}),
                    }))
                )
                : [];

            let payload = {
                ...this.formData,
                checkedTeamName: (this.formData.checkedTeamName || '').trim(),
                checkProjectItemList: originalCheckProjectItemList
            };

            delete payload.id;
            console.log(payload, "payload")
            // debugger
            return payload;
        },
        // 保存草稿
        saveDraft() {
            // this.$refs.form.validate().then(res => {
            uni.showLoading({ title: '保存中...', mask: true });


            const payload = this.formateData();


            addDraftInspection({ ...payload, ...(this.formData.checkRecordStatus == 'DRAFT' ? { id: this.taskId } : {}) })
                .then(() => {
                    uni.showToast({ title: '草稿保存成功', icon: 'success' });
                    console.log('草稿保存成功:',);
                    setTimeout(() => uni.navigateBack(), 1500);
                })
                .catch((error) => {
                    uni.showToast({ title: '草稿保存失败，请稍后重试！', icon: 'none' });
                    console.error('草稿保存失败:', error);
                });

            // }).catch(err => {
            //     console.log('表单验证失败:', err);
            //     uni.showToast({ title: '请填写完整表单信息', icon: 'none' });
            // });
        },

        // 提交表单
        submitForm() {
            this.$refs.form.validate().then(res => {
                debugger
                // 检查所有不合格项是否都填写了相关人员
                let hasError = false;
                let errorMessage = '';
                //被检查级别科 班组
                if (this.formData.checkProjectItemList && this.formData.checkProjectItemList.length > 0 && this.getCheckLabel != '被检查人') {
                    for (let groupIndex = 0; groupIndex < this.formData.checkProjectItemList.length; groupIndex++) {
                        const group = this.formData.checkProjectItemList[groupIndex];
                        if (group.children && group.children.length > 0) {
                            for (let itemIndex = 0; itemIndex < group.children.length; itemIndex++) {
                                const item = group.children[itemIndex];
                                if (item.scoreLevel === 'UNQUALIFIED' &&
                                    ((!item.checkUserList || item.checkUserList.length === 0) && (!item.problemDescription || item.problemDescription.trim() === ''))) {
                                    hasError = true;
                                    errorMessage = `第${groupIndex + 1}组项目 "${item.projectName}" 标记为不符合，请选择相关人员或填写问题描述`;
                                    break;
                                }
                            }
                            if (hasError) break;
                        }
                    }
                }

                // 如果有错误，弹出提示并阻止提交
                if (hasError) {
                    uni.showToast({ title: errorMessage, icon: 'none' });
                    return;
                }

                // 验证通过，继续提交
                uni.showLoading({ title: '提交中...', mask: true });

                const payload = this.formateData();
                debugger

                submitInspection({ ...payload, ...(this.type == 'task' ? {} : { id: this.taskId }) })
                    .then(() => {
                        uni.showToast({ title: '提交成功', icon: 'success' });
                        this.$refs.submitResult.open();
                    })
                    .catch((error) => {
                        uni.showToast({ title: '操作失败，请稍后重试！', icon: 'none' });
                        console.error('提交失败:', error);
                    });

            }).catch(err => {
                console.log('表单验证失败:', err);
                uni.showToast({ title: '请填写完整表单信息', icon: 'none' });
            });
        }

    }
}
</script>

<style lang="scss" scoped>
.report-container {
    min-height: 100vh;
    padding-top: 35px;

    .card {
        border-radius: 8px;
        margin: 15px 0;
        overflow: hidden;
        box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;
    }
}

/* 折叠面板标题 */
.collapse-title {
    display: flex;
    flex-direction: column;
    padding: 12px 15px;

    .collapse-summary {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
    }
}

/* 表单项样式 */
::v-deep .uni-forms-item {
    margin-bottom: 0;
    padding: 0 15px;

    .uni-forms-item__label {
        padding: 12px 0 8px;
        font-size: 14px;
        color: #666;
        width: auto !important;
    }

    .uni-forms-item__content {
        padding: 0 0 12px;
        border-bottom: 1px solid #f0f0f0;
    }

    &:last-child .uni-forms-item__content {
        border-bottom: none;
    }
}

.submit-btn {
    margin-top: 20px;
    width: calc(100% - 30px);
    margin-left: 15px;
}

/* 底部弹窗样式调整 */
::v-deep .uni-popup__wrapper {
    border-radius: 16px 16px 0 0;

    .uni-popup__wrapper-box {
        max-height: 70vh;
        overflow-y: auto;
    }

    .uni-data-pickerview {
        padding-bottom: 20px;
    }
}

:v-deep .uni-input-input:disabled {
    background-color: #f5f5f5;
}

/* 巡检项目卡片样式 */
.item-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    font-size: 16px;
    font-weight: bold;
    color: #333;
}

.item-content {
    margin-top: 12px;

    .item-description {
        display: flex;
        flex-direction: column;

        .description-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 4px;
        }

        .description-text {
            font-size: 14px;
            color: #333;
            line-height: 1.5;
        }
    }
}

.upload-section {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;

    .upload-title {
        display: block;
        font-size: 16px;
        font-weight: bold;
        color: #333;
        margin-bottom: 12px;
    }
}

/* 按钮组样式 - 左右布局 */
.button-group {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
    margin-top: 20px;
    gap: 15px;
}

.button-group .custom-btn-white,
.button-group .custom-btn-normal {
    flex: 1;
    margin-top: 0;
    width: auto;
}
</style>