<template>
    <home-container>
        <view class="report-container">
            <!-- 表单区域 -->
            <uni-forms ref="form" :rules="rules" :modelValue="formData" label-position="top" err-show-type="modal">
                <!-- 1. 基本信息分组 (默认展开) -->
                <view class="card">
                    <uni-collapse :accordion="false" :value="['group1']">
                        <h-collapse-item title="基本信息" name="group1" :show-animation="true"
                            :iconUrl="'../../static/images/icon/jiben.png'">
                            <uni-forms-item label="任务编号" name="taskCode">
                                <uni-easyinput v-model="formData.taskCode" placeholder="系统自动生成" disabled />
                            </uni-forms-item>
                            <uni-forms-item label="巡检编号" name="documentCode">
                                <uni-easyinput v-model="formData.documentCode" placeholder="系统自动生成" disabled />
                            </uni-forms-item>

                            <uni-forms-item label="检查人" name="checkerName">
                                <uni-easyinput v-model="formData.checkerName" placeholder="请输入检查人姓名" disabled />
                            </uni-forms-item>

                            <uni-forms-item :label="getCheckLabel" name="checkedDepartmentId">
                                <uni-data-picker v-if="getCheckLabel == '被检查科'" :localdata="departments"
                                    :popup-title="`请选择${getCheckLabel}`" v-model="formData.checkedDepartmentId"
                                    :readonly="true" />
                                <uni-data-picker v-if="getCheckLabel == '被检查大队'" :localdata="brigades"
                                    :popup-title="`请选择${getCheckLabel}`" v-model="formData.checkedBrigadeId"
                                    :readonly="true" />
                                <uni-data-picker v-if="getCheckLabel == '被检查班组'" :localdata="teams"
                                    :popup-title="`请选择${getCheckLabel}`" v-model="formData.checkedTeamId"
                                    :readonly="true" />
                                <fuzzy-select v-if="getCheckLabel == '被检查人'" v-model="formData.checkedPersonnelId"
                                    :options="userOptions" placeholder="请输入被检查人姓名搜索" data-value="userId"
                                    data-text="nickName" disabled />
                            </uni-forms-item>

                            <uni-forms-item label="检查时间" name="checkTime">
                                <uni-datetime-picker type="datetime" :start="startDate" :end="endDate"
                                    v-model="formData.checkTime" disabled />
                            </uni-forms-item>

                            <uni-forms-item label="检查位置" name="checkLocation">
                                <uni-easyinput v-model="formData.checkLocation" placeholder="请选择检查位置" disabled />
                            </uni-forms-item>
                        </h-collapse-item>
                    </uni-collapse>
                </view>

                <!-- 2. 待整改问题分组 -->
                <view class="card">
                    <uni-collapse :accordion="false" :value="['group2']">
                        <h-collapse-item title="待整改问题" name="group2" :show-animation="true"
                            :iconUrl="'../../static/images/icon/wenti.png'">
                            <view style="padding: 0 15px 15px 15px;">
                                <!-- 问题列表遍历 -->
                                <view v-for="(problem, index) in formData.checkProjectItemList" :key="problem.id"
                                    class="problem-item">
                                    <view class="problem-header">
                                        <text class="problem-title">{{
                                            `${problem.categoryNameOne}/${problem.categoryNameTwo}/${problem.projectName}`
                                        }}</text>
                                    </view>
                                    <view class="problem-content">
                                        <view class="problem-person">
                                            <view class="problem-label"><text v-if="isResponsiblePerson"
                                                    style="color: red;">*</text>问题人<text
                                                    style="color: red;margin-left: 10rpx;">请确定问题人</text></view>

                                            <fuzzy-select :value="getCheckUserListValue(problem.checkUserList)"
                                                :options="userOptions" :placeholder="'请输入问题' + (index + 1) + '的责任人'"
                                                data-value="userId" data-text="nickName"
                                                @input="handleUserInput(index, $event)"
                                                @change="handleUserSelect($event, index)"
                                                @delete="handleUserDelete(index)" :disabled="formDisabled" />
                                        </view>
                                        <view class="problem-description">
                                            <text class="problem-label">问题描述</text>
                                            <uni-easyinput type="textarea" v-model="problem.problemDescription"
                                                :disabled="true" />
                                        </view>
                                    </view>
                                </view>

                                <uni-file-picker v-if="formData.checkRecordBaseAttachmentList.length > 0"
                                    v-model="formData.checkRecordBaseAttachmentList" limit="8" title="最多上传8张"
                                    :image-styles="imageStyles" fileMediatype="image" mode="grid"
                                    @select="onCheckRecordBaseAttachmentListSelect" :disabled="true" :del-icon="false"
                                    :readonly="true" />
                            </view>
                        </h-collapse-item>
                    </uni-collapse>
                </view>

                <!-- 3. 整改要求分组 -->
                <view class="card">
                    <uni-collapse :accordion="false" :value="['group3']">
                        <h-collapse-item title="整改要求" name="group3" :show-animation="true"
                            :iconUrl="'../../static/images/icon/yaoqiu.png'">
                            <uni-forms-item label="责任人" name="responsibleUserName" required>
                                <uni-easyinput v-model="formData.responsibleUserName" placeholder="请输入责任人姓名" disabled />
                            </uni-forms-item>

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


                            <!-- 是否流转至班组 -->
                            <uni-forms-item
                                v-if="nodeCode === 'SECTION_LEADER_APPROVE' && businessType === 'SECTION_CHECK'"
                                label="是否流转至班组" name="isSelectTeam">
                                <radio-group @change="handleIsSelectTeamChange" class="radio-group">
                                    <label class="radio-item">
                                        <radio :value="'0'" :checked="formData.isSelectTeam == 0" color="#409EFF" />
                                        <text>否</text>
                                    </label>
                                    <label class="radio-item">
                                        <radio :value="'1'" :checked="formData.isSelectTeam == 1" color="#409EFF" />
                                        <text>是</text>
                                    </label>
                                </radio-group>
                            </uni-forms-item>

                            <!-- 整改班组 -->
                            <uni-forms-item
                                v-if="nodeCode === 'SECTION_LEADER_APPROVE' && businessType === 'SECTION_CHECK' && formData.isSelectTeam == 1"
                                label="整改班组" name="selectTeamId">
                                <uni-data-picker :localdata="teams" popup-title="请选择整改班组"
                                    v-model="formData.selectTeamId" @change="handlecheckedTeamIdChange" />
                            </uni-forms-item>

                            <!-- 班组长 -->
                            <uni-forms-item
                                v-if="nodeCode === 'SECTION_LEADER_APPROVE' && businessType === 'SECTION_CHECK' && formData.isSelectTeam == 1"
                                label="班组长" name="selectTeamLeaderName">
                                <uni-easyinput v-model="formData.selectTeamLeaderName" placeholder="班组长" disabled />
                            </uni-forms-item>

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

                        </h-collapse-item>
                    </uni-collapse>
                </view>

                <!-- 4. 整改信息分组 -->
                <view class="card">
                    <uni-collapse :accordion="false" :value="['group4']">
                        <h-collapse-item title="整改信息" name="group4" :show-animation="true"
                            :iconUrl="'../../static/images/icon/zhenggai.png'">
                            <uni-forms-item label="整改详情" name="rectificationDetails"
                                :required="rectificationDetailsRequired">
                                <uni-easyinput type="textarea" v-model="formData.rectificationDetails"
                                    placeholder="请输入整改详情" :disabled="formDisabled" />
                            </uni-forms-item>

                            <view style="padding: 0 15px 15px 15px;">
                                <uni-file-picker v-model="formData.baseAttachmentList" limit="8" title="最多上传8张整改照片"
                                    :image-styles="imageStyles" fileMediatype="image" mode="grid"
                                    @select="onBaseAttachmentListelect" :disabled="formDisabled"
                                    :del-icon="!formDisabled" :readonly="formDisabled" />
                            </view>
                        </h-collapse-item>
                    </uni-collapse>
                </view>

                <!-- 5. 审批历史分组 -->
                <view class="card">
                    <uni-collapse :accordion="false" :value="['group5']">
                        <h-collapse-item title="审批历史" name="group5" :show-animation="true"
                            :iconUrl="'../../static/images/icon/lishi.png'">
                            <approve-history :history-list="approvalHistory" />
                        </h-collapse-item>
                    </uni-collapse>
                </view>

                <!-- 提交按钮 -->
                <view class="button-group" v-if="type === 'approve'">
                    <!-- <view v-if="btnPermission.showSubmitBtn" class="custom-btn-normal" @click="submitForm">立刻提交
                    </view> -->
                    <RejectModal v-if="btnPermission.showApproveRejectBtn" @confirm="handleRejectConfirm">
                        <view class="custom-btn-white">
                            驳回/退回
                        </view>
                    </RejectModal>

                    <view v-if="btnPermission.showApprovePassBtn" class="custom-btn-normal" @click="submitForm">{{
                        nodeCode == 'START' ? '提交' : '通过/提交' }}
                    </view>
                </view>
            </uni-forms>
        </view>
    </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import { treeSelectByType } from "@/api/system/common"
import { uploadFile } from '@/utils/common'
import useDictMixin from '@/utils/dict'
import RejectModal from './components/RejectModal.vue'
import { addChecklistRecord } from '@/api/check/checklist.js'
import config from '@/config'
import { getToken } from '@/utils/auth'
import { checkedLevelEnums } from "@/utils/enums.js"
import { getDeptList } from "@/api/system/dept/dept.js"
import { selectDeptLeaderByUserId } from '@/api/approve/approve.js'
import { formatTime } from '@/utils/formatUtils'
import { listAllUser } from "@/api/system/user.js"
import { getProblemRectDetail, approvalAgree, approvalReject } from '@/api/problemRect/problemRect.js'
import { getApprovelHistory } from '@/api/approve/approve.js'
import { getDeptManager, getDeptDetail } from "@/api/system/dept/dept.js"
import { buildTeamOptions, buildDepartmentOptions, buildBrigadeOptions } from "@/utils/common.js"
export default {
    components: { HomeContainer, RejectModal },
    mixins: [useDictMixin],
    computed: {
        currentUser() {
            return this.$store.state.user;
        },
        currentUserId() {
            return this.currentUser && this.currentUser.id;
        },
        //表单责任人是当前登陆人
        isResponsiblePerson() {
            return this.currentUserId == this.formData.responsibleUserId;
        },
        userInfo() {
            return (this.$store.state.user && this.$store.state.user.userInfo) ? this.$store.state.user.userInfo : {}
        },
        userInfoRoles() {
            return this.$store.state.user && this.$store.state.user.roles
        },
        // 按钮权限判断
        btnPermission() {
            const roles = this.userInfoRoles || [];
            return {
                // 班组长或安全检查员显示"立刻提交"按钮
                showApprovePassBtn: ['SECTION_LEADER_APPROVE', 'GROUP_LEADER_RECTIFY', 'INITIATOR_FINAL_REVIEW', 'RESPONSIBLE_PERSON_REVIEW'].includes(this.nodeCode) || (this.businessType == 'PERSONAL_CHECK' && ['INITIATOR_REVIEW', 'PROBLEM_USER_RECTIFY'].includes(this.nodeCode)) || (this.businessType == 'GROUP_CHECK' && ['SECTION_REVIEW'].includes(this.nodeCode)) || this.nodeCode == 'START',
                showApproveRejectBtn: ['GROUP_LEADER_RECTIFY', 'INITIATOR_FINAL_REVIEW', 'RESPONSIBLE_PERSON_REVIEW'].includes(this.nodeCode) || (this.businessType == 'PERSONAL_CHECK' && ['INITIATOR_REVIEW', 'SECTION_LEADER_APPROVE'].includes(this.nodeCode)) || (this.businessType == 'GROUP_CHECK' && ['SECTION_REVIEW'].includes(this.nodeCode)),
            };
        },
        formDisabled() {
            return this.type === 'view';
        },
        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 '被检查大队'
            }
        },
        // 动态验证规则
        rules() {
            return {
                checkerName: {
                    rules: [{ required: true, errorMessage: '请输入检查人姓名' }]
                },
                checkTime: {
                    rules: [{ required: true, errorMessage: '请选择检查时间' }]
                },
                checkLocation: {
                    rules: [{ required: true, errorMessage: '请选择检查位置' }]
                },
                rectificationDetails: {
                    rules: this.rectificationDetailsRequired ? [{ required: true, errorMessage: '请输入整改详情' }] : []
                },
                isSelectTeam: {
                    rules: [{ required: true, errorMessage: '请选择是否流转至班组' }]
                },
                selectTeamId: {
                    rules: [{ required: true, errorMessage: '请选择整改班组' }]
                }
            };
        },
        rectificationDetailsRequired() {
            //科长并且是责任人节点，并且是否流转至班组长为是，整改详情不必填，为否，整改详情必填;或者是班组长节点，也必填
            let res1 = this.formData.checkedLevel == 'DEPARTMENT_LEVEL' && ((this.nodeCode == 'SECTION_LEADER_APPROVE' && this.formData.isSelectTeam !== 1) || this.nodeCode == 'GROUP_LEADER_RECTIFY');
            // 班组长并且是责任人节点,必填
            let res2 = this.formData.checkedLevel == 'TEAM_LEVEL' && this.nodeCode == 'GROUP_LEADER_RECTIFY';
            //个人
            let res3 = this.formData.checkedLevel == 'PERSONNEL_LEVEL' && this.nodeCode == 'PROBLEM_USER_RECTIFY';
            return res1 || res2 || res3 || this.isResponsiblePerson
        },
    },
    data() {
        return {
            userOptions: [],
            teams: [], // 班组选项数据
            departments: [], // 部门选项数据
            brigades: [], // 大队选项数据
            // 表单数据
            formData: {
                // 基本信息
                taskCode: "",
                checkerName: '',

                checkLocation: '',
                // 待整改问题
                baseAttachmentList: [],
                checkRecordBaseAttachmentList: [],
                // 整改要求
                responsibleUserName: '',
                rectificationDeadline: '',
                rectificationSuggestions: '',
                isSelectTeam: 0, // 是否流转至班组 0-否 1-是
                selectTeamId: '', // 整改班组ID
                selectTeamName: '', // 整改班组名称
                selectTeamLeaderId: '', // 班组长ID
                selectTeamLeaderName: '', // 班组长姓名

                // 被检查对象相关字段
                checkedBrigadeId: '', // 被检查大队ID
                checkedBrigadeName: '', // 被检查大队名称

                // 整改信息
                rectificationDetails: '',
                baseAttachmentList: []
            },
            // 审批历史数据
            approvalHistory: [],
            // 数据选项
            location_options: [],
            // 其他数据
            startDate: '2020-01-01',
            endDate: '2030-12-31',
            imageStyles: {
                width: 80,
                height: 80,
                border: {
                    color: '#eee',
                    width: '1px',
                    style: 'solid'
                }
            },
            dataOptionMap: { text: 'label', value: 'value' },
            businessId: '',
            instanceId: '',
            id: '',
            nodeCode: '',
            type: '',
            businessType: '',
        }
    },
    onLoad(options) {
        let params = JSON.parse(decodeURIComponent(options.params));
        this.businessId = params.businessId;
        this.instanceId = params.instanceId;
        this.id = params.id;
        this.nodeCode = params.nodeCode;
        this.type = params.type;
        this.businessType = params.businessType;
        this.initPageData();
    },
    mounted() {
        this.loadDictData();
        console.log(this.$store.state.user)
    },
    methods: {
        handleUserSelect(e, index) {
            const person = this.userOptions.find(item => item.userId == e)
            if (this.formData.checkProjectItemList && this.formData.checkProjectItemList[index]) {
                this.formData.checkProjectItemList[index].checkUserList = person;
            }
        },

        // 获取checkUserList的值，处理null情况
        getCheckUserListValue(checkUserList) {
            return checkUserList && checkUserList.userId ? checkUserList.userId : '';
        },

        // 处理用户输入
        handleUserInput(index, value) {
            if (this.formData.checkProjectItemList && this.formData.checkProjectItemList[index]) {
                if (!this.formData.checkProjectItemList[index].checkUserList) {
                    this.formData.checkProjectItemList[index].checkUserList = {};
                }
                this.formData.checkProjectItemList[index].checkUserList.userId = value;
            }
        },

        // 处理用户删除
        handleUserDelete(index) {
            // 将problem.checkUserList置为null
            if (this.formData.checkProjectItemList && this.formData.checkProjectItemList[index]) {
                this.formData.checkProjectItemList[index].checkUserList = null;
                // 强制更新视图以确保fuzzy-select组件重新渲染
                this.$nextTick(() => {
                    this.$forceUpdate();
                });
            }
        },
        // 被检查大队选择
        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, 'checkedBrigadeId', value);
        },
        async loadDictData() {
            const user = await listAllUser();
            this.userOptions = user.data.map(item => ({
                ...item,
                nickName: `${item.nickName}(${item.userName})`,
            })) || [];
        },


        async initPageData() {
            try {
                uni.showLoading({ title: '加载中...', mask: true });

                // 如果有ID，获取问题整改详细信息
                if (this.businessId) {
                    const detailRes = await getProblemRectDetail(this.businessId);
                    if (detailRes.code === 200 && detailRes.data) {
                        this.fillFormData(detailRes.data);
                    }

                    // 获取审批历史
                    const historyRes = await getApprovelHistory(this.instanceId);

                    if (historyRes.code === 200 && historyRes.rows) {
                        this.approvalHistory = historyRes.rows;
                    }
                }

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

                // 获取班组列表
                const deptTree = await getDeptList();
                this.teams = buildTeamOptions(deptTree.data || []);
                this.departments = buildDepartmentOptions(deptTree.data || []);
                this.brigades = buildBrigadeOptions(deptTree.data || []);
                uni.hideLoading();
            } catch (err) {
                uni.hideLoading();
                uni.showToast({ title: '加载失败', icon: 'none' });
                console.error('初始化数据失败:', err);
            }
        },

        // 填充表单数据
        async fillFormData(data) {
            console.log(data, "data")
            // debugger
            let checedProjectArr = [];
            if (data.checkProjectItemList && data.checkProjectItemList?.length > 0) {
                if (this.businessType == 'PERSONAL_CHECK' && this.nodeCode == 'SECTION_LEADER_APPROVE') {
                    // let res = await selectDeptLeaderByUserId({
                    //     userId: data.checkedPersonnelId,
                    //     deptType: 'TEAMS'
                    // })
                    // let dept = {}
                    // if (res.code == 200) {
                    //     dept = res.data || {};
                    // }
                    // let res1 = await getDeptDetail(dept.deptId)
                    // if (res1.code == 200) {
                    //     console.log(res1, "res1")
                    //     debugger
                    // }
                    data.checkProjectItemList = data.checkProjectItemList.map(item => ({
                        ...item,
                        checkUserList: [{ userName: data.checkedPersonnelName, userId: data.checkedPersonnelId, }]
                    }))
                    console.log(data.checkProjectItemList, "data.checkProjectItemList")
                    data.checkProjectItemList.forEach(element => {

                        if (element.checkUserList && element.checkUserList?.length > 0) {
                            element.checkUserList.forEach(user => {
                                checedProjectArr.push({
                                    ...element,
                                    checkUserList: user
                                })
                            });
                        }
                    });
                } else {
                    data.checkProjectItemList.forEach(element => {
                        if (element.checkUserList && element.checkUserList?.length > 0) {
                            element.checkUserList.forEach(user => {
                                checedProjectArr.push({
                                    ...element,
                                    checkUserList: user
                                })
                            });
                        } else {
                            checedProjectArr.push({
                                ...element,
                                checkUserList: { userId: "" }
                            })
                        }
                    });
                }

            }
            console.log(checedProjectArr, "checedProjectArr")
            //    debugger

            this.formData = {
                ...this.formData,
                ...data,
                checkLocation: `${data.terminlName}/${data.regionalName}/${data.channelName}`,
                baseAttachmentList: data.baseAttachmentList?.length ? data.baseAttachmentList.map(img => ({
                    ...img,
                    url: img.attachmentUrl || img.url,
                    name: img.attachmentName || img.name,
                    extname: img.extname || (img.name ? img.name.split('.').pop() : '')
                })) : [],
                baseAttachmentList: (data.baseAttachmentList && data.baseAttachmentList?.length > 0) ? data.baseAttachmentList.map(img => ({
                    ...img,
                    url: img.attachmentUrl || img.url,
                    name: img.attachmentName || img.name,
                    extname: img.extname || (img.name ? img.name.split('.').pop() : '')
                })) : [],
                checkProjectItemList: checedProjectArr,
                approvalHistory: (data.approvalHistory && data.approvalHistory?.length > 0) ? data.approvalHistory.map(item => ({
                    name: item.name || '未知用户',
                    date: item.date || new Date().toISOString().split('T')[0],
                    content: item.content || '无审批内容'
                })) : [],
            }
        },

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

        // 选择待整改问题图片
        async onBaseAttachmentListelect(event) {
            const file = await uploadFile(event);
            this.formData.baseAttachmentList.push({
                url: file.url,
                name: file.newFileName,
                attachmentName: file.newFileName,
                attachmentUrl: file.url,
                extname: file.newFileName.split('.').pop()
            });
        },

        // 选择不合格图片
        async onCheckRecordBaseAttachmentListSelect(event) {
            const file = await uploadFile(event);
            this.formData.checkRecordBaseAttachmentList.push({
                url: file.url,
                name: file.newFileName,
                attachmentName: file.newFileName,
                attachmentUrl: file.url,
                extname: file.newFileName.split('.').pop()
            });
        },


        formatDateTime(date) {
            const y = date.getFullYear();
            const m = String(date.getMonth() + 1).padStart(2, '0');
            const d = String(date.getDate()).padStart(2, '0');
            const h = String(date.getHours()).padStart(2, '0');
            const mm = String(date.getMinutes()).padStart(2, '0');
            const s = String(date.getSeconds()).padStart(2, '0');
            return `${y}-${m}-${d} ${h}:${mm}:${s}`;
        },
        handleRejectConfirm(reason) {
            this.formData.comment = reason
            this.rejectForm()
        },
        rejectForm() {
            // this.$refs.form.validate().then(res => {
            uni.showLoading({ title: '提交中...', mask: true });

            // 还原checkProjectItemList结构到后端原始格式
            const restoredCheckProjectItemList = this.restoreOriginalCheckProjectItemList();

            const payload = {
                ...this.formData,
                checkProjectItemList: restoredCheckProjectItemList,
                taskId: this.id,
                instanceId: this.instanceId,
            };

            approvalReject(payload)
                .then(() => {
                    uni.showToast({ title: '提交成功', icon: 'success' });
                    setTimeout(() => uni.navigateBack(), 1500);
                })
                .catch((error) => {
                    uni.showToast({ title: '操作失败，请稍后重试！', icon: 'none' });
                    console.error('提交失败:', error);
                });

            // }).catch(err => {
            //     console.log('表单验证失败:', err);
            // });
        },

        // 提交表单
        submitForm() {
            debugger
            // 如果当前用户是责任人，校验问题人字段必填
            if (this.isResponsiblePerson) {
                const hasEmptyProblemUser = this.formData.checkProjectItemList?.some(problem =>
                    !problem.checkUserList || !problem.checkUserList.userId
                );

                if (hasEmptyProblemUser) {
                    uni.showToast({
                        title: '请填写所有问题的问题人',
                        icon: 'none',
                        duration: 3000
                    });
                    return;
                }
            }

            this.$refs.form.validate().then(res => {
                uni.showLoading({ title: '提交中...', mask: true });

                // 还原checkProjectItemList结构到后端原始格式
                const restoredCheckProjectItemList = this.restoreOriginalCheckProjectItemList();

                const payload = {
                    ...this.formData,
                    checkProjectItemList: restoredCheckProjectItemList,
                    taskId: this.id,
                    instanceId: this.instanceId,
                    comment: '审批通过'
                };

                approvalAgree(payload)
                    .then(() => {
                        uni.showToast({ title: '提交成功', icon: 'success' });
                        setTimeout(() => uni.navigateBack(), 1500);
                    })
                    .catch((error) => {
                        uni.showToast({ title: '操作失败，请稍后重试！', icon: 'none' });
                        console.error('提交失败:', error);
                    });

            }).catch(err => {
                console.log('表单验证失败:', err);
            });
        },

        // 处理是否流转至班组选择
        handleIsSelectTeamChange(e) {
            const selectedValue = parseInt(e.detail.value);
            this.$set(this.formData, 'isSelectTeam', selectedValue);

            // 如果选择"否"，清空班组相关字段
            if (selectedValue === 0) {
                this.$set(this.formData, 'selectTeamId', '');
                this.$set(this.formData, 'selectTeamName', '');
                this.$set(this.formData, 'selectTeamLeaderId', '');
                this.$set(this.formData, 'selectTeamLeaderName', '');
            }
        },

        // 处理整改班组选择
        handlecheckedTeamIdChange(e) {

            const { text, value } = e.detail.value[0];
            this.$set(this.formData, 'selectTeamName', text);
            this.$set(this.formData, 'selectTeamId', value);

            // 获取班组长信息
            getDeptManager(value).then(res => {
                console.log(res?.data?.userId, "班组长信息");
                this.$set(this.formData, 'selectTeamLeaderId', res?.data?.userId || '');
                this.$set(this.formData, 'selectTeamLeaderName', res?.data?.nickName || '');
            }).catch(err => {
                console.error('获取班组长信息失败:', err);
                this.$set(this.formData, 'selectTeamLeaderId', '');
                this.$set(this.formData, 'selectTeamLeaderName', '');
            });
        },

        // 还原checkProjectItemList到后端原始格式
        restoreOriginalCheckProjectItemList() {
            const groupedItems = {};

            // 按照原始问题项分组
            this.formData.checkProjectItemList?.forEach(item => {
                const key = `${item.categoryCodeOne}-${item.categoryCodeTwo}-${item.problemDescription}`;
                if (!groupedItems[key]) {
                    groupedItems[key] = {
                        ...item,
                        checkUserList: []
                    };
                }

                // 将用户对象添加到checkUserList数组中
                if (item.checkUserList && typeof item.checkUserList === 'object') {
                    groupedItems[key].checkUserList.push(item.checkUserList);
                }
            });

            return Object.values(groupedItems);
        }
    }
}
</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;
    }
}

/* 审批历史样式 */
.approval-history {
    padding: 15px;

    .approval-item {
        display: flex;
        // margin-bottom: 20px;

        &:last-child {
            margin-bottom: 0;
        }

        .timeline {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-right: 12px;

            .circle {
                width: 12px;
                height: 12px;
                border-radius: 50%;
                background-color: #409EFF;
                border: 2px solid #fff;
                box-shadow: 0 0 0 2px #409EFF;
            }

            .line {
                width: 2px;
                flex: 1;
                background-color: #409EFF;
                margin-top: 4px;
            }
        }

        .content {
            flex: 1;
            position: relative;
            bottom: 8rpx;

            .header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 8px;

                .name {
                    font-size: 14px;
                    font-weight: 500;
                    color: #333;
                }

                .date {
                    font-size: 12px;
                    color: #999;
                }
            }

            .approval-content {
                font-size: 13px;
                color: #666;
                border: 1px solid #DDDDDD;
                line-height: 1.5;
                background-color: #f8f9fa;
                padding: 10px;
                border-radius: 6px;

            }
        }
    }
}

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

/* 按钮组样式 - 左右布局 */
.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;
}

/* 问题列表样式 */
.problem-item {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px dashed #e0e0e0;
}

.problem-item:last-child {
    border-bottom: none;
    margin-bottom: 15px;
}

.problem-header {
    margin-bottom: 12px;
}

.problem-title {
    font-size: 16px;
    font-weight: 600;
    color: #626FF0;
}

.problem-content {}

.problem-person,
.problem-description {
    margin-bottom: 12px;
}

.problem-label {
    display: block;
    font-size: 14px;
    color: #606266;
    margin-bottom: 6px;
    font-weight: 500;
}

.problem-description ::v-deep .uni-textarea__textarea {
    background-color: #f5f7fa !important;
    color: #909399 !important;
    cursor: not-allowed !important;
}
</style>