<template>
  <home-container>
    <view class="report-container">
      <!-- 表单区域 -->
      <uni-forms ref="form" :rules="rules" :modelValue="formData" label-position="top" err-show-type="modal">
        <!-- <scroll-view class="form-scroll" scroll-y> -->
        <!-- 安检员信息分组 (默认折叠) -->
        <!-- <view class="card" style="overflow: visible;"> -->
        <uni-collapse class="collapse" :class="firstCollapsed.length > 0 ? 'collapse-card' : 'collapse-card-hidden'"
          :accordion="false" v-model="firstCollapsed" @change="changeCollapse">
          <uni-collapse-item class="collapse-item" title="安检员信息" name="group1" :show-animation="true">
            <template v-slot:title>
              <view class="header-section collapse-title userInfo">
                <view class="userName">{{ `${type !== 'add' ? '查获人:' : ''}` }}{{ type !==
                  'add' ? `${formData.inspectUserName}（${formData.createBy}）` :
                  `${userInfo.nickName}（${userInfo.userName}）`
                }}
                </view>
                <view class="teamInfo" v-if="type !== 'add'">
                  <view>{{ formData.inspectUserRoleName }}</view>
                  <view class="team">

                    <view v-if="formData.inspectStationName">
                      {{ formData.inspectStationName }}
                    </view>
                    <view v-if="formData.inspectDepartmentName">
                      /{{ formData.inspectDepartmentName }}
                    </view>
                    <view v-if="formData.inspectTeamName">
                      /{{ formData.inspectTeamName }}
                    </view>
                  </view>
                </view>
                <view class="teamInfo" v-else>
                  <view>安检员</view>
                  <view class="team">

                    <view v-if="userInfo.stationName">
                      {{ userInfo.stationName }}
                    </view>
                    <view v-if="userInfo.departmentName">
                      /{{ userInfo.departmentName }}
                    </view>
                    <view v-if="userInfo.teamsName">
                      /{{ userInfo.teamsName }}
                    </view>
                  </view>
                </view>

              </view>
            </template>

            <!-- kezhang角色显示查获人员选择 -->
            <uni-forms-item v-if="isKezhang && !isDetailMode" label="查获人员" name="inspectUserId" required>
              <uni-data-picker :readonly="isDetailMode" :localdata="departmentUserOptions" popup-title="请选择查获人员"
                v-model="formData.inspectUserId" @change="onInspectUserChange" />
            </uni-forms-item>
            <uni-forms-item v-else-if="isKezhang && isDetailMode" label="查获人员">
              <uni-easyinput :disabled="true" placeholder="查获人员" :value="formData.inspectUserName" />
            </uni-forms-item>

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

            <uni-forms-item label="安检岗位" name="checkMethodText" required>
              <uni-combox :disabled="isDetailMode" :candidates="checkMethodCandidates" placeholder="请选择安检岗位"
                v-model="formData.checkMethodText" @input="onCheckMethodComboxChange" />
            </uni-forms-item>

            <uni-forms-item label="查获位置" name="securityLocation" required>
              <uni-data-picker v-if="!isDetailMode" :readonly="isDetailMode" :localdata="position_options"
                popup-title="请选择查获位置" v-model="formData.securityLocation" @change="onLocationChange" />
              <uni-easyinput v-else :disabled="true" placeholder="请选择查获班组" :value="formData.securityLocationText" />
            </uni-forms-item>

            <uni-forms-item label="查获班组" name="reportTeam" required>
              <uni-data-picker v-if="!isDetailMode" :readonly="isDetailMode" :localdata="teams" popup-title="请选择查获班组"
                v-model="formData.reportTeam" @change="onReportTeamChange" />

              <uni-easyinput v-else :disabled="true" placeholder="请选择查获班组" :value="formData.attendanceTeamName" />
            </uni-forms-item>

            <!-- 开机指令（仅开箱检查岗位显示） -->
            <uni-forms-item v-if="isPackageInspection" label="开机指令" name="powerOnInstruction" required>
              <radio-group v-if="!isDetailMode" @change="onpowerOnInstructionChange" class="radio-group"
                :class="{ 'disabled-group': isDetailMode }">
                <label class="radio-item" v-for="(item, index) in powerOnInstructionOptions" :key="index">
                  <radio :value="item.value" :checked="formData.powerOnInstruction == item.value" color="#409EFF" />
                  <text>{{ item.text }}</text>
                </label>
              </radio-group>
              <uni-easyinput v-else :disabled="true" placeholder="请选择开机指令" :value="formData.powerOnInstructionText" />
            </uni-forms-item>

            <!-- X光开机员（仅非指令时显示） -->
            <uni-forms-item v-if="showXrayOperator" label="X光开机员" name="xrayOperatorId" required>
              <fuzzy-select v-if="!isDetailMode" v-model="formData.xrayOperatorId" :options="xrayOperatorOptions"
                placeholder="请输入X光开机员姓名搜索" data-value="userId" data-text="nickName" @change="handleXrayOperatorSelect"
                :disabled="isDetailMode" />
              <uni-easyinput v-else :disabled="true" placeholder="请选择X光开机员" :value="formData.xrayOperatorName" />
            </uni-forms-item>
          </uni-collapse-item>
        </uni-collapse>
        <!-- </view> -->

        <!-- 违禁品信息分组 -->
        <view class="card">
          <uni-collapse class="collapse" :accordion="false" :value="['group2']">
            <uni-collapse-item class="collapse-item" title="违禁品信息" name="group2" :show-animation="true">

              <uni-forms-item label="常用违禁品" v-if="type == 'add'">
                <view class="gridWrap">
                  <uni-tag v-for="item of commonlyList.forbidden" :key="item.categoryId" @click="selectCategory(item)"
                    :text="item.categoryName" type="primary"
                    :inverted="formData.forbiddenCategory !== item.categoryId" />
                </view>
              </uni-forms-item>

              <uni-forms-item label="搜索违禁品" v-if="type == 'add'">
                <SearchView title="搜索违禁品" :load="searchLoadData" placeholder="请选择/输入违禁品名称"
                  :map="{ text: 'name', value: 'id' }" @change="searchSelectChange" />
              </uni-forms-item>

              <uni-forms-item label="违禁品类别/类型" name="forbiddenType" required>
                <uni-data-picker v-if="!isDetailMode" :readonly="isDetailMode" :localdata="item_category_options"
                  :map="dataTreeOptionMap" popup-title="请选择违禁品类别" v-model="formData.forbiddenType"
                  @change="onCategoryChange" />
                <uni-easyinput v-else :disabled="true" placeholder="请选择违禁品类别/类型"
                  :value="`${formData.forbiddenCategoryText} / ${formData.forbiddenTypeText}`" />
              </uni-forms-item>

              <uni-forms-item label="违禁品名称" name="forbiddenName">
                <uni-easyinput :disabled="isDetailMode" placeholder="请输入违禁品名称" v-model="formData.forbiddenName" />
              </uni-forms-item>

              <uni-forms-item label="数量" name="quantity" required>
                <view class="number-input">
                  <uni-easyinput :disabled="isDetailMode" v-model="formData.quantity" type="number" placeholder="1"
                    class="input-number" />
                  <!-- <uni-data-picker :localdata="item_unit_options" :map="dataOptionMap" popup-title="请选择单位"
                    v-model="formData.unit" @change="onUnitChange" name="unit" required /> -->
                </view>
              </uni-forms-item>
              <uni-forms-item label="是否常见违禁品" name="commonContraband" required>
                <radio-group @change="onCommonForbiddenChange" class="radio-group"
                  :class="{ 'disabled-group': isDetailMode }">
                  <label class="radio-item" v-for="(item, index) in commonForbiddenOptions" :key="index">
                    <radio :value="item.value" :checked="formData.commonContraband == item.value" color="#409EFF" />
                    <text>{{ item.text }}</text>
                  </label>
                </radio-group>
              </uni-forms-item>

              <uni-forms-item v-if="formData.commonContraband == 0" label="违禁品描述" name="contrabandDesc" required>
                <uni-easyinput :disabled="isDetailMode" placeholder="请输入违禁品详细描述" v-model="formData.contrabandDesc" />
              </uni-forms-item>

              <!-- 违禁品照片 (当选择"否"时显示) -->
              <uni-forms-item
                v-if="(!isDetailMode || isDetailMode && formData.images.length > 0) && formData.commonContraband == 0"
                label="违禁品照片">
                <view style="padding: 0 15px 15px 15px;">
                  <uni-file-picker :disabled="isDetailMode" :readonly="isDetailMode" v-model="formData.images" limit="3"
                    title="最多上传3张" :image-styles="imageStyles" fileMediatype="image" mode="grid" @select="onSelect" />
                </view>
              </uni-forms-item>
            </uni-collapse-item>
          </uni-collapse>
        </view>

        <!-- 查获部位分组 -->
        <view class="card">
          <uni-collapse class="collapse" :accordion="false" :value="['group3']">
            <uni-collapse-item class="collapse-item" title="查获部位" name="group3" :show-animation="true">

              <uni-forms-item label="常用查获部位" v-if="type == 'add'">
                <view class="gridWrap">
                  <uni-tag v-for="item of commonlyList.part" :key="item.categoryId" @click="selectPart(item)"
                    :text="item.categoryName" type="primary" :inverted="formData.partCategory !== item.categoryId" />
                </view>
              </uni-forms-item>

              <uni-forms-item label="部位类别/类型" name="partType" required>
                <uni-data-picker v-if="!isDetailMode" :readonly="isDetailMode" :localdata="check_point_options"
                  :map="dataTreeOptionMap" popup-title="请选择部位类别" :value="formData.partType"
                  @change="onPartCategoryChange" />
                <uni-easyinput v-else :disabled="true" placeholder="请选择部位类别"
                  :value="`${formData.partCategoryText} / ${formData.partTypeText}`" />
              </uni-forms-item>
              <uni-forms-item label="具体位置" name="location">
                <uni-easyinput :disabled="isDetailMode" placeholder="请输入具体位置" v-model="formData.location" />
              </uni-forms-item>

              <uni-forms-item label="处理方式" name="handlingMethod" required>
                <uni-data-picker v-if="!isDetailMode" :readonly="isDetailMode" popup-title="请选择处理方式"
                  :map="dataOptionMap" :localdata="item_handling_method_options" v-model="formData.handlingMethod"
                  @change="onMethodChange" />
                <uni-easyinput v-else :disabled="true" placeholder="请选择处理方式" v-model="formData.handlingMethodDesc" />
              </uni-forms-item>

              <uni-forms-item label="是否隐匿夹带" name="isActiveConcealment" required>
                <radio-group @change="bindConcealChange" class="radio-group"
                  :class="{ 'disabled-group': isDetailMode }">
                  <label class="radio-item" v-for="(item, index) in concealOptions" :key="index">
                    <radio :value="item.value" :checked="formData.isActiveConcealment === item.value" color="#409EFF" />
                    <text>{{ item.name }}</text>
                  </label>
                </radio-group>
              </uni-forms-item>
            </uni-collapse-item>
          </uni-collapse>
        </view>

        <!-- 违禁品照片分组 -->
        <!-- <view class="card" v-if="!isDetailMode || isDetailMode && formData.images.length > 0">
          <uni-collapse class="collapse" :accordion="false" :value="['group4']">
            <uni-collapse-item class="collapse-item" title="违禁品照片 (可选)" name="group4" :show-animation="true">
              <view style="padding: 0 15px 15px 15px;margin-bottom: 150rpx;">
                <uni-file-picker :disabled="isDetailMode" v-model="formData.images" limit="8" title="最多上传8张"
                  :image-styles="imageStyles" fileMediatype="image" mode="grid" @select="onSelect" />
              </view>
            </uni-collapse-item>
          </uni-collapse>
        </view> -->

        <!-- 5. 审批历史分组 -->
        <view class="card" v-if="type !== 'add'">
          <uni-collapse class="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 :is-shadow="true" :shadow="shadow">
          <uni-collapse :accordion="false" :value="['group5']">
            <uni-collapse-item title="旅客信息" name="group5" :show-animation="true">
              <template v-slot:title>
                <view class="collapse-title">
                  <text>旅客信息</text>
                  <text class="collapse-summary" v-if="formData.passengerName">{{ formData.passengerName }} ·
                    {{ formData.flightNumber || '无航班号' }}</text>
                </view>
              </template>

              <uni-forms-item label="姓名" name="passengerName">
                <uni-easyinput :disabled="isDetailMode" v-model="formData.passengerName" placeholder="请输入旅客姓名" />
              </uni-forms-item>

              <uni-forms-item label="证件号" name="passengerId">
                <uni-easyinput :disabled="isDetailMode" v-model="formData.passengerId" placeholder="请输入证件号 (可选)" />
              </uni-forms-item>

              <uni-forms-item label="航班号" name="flightNumber">
                <uni-easyinput :disabled="isDetailMode" v-model="formData.flightNumber" placeholder="例如：CA1234 (可选)" />
              </uni-forms-item>
            </uni-collapse-item>
          </uni-collapse>
        </view> -->

        <!-- 提交按钮 -->
        <view class="button-group" v-if="type === 'approve' || type === 'add'">
          <view v-if="!isDetailMode" class="custom-btn-normal" @click="submitForm">提交上报</view>
          <template v-else>
            <view v-if="nodeCode != 'START'" class="custom-btn-white" @click="handleApproveReject"
              style="margin-right: 10px;">审批驳回</view>
            <view class="custom-btn-normal" @click="handleApprovePass">{{
              nodeCode == 'START' ? '提交' : '审批通过' }}</view>
          </template>
        </view>

        <!-- </scroll-view> -->
      </uni-forms>
    </view>

  </home-container>

</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import SearchView from "@/pages/attendance/components/SearchView.vue"
import { treeSelectByType } from "@/api/system/common"
import useDictMixin from '@/utils/dict'
import FuzzySelect from "@/components/fuzzy-select/fuzzy-select.vue"
import { addSeizureRecord, approvalStart, getInfo } from '@/api/seizure/seizureRecord.js'
import { getLocationsbyTime, categoryInfo, categoryList } from '@/api/seizureRecord/seizureRecord.js'
import config from '@/config'
import { getToken } from '@/utils/auth'
import { approvePass, approveReject, getApprovelHistory } from '@/api/approve/approve.js'
import { getDeptList } from "@/api/system/dept/dept.js"
import { formatTime } from '@/utils/formatUtils'
import { getUserInfoById, getPostListsByUserId } from '@/api/system/user.js'
import { getUserList } from '@/api/attendance/attendance'
export default {
  components: { HomeContainer, SearchView, FuzzySelect },
  mixins: [useDictMixin],
  computed: {
    currentUser() {
      return this.$store.state.user;
    },
    userInfo() {

      return (this.$store.state.user && this.$store.state.user.userInfo) ? this.$store.state.user.userInfo : {}
    },
    // 判断是否为kezhang角色
    isKezhang() {
      return this.$store?.state?.user?.roles?.includes('kezhang')
    },
    // 将item_check_method_options转换为字符串数组供uni-combox使用
    checkMethodCandidates() {
      // console.log(this.item_check_method_options.map(item => item.postName || item.label || item.text || item.value),"this.item_check_method_options.map(item => item.postName || item.label || item.text || item.value)")
      return this.item_check_method_options.map(item => item.postName || item.label || item.text || item.value);
    },
    // 判断是否为开箱（包）检查岗位
    isPackageInspection() {
      return this.formData.checkMethodText === '开箱（包）检查岗位';
    },
    // 判断是否显示X光开机员选择（非指令时显示）
    showXrayOperator() {
      return this.isPackageInspection && this.formData.powerOnInstruction == '1';
    },
    // // 判断是新增模式还是详情模式
    isDetailMode() {

      return !!this.businessId; // 如果有id则为详情模式，否则为新增模式
    },
    // 动态验证规则
    rules() {
      return {
        seizureTime: {
          rules: [{ required: true, errorMessage: '请选择查获时间' }]
        },
        checkMethodText: {
          rules: [{ required: true, errorMessage: '请选择安检位置' }]
        },
        reportTeam: {
          rules: [{ required: true, errorMessage: '请选择上报班组' }]
        },
        powerOnInstruction: {
          rules: [{ required: true, errorMessage: '请选择开机指令' }]
        },
        xrayOperatorId: {
          rules: [{ required: true, errorMessage: '请选择X光开机员' }]
        },
        forbiddenCategory: {
          rules: [{ required: true, errorMessage: '请选择违禁品类别' }]
        },
        forbiddenType: {
          rules: [{ required: true, errorMessage: '请选择违禁品类型' }]
        },
        quantity: {
          rules: [
            { required: true, errorMessage: '请输入数量' },
            { format: 'number', errorMessage: '数量必须为数字' }
          ]
        },
        partCategory: {
          rules: [{ required: true, errorMessage: '请选择部位类别' }]
        },
        unit: {
          rules: [{ required: true, errorMessage: '请选择违禁品数量单位' }]
        },
        partType: {
          rules: [{ required: true, errorMessage: '请选择部位类型' }]
        },
        handlingMethod: {
          rules: [{ required: true, errorMessage: '请选择处理方式' }]
        },
        isActiveConcealment: {
          rules: [{ required: true, errorMessage: '请选择是否有意隐匿' }]
        },
        commonContraband: {
          rules: [{ required: true, errorMessage: '请选择是否常见违禁品' }]
        },
        contrabandDesc: {
          rules: [
            {
              required: this.formData.commonContraband == 0,
              errorMessage: '请填写违禁品描述'
            }
          ]
        }
      }
    }
  },
  data() {
    return {
      // 路由参数id，用于判断详情模式
      businessId: null,
      // 表单数据
      formData: {
        // 安检员信息
        inspectUserName: this.isKezhang ? '' : this.$store.state.user.name,
        inspectUserId: this.isKezhang ? '' : this.$store.state.user.id,
        seizureTime: this.formatDateTime(new Date()),
        securityLocation: '',
        securityLocationText: '',
        checkMethod: '',    // 检查岗位
        checkMethodText: '',
        teamId: 1,
        team: '',
        teamName: '',
        reportTeam: '',
        reportTeamText: '',
        // 开机指令相关字段（开箱检查岗位使用）
        powerOnInstruction: '0', // 开机指令：'0'-指令, '1'-非指令
        powerOnInstructionText: '指令',
        xrayOperatorId: '', // X光开机员ID
        xrayOperatorName: '', // X光开机员姓名
        // 查获位置信息
        channelCode: '',
        channelName: '',

        // 违禁品信息
        forbiddenCategory: '',
        forbiddenCategoryText: '',
        forbiddenType: '',
        forbiddenTypeText: '',
        forbiddenName: '',
        quantity: '1',
        unit: '',
        unitText: '',
        commonContraband: 1, // 是否常见违禁品：1-是，0-否
        contrabandDesc: '', // 违禁品描述（选择否时必填）
        // 查获部位
        partCategory: '',
        partCategoryText: '',
        partType: '',
        partTypeText: '',
        location: '',
        locationText: '',
        customLocation: '',
        handlingMethod: 'ABANDON',
        handlingMethodDesc: '自弃',
        isActiveConcealment: '0',

        // 旅客信息
        passengerName: '',
        passengerId: '',
        flightNumber: '',

        // 照片
        images: [],

        //暂时不要
        attendanceId: '',
        attendanceTeamId: '',
        attendanceTeamName: '无',
        attendanceDepartmentId: '',
        attendanceDepartmentName: '无',
        attendanceStationId: '',
        attendanceStationName: '无',
        regionalCode: '',
        regionalName: '无',
        terminlCode: '',
        terminlName: '无',
        inspectTeamId: '',
        inspectTeamName: '无',
        inspectDepartmentId: '',
        inspectDepartmentName: '无',
        checkMethodDesc: '无',
        passengerCard: '',
        flightNumber: '',

      },
      // 数据选项
      item_check_method_options: [],   // 检查岗位
      position_options: [],  // 位置通道
      teams: [],
      item_category_options: [], // 物品分类
      departmentUserOptions: [],  // 部门人员选项（kezhang角色使用）
      typeData: [],
      item_unit_options: [],
      check_point_options: [],
      partTypeData: [],
      locations: [
      ],
      item_handling_method_options: [], // 处理方式
      concealOptions: [
        { name: '是', value: '1' },
        { name: '否', value: '0' }
      ],
      // 开机指令选项
      powerOnInstructionOptions: [
        { text: '指令', value: '0' },
        { text: '非指令', value: '1' }
      ],
      // 是否常见违禁品选项
      commonForbiddenOptions: [
        { text: '是', value: 1 },
        { text: '否', value: 0 }
      ],
      // X光开机员选项
      xrayOperatorOptions: [],
      // 其他数据
      startDate: '2020-01-01',
      endDate: '2030-12-31',
      imageStyles: {
        width: 80,
        height: 80,
        border: {
          color: '#eee',
          width: '1px',
          style: 'solid'
        }
      },
      dataOptionMap1: { text: 'label', value: 'value' }, // 级联字段映射关系
      dataOptionMap: { text: 'label', value: 'value' }, // 级联字段映射关系
      dataTreeOptionMap: { text: 'label', value: 'id' }, // 级联字段映射关系树结构
      commonlyList: {
        forbidden: [],
        part: []
      },
      searchforbiddenName: '',
      forbiddenList: [],
      instanceId: '',
      nodeCode: '',
      id: '',
      type: '',
      approvalHistory: [],
      firstCollapsed: ["group1"],
    }
  },
  async onLoad(options) {

    // if (options && options?.params) {
    let params = {};
    if (options?.params) {
      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 || 'add';
    // }
    await this.initPageData();

    // 如果是kezhang角色，加载部门人员
    if (this.isKezhang) {
      await this.loadDepartmentUsers();
    }

    if (this.type == 'add' && !this.isKezhang) {
      this.invokerGetLocationsbyTime()
    }

    this.invokerCategoryInfo()
    // 如果有路由ID，获取详情信息
    if (this.businessId) {
      this.getDetailInfo();
    }
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.isDetailMode = !!this.businessId
    // })

  },
  methods: {
    // 处理是否常见违禁品选择变化
    onCommonForbiddenChange(e) {
      this.formData.commonContraband = e.detail.value
      // 如果选择"是"，清空违禁品描述
      if (e.detail.value === '1') {
        this.formData.contrabandDesc = ''
      }
    },

    // 处理驳回确认
    // handleRejectConfirm(rejectReason) {
    //   this.formData.comment = rejectReason
    //   this.handleApproveReject()
    // },
    changeCollapse(e) {
      this.firstCollapsed = e
    },
    //审批通过
    async handleApprovePass() {
      try {
        let payload = this.formatData()
        uni.showLoading({ title: '审批中...', mask: true });
        const res = await approvePass(this.id, { formData: payload, comment: '审批通过' });

        if (res.code === 200) {
          uni.hideLoading();
          uni.showToast({ title: '审批通过', icon: 'success' });
        } else {
          uni.hideLoading();
          uni.showToast({ title: '审批失败', icon: 'none' });
        }
        setTimeout(() => {
          uni.navigateBack()
        }, 500)
      } catch (err) {
        uni.hideLoading();
        uni.showToast({ title: '审批失败', icon: 'none' });
        console.error('审批失败:', err);
      }
    },
    //审批驳回
    async handleApproveReject() {
      try {
        let payload = this.formatData()
        uni.showLoading({ title: '审批中...', mask: true });
        const res = await approveReject(this.id, { formData: payload, comment: '审批驳回' });

        if (res.code === 200) {
          uni.hideLoading();
          uni.showToast({ title: '审批驳回', icon: 'success' });

        } else {
          uni.hideLoading();
          uni.showToast({ title: '审批失败', icon: 'none' });
        }
        setTimeout(() => {
          uni.navigateBack()
        }, 500)
      } catch (err) {
        uni.hideLoading();
        uni.showToast({ title: '审批失败', icon: 'none' });
        console.error('审批失败:', err);
      }
    },
    // 获取详情信息
    async getDetailInfo() {
      try {
        uni.showLoading({ title: '加载详情中...', mask: true });
        const res = await getInfo(this.businessId);
        let inspectUserInfo = await getUserInfoById(res.data.inspectUserId)


        res.data.inspectUserRoleName = inspectUserInfo?.data?.roles[0]?.roleName || ''
        if (res.code === 200 && res.data) {
          this.fillFormData(res.data);


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

          if (historyRes.code === 200 && historyRes.rows) {
            this.approvalHistory = historyRes.rows;
          }
          uni.hideLoading();
        } else {
          uni.hideLoading();
          uni.showToast({ title: '获取详情失败', icon: 'none' });
        }
      } catch (err) {
        uni.hideLoading();
        uni.showToast({ title: '获取详情失败', icon: 'none' });
        console.error('获取详情失败:', err);
      }
    },

    // 填充表单数据
    fillFormData(detailData) {
      if (!detailData) return;
      let files = detailData?.itemSeizureItemsList[0].baseAttachmentList && detailData?.itemSeizureItemsList[0].baseAttachmentList.map(file => ({
        ...file,
        url: file.attachmentUrl || file.url,
      }))
      // 填充基础信息
      this.formData = {
        ...this.formData,
        ...detailData,
        // 处理下拉选择器数据格式 - 组成[{text: '', value: ''}]格式以支持回显

        // 处理图片数据
        // images: detailData.images ? detailData.images.map(img => ({
        //   ...img,
        //   url: img.attachmentUrl || img.url,
        //   name: img.attachmentName || img.name,
        //   extname: img.extname
        // })) : [],
        commonContraband: detailData?.itemSeizureItemsList[0].commonContraband,
        contrabandDesc: detailData?.itemSeizureItemsList[0].contrabandDesc,
        forbiddenCategory: detailData?.itemSeizureItemsList[0].categoryCodeOne,
        forbiddenCategoryText: detailData?.itemSeizureItemsList[0].categoryNameOne,
        forbiddenType: detailData?.itemSeizureItemsList[0].categoryCodeTwo,
        forbiddenTypeText: detailData?.itemSeizureItemsList[0].categoryNameTwo,
        partCategory: detailData?.itemSeizureItemsList[0].checkPositionCodeOne,
        partCategoryText: detailData?.itemSeizureItemsList[0].checkPositionNameOne,
        partType: detailData?.itemSeizureItemsList[0].checkPositionCodeTwo,
        partTypeText: detailData?.itemSeizureItemsList[0].checkPositionNameTwo,
        forbiddenName: detailData?.itemSeizureItemsList[0].itemName,
        quantity: detailData?.itemSeizureItemsList[0].quantity,
        images: files || [],
        location: detailData?.itemSeizureItemsList[0].location,
        isActiveConcealment: String(detailData?.itemSeizureItemsList[0].isActiveConcealment),
        handlingMethodDesc: detailData?.itemSeizureItemsList[0].handlingMethodDesc,
        handlingMethod: detailData?.itemSeizureItemsList[0].handlingMethod,
        // reportTeamText:`${detailData?.inspectStationName}/${detailData?.inspectBrigadeName}/${detailData?.inspectDepartmentName}/${detailData?.inspectTeamName}`,
        securityLocationText: `${detailData?.terminlName}/${detailData?.regionalName}/${detailData?.channelName}`
      };

      this.$nextTick(() => {
        // 处理所有下拉选择器字段的数组格式转换
        const dropdownFields = [
          { field: 'checkMethod', textField: 'checkMethodText', descField: 'checkMethodDesc' },
          { field: 'reportTeam', textField: 'reportTeamText' },
          { field: 'unit', textField: 'unitText' },

        ]

        dropdownFields.forEach(({ field, textField, descField }) => {
          if (detailData[field]) {
            // 对于checkMethod字段，保持字符串格式（uni-combox需要）
            if (field === 'checkMethod') {
              this.formData[field] = detailData[field];
              this.formData[textField] = detailData[descField] || detailData[textField] || detailData[field];
            } else {
              // 其他下拉字段保持数组格式
              this.formData[field] = [{
                value: detailData[field],
                text: detailData[descField] || detailData[textField] || detailData[field]
              }]
              this.formData[textField] = detailData[descField] || detailData[textField] || detailData[field]
            }
          }
        })

        // 处理powerOnInstruction字段，确保为字符串类型
        if (detailData.powerOnInstruction != null) {
          this.formData.powerOnInstruction = String(detailData.powerOnInstruction);
          this.formData.powerOnInstructionText = detailData.powerOnInstructionText || (detailData.powerOnInstruction == 1 ? '非指令' : '指令');
        } else {
          this.formData.powerOnInstruction = '0';
          this.formData.powerOnInstructionText = '指令';
        }

      })

      console.log('表单数据已回填:', this.formData);
    },

    searchLoadData(val) {
      return categoryList({ name: val, level: 2 }).then(res => {
        return res.data
      })
    },
    invokerGetLocationsbyTime() {
      return getLocationsbyTime({
        searchtime: formatTime(new Date())
      }).then(res => {
        const curUserInfo = (res.data || []).find(item => {
          return item.userId === this.currentUser.id && (!item.checkOutTime || item.checkOutTime === '2000-01-01 00:00:00')
        }) || {}

        this.formData.securityLocation = curUserInfo.channelCode || curUserInfo.regionalCode
        this.formData.securityLocationText = curUserInfo.channelName || curUserInfo.regionalName

        this.formData.team = curUserInfo.attendanceTeamId
        this.formData.reportTeam = curUserInfo.attendanceTeamId
        if (curUserInfo.attendanceStationName && curUserInfo.attendanceDepartmentName) {
          this.formData.teamName = `${curUserInfo.attendanceStationName} / ${curUserInfo.attendanceDepartmentName} / ${curUserInfo.attendanceTeamName}`
          this.formData.reportTeamText = `${curUserInfo.attendanceStationName} / ${curUserInfo.attendanceDepartmentName} / ${curUserInfo.attendanceTeamName}`
        }
        console.log(this.formData);
        const locationResult = this.getParentLocation(this.formData.securityLocation)
        console.log(locationResult);

        // 安全地处理可能为null的结果
        if (locationResult) {
          this.formData.terminlName = locationResult.grandParent?.text || '';
          this.formData.terminlCode = locationResult.grandParent?.value || '';
          this.formData.regionalName = locationResult.parent?.text || '';
          this.formData.regionalCode = locationResult.parent?.value || '';
          this.formData.channelName = locationResult.current?.text || '';
          this.formData.channelCode = locationResult.current?.value || '';
        } else {
          // 如果找不到位置信息，清空相关字段
          this.formData.terminlName = '';
          this.formData.terminlCode = '';
          this.formData.regionalName = '';
          this.formData.regionalCode = '';
          this.formData.channelName = '';
          this.formData.channelCode = '';
        }
      })
    },
    //根据securityLocation,从this.position_options中向上找到前两级别的父级对象和当前级别对象
    getParentLocation(securityLocation) {
      if (!securityLocation || !this.position_options || !this.position_options.length) {
        return null;
      }

      // 递归查找节点及其父级
      const findNodeAndParents = (nodes, targetValue, parents = []) => {
        for (const node of nodes) {
          if (node.value === targetValue) {
            return { node, parents };
          }

          if (node.children && node.children.length) {
            const result = findNodeAndParents(node.children, targetValue, [...parents, node]);
            if (result) {
              return result;
            }
          }
        }
        return null;
      };

      const result = findNodeAndParents(this.position_options, securityLocation);

      if (!result) {
        return null;
      }

      const { node, parents } = result;

      // 返回当前级别对象和前两级的父级对象（如果存在）
      if (parents.length >= 2) {
        return {
          current: node,                              // 当前级别对象
          grandParent: parents[parents.length - 2],  // 祖父级
          parent: parents[parents.length - 1]        // 父级
        };
      } else if (parents.length === 1) {
        return {
          current: node,                              // 当前级别对象
          grandParent: null,                         // 没有祖父级
          parent: parents[0]                         // 只有父级
        };
      } else {
        return {
          current: node,                              // 当前级别对象
          grandParent: null,                         // 没有祖父级
          parent: null                               // 没有父级
        };
      }
    },
    invokerCategoryInfo() {
      categoryInfo(1).then(res => {
        this.commonlyList.forbidden = res.data || []
      })
      categoryInfo(2).then(res => {
        this.commonlyList.part = res.data || []
      })
    },
    async initPageData() {
      try {
        uni.showLoading({ title: '加载中...', mask: true });

        // 查询基础数据 
        // 位置  航站楼 区域  通道   locationData   树结构  POSITION
        // 物品类型  categoryData   树结构   ITEM_CATEGORY
        // 身体部位类型 partCategoryData   树结构  CHECK_POINT

        const deptTree = await getDeptList();
        this.teams = this.buildTeamOptions(deptTree.data || []);

        const [positionRes, itemCategoryRes, checkPointRes] = await Promise.all([
          treeSelectByType("POSITION", 3),
          treeSelectByType("ITEM_CATEGORY", 3),
          treeSelectByType("CHECK_POINT", 3)
        ]);
        // 初始化岗位选项数据
        await this.initPositionAndOptions();

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

        this.position_options = convertTree(positionRes.data || []);
        this.item_category_options = itemCategoryRes.data || [];
        this.forbiddenList = itemCategoryRes.data || [];
        this.check_point_options = checkPointRes.data || [];

        // 处理方式  item_handling_method_options  字典  item_handling_method
        // 单位 units  字典  item_unit
        const dict = await this.useDict(
          'item_handling_method',
          'item_unit'
        )

        this.item_handling_method_options = dict.item_handling_method || [];
        // console.log(this.item_handling_method_options,"this.item_handling_method_options")
        this.item_unit_options = dict.item_unit || [];

        uni.hideLoading();
      } catch (err) {
        uni.hideLoading();
        uni.showToast({ title: '加载失败', icon: 'none' });
        console.error('初始化数据失败:', err);
      }
    },

    buildTeamOptions(tree = []) {
      const result = [];

      function dfs(node, path = []) {
        const currentPath = [...path, node.label];
        // 如果是 TEAMS 叶子节点
        if (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;
    },

    // 初始化岗位和选项数据
    async initPositionAndOptions() {
      try {
        // 使用当前选择的inspectUserId查询岗位列表
        const userId = this.formData.inspectUserId || this.currentUser.id;
        const postListsRes = await getPostListsByUserId(userId);


        // 更新岗位选项
        this.item_check_method_options = postListsRes.data || [];

        console.log("岗位和选项数据已更新，用户ID:", userId);
      } catch (error) {
        console.error("初始化岗位和选项数据失败:", error);
      }
    },

    // 加载部门人员（kezhang角色使用）
    async loadDepartmentUsers() {
      if (!this.isKezhang) return;

      try {
        const currentUserInfo = this.userInfo || {};
        const currentUserDeptId = currentUserInfo.departmentId || currentUserInfo.deptId;

        if (!currentUserDeptId) {
          console.warn('无法获取当前用户的部门ID');
          return;
        }

        const response = await getUserList({
          deptId: currentUserDeptId,
          status: '0',
          pageSize: 1000
        });

        if (response && response.code === 200) {
          this.departmentUserOptions = (response.rows || []).map(user => ({
            ...user,
            value: user.userId,
            text: user.nickName || user.userName,

          }));
        }
      } catch (error) {
        console.error('获取部门人员失败:', error);
        uni.showToast({
          title: '获取部门人员失败',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 选择文件后手动上传
    async onSelect(event) {
      // 由于限制只能上传1个文件，直接取第一个文件进行上传
      const files = await this.uploadFile(event);

      console.log("上传成功====", files);
      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.images = [
        ...this.formData.images,
        ...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
          });
        });
      }));
    },

    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}`;
    },

    // 安检位置变化
    onLocationChange(e) {
      const arr = e.detail.value || [];
      this.formData.securityLocation = arr[arr.length - 1]?.value || '';
      this.formData.securityLocationText = arr.map(item => item.text).join('/');
      const locationResult = this.getParentLocation(this.formData.securityLocation)
      console.log(locationResult);

      // 安全地处理可能为null的结果
      if (locationResult) {
        this.formData.terminlName = locationResult.grandParent?.text || '';
        this.formData.terminlCode = locationResult.grandParent?.value || '';
        this.formData.regionalName = locationResult.parent?.text || '';
        this.formData.regionalCode = locationResult.parent?.value || '';
        this.formData.channelName = locationResult.current?.text || '';
        this.formData.channelCode = locationResult.current?.value || '';
      } else {
        // 如果找不到位置信息，清空相关字段
        this.formData.terminlName = '';
        this.formData.terminlCode = '';
        this.formData.regionalName = '';
        this.formData.regionalCode = '';
        this.formData.channelName = '';
        this.formData.channelCode = '';
      }
    },

    // 通用取值：只拿最后一级
    lastValue(e) {
      const val = e.detail.value;
      if (Array.isArray(val)) return val[val.length - 1] || '';
      if (val && typeof val === 'object') return val.value || '';
      return String(val || '');
    },

    // 安检岗位 - combox版本
    onCheckMethodComboxChange(text) {
      // 根据选中的文本找到对应的原始对象
      const selectedItem = this.item_check_method_options.find(item =>
        item.postName === text || item.label === text || item.text === text || item.value === text
      );

      if (!selectedItem) {
        this.formData.checkMethod = '';
        this.formData.checkMethodText = '';
        return
      }
      // 如果切换了岗位，重置开机指令相关字段
      if (this.formData.checkMethodText !== text) {
        this.formData.powerOnInstruction = '';
        this.formData.powerOnInstructionText = '';
        this.formData.xrayOperatorId = '';
        this.formData.xrayOperatorName = '';
      }


      this.formData.checkMethod = selectedItem?.postCode || text;
      this.formData.checkMethodText = selectedItem?.postName || selectedItem?.label || selectedItem?.text || text;
      // 如果是开箱（包）检查岗位，加载X光开机员列表
      if (text === '开箱（包）检查岗位') {
        this.loadXrayOperators();
      }
    },
    // 开机指令变化
    onpowerOnInstructionChange(e) {
      const selectedValue = e.detail.value;

      this.formData.powerOnInstruction = selectedValue;
      this.formData.powerOnInstructionText = selectedValue === '1' ? '非指令' : '指令';
      this.formData.xrayOperatorId = '';
      this.formData.xrayOperatorName = '';

      // 如果选择了指令，清空X光开机员
      if (this.formData.powerOnInstruction === '0') {
        this.loadXrayOperators();
      }
    },

    // 加载X光开机员列表
    async loadXrayOperators() {
      try {
        // 使用现有的用户列表接口，可以根据需要调整参数
        const { listAllUser } = await import('@/api/system/user.js');
        const res = await listAllUser();
        if (res && res.data) {
          this.xrayOperatorOptions = res.data.map(item => ({
            ...item,
            nickName: `${item.nickName}(${item.userName})`,
          })) || [];
        }
      } catch (error) {
        console.error('加载X光开机员列表失败:', error);
      }
    },

    // X光开机员选择
    handleXrayOperatorSelect(value) {
      const selectedUser = this.xrayOperatorOptions.find(user => user.userId === value);
      if (selectedUser) {
        this.formData.xrayOperatorId = selectedUser.userId;
        this.formData.xrayOperatorName = selectedUser.nickName;
      }
    },
    // 安检岗位 - 原data-picker版本（已弃用）
    onItemCheckMethodChange(e) {
      this.formData.checkMethod = e.detail.value[0]?.value || '';
      this.formData.checkMethodText = e.detail.value[0]?.text || e.detail.value[0]?.text || '';
    },

    // 查获班组变化
    onTeamChange(e) {
      this.formData.team = e.detail.value[0].value;
      this.formData.teamName = e.detail.value[1]?.text || e.detail.value[0]?.text || '';
    },

    // 上报班组变化
    onReportTeamChange(e) {
      console.log("e.detail.value", e.detail.value)
      this.formData.reportTeam = e.detail.value[0].value;
      this.formData.reportTeamText = e.detail.value[1]?.text || e.detail.value[0]?.text || '';
    },
    // 快捷选中违禁品
    selectCategory(item) {
      const createEventInfo = {
        detail: {
          value: [
            { value: item.parentId, text: item.parentName },
            { value: item.categoryId, text: item.categoryName },
          ]
        }
      }
      this.onCategoryChange(createEventInfo)
    },
    // 搜索违禁品 选中
    searchSelectChange(selectItem) {

      const curParent = this.item_category_options.find(item => item.id === selectItem.parentId)
      const createEventInfo = {
        detail: {
          value: [
            { value: selectItem.parentId, text: selectItem.parentName || curParent?.label },
            { value: selectItem.id, text: selectItem.name },
          ]
        }
      }
      this.onCategoryChange(createEventInfo)
    },
    // 违禁品类别变化
    onCategoryChange(e) {
      if (!e.detail.value || !e.detail.value.length) {
        this.formData.forbiddenCategory = ''
        this.formData.forbiddenCategoryText = ''
        this.formData.forbiddenType = ''
        this.formData.forbiddenTypeText = ''
        return
      }
      this.formData.forbiddenCategory = e.detail.value[0].value;
      this.formData.forbiddenCategoryText = e.detail.value[0].text;
      this.formData.forbiddenType = e.detail.value[1].value;
      this.formData.forbiddenTypeText = e.detail.value[1].text;
    },

    // 单位变化
    onUnitChange(e) {
      this.formData.unit = e.detail.value;
      this.formData.unitText =
        this.item_unit_options.find(item => item.value === e.detail.value)?.label || '件';
    },

    // 快捷选中违禁品
    selectPart(item) {
      const createEventInfo = {
        detail: {
          value: [
            { value: item.parentId, text: item.parentName },
            { value: item.categoryId, text: item.categoryName },
          ]
        }
      }
      this.onPartCategoryChange(createEventInfo)
    },
    // 部位类别变化
    onPartCategoryChange(e) {
      if (!e.detail.value || !e.detail.value.length) {
        this.formData.partCategory = ''
        this.formData.partCategoryText = ''
        this.formData.partType = ''
        this.formData.partTypeText = ''
        return
      }
      this.formData.partCategory = e.detail.value[0].value;
      this.formData.partCategoryText = e.detail.value[0].text;
      this.formData.partType = e.detail.value[1].value;
      this.formData.partTypeText = e.detail.value[1].text;
    },

    // 安检员选择变化（kezhang角色使用）
    async onInspectUserChange(e) {
      console.log("查获人员选择变化", e.detail.value)
      const arr = e.detail.value || [];
      this.formData.inspectUserId = arr[arr.length - 1]?.value || '';
      this.formData.inspectUserName = arr.map(item => item.text).join('/');

      this.formData.reportTeam = this.departmentUserOptions.find(item => item.userId === this.formData.inspectUserId)?.deptId;
      this.formData.reportTeamText = this.teams.find(item => item.value === this.formData.reportTeam)?.text;
      // 切换查获人员后，重新初始化岗位和选项数据
      if (this.formData.inspectUserId) {
        await this.initPositionAndOptions();
      }
    },

    // 部位类型变化
    onPartTypeChange(e) {
      this.formData.partType = e.detail.value[0].value;
      this.formData.partTypeText = e.detail.value[0].text;
    },

    // 具体位置选择
    onLocationSelectChange(e) {
      this.formData.location = e.detail.value;
      this.formData.locationText = this.locations.find(item => item.value === e.detail.value)?.text || '';
      this.formData.customLocation = this.formData.locationText;
    },

    // 处理方式变化
    onMethodChange(e) {
      this.formData.handlingMethod = e.detail.value[0].value;
      this.formData.handlingMethodDesc = e.detail.value[0].text;
    },

    // 是否有意隐匿选择
    bindConcealChange(e) {

      if (this.isDetailMode) {
        return; // 详情模式下不处理change事件
      }
      this.formData.isActiveConcealment = e.detail.value;
    },
    generateNumericID() {
      // 使用更安全的ID生成方式，避免重复
      const timestamp = Date.now();
      const random = Math.floor(Math.random() * 1e9); // 9位随机数
      return parseInt(`${timestamp}${random}`.slice(-15)); // 确保总长度不超过15位
    },
    formatData() {
      // this.formData.regionalCode = this.formData.securityLocation
      // this.formData.regionalName = this.formData.securityLocationText
      this.formData.channelCode =
        this.formData.channelCode || this.formData.securityLocation || '无'
      this.formData.channelName =
        this.formData.channelName || this.formData.securityLocationText || '无'
      this.formData.inspectTeamId = this.formData.team
      this.formData.inspectTeamName = this.formData.teamName
      this.formData.attendanceTeamId = this.formData.reportTeam
      this.formData.attendanceTeamName = this.formData.reportTeamText
      this.formData.passengerCard = this.formData.passengerId
      this.formData.passengerFlight = this.formData.flightNumber
      this.formData.checkMethodDesc = this.formData.checkMethodText

      // if (this.formData.isActiveConcealment === 'yes') {
      //   this.formData.isActiveConcealment = 1

      // } else {
      //   this.formData.isActiveConcealment = 0

      // }



      const item = {
        // 违禁品信息
        forbiddenType: this.formData.forbiddenType,
        forbiddenTypeText: this.formData.forbiddenTypeText,
        itemName: this.formData.forbiddenName,
        quantity: this.formData.quantity,
        unit: this.formData.unit[0]?.value || '',
        unitDesc: this.formData.unitText,
        checkPositionCodeOne: this.formData.partCategory,
        checkPositionNameOne: this.formData.partCategoryText,
        checkPositionCodeTwo: this.formData.partType,
        checkPositionNameTwo: this.formData.partTypeText,
        checkPositionSpecific: this.formData.customLocation,
        //附件
        baseAttachmentList: this.formData.images,
        //暂时不要
        itemCode: '无',
        commonContraband: Number(this.formData.commonContraband),
        contrabandDesc: this.formData.contrabandDesc,
        isActiveConcealment: this.formData.isActiveConcealment,

        categoryCodeOne: this.formData.forbiddenCategory,
        categoryNameOne: this.formData.forbiddenCategoryText,
        categoryCodeTwo: this.formData.forbiddenType,
        categoryNameTwo: this.formData.forbiddenTypeText,

        handlingMethod: this.formData.handlingMethod,
        handlingMethodDesc: this.formData.handlingMethodDesc,
        location: this.formData.location,
        id: this.generateNumericID(),

      }




      const payload = {
        ...this.formData,
        itemSeizureItemsList: [item],
      };
      return payload
    },

    // 提交表单
    submitForm() {

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

        let params = {
          businessType: 'SEIZURE_REPORT',
          title: '查获物品上报审批流程',
          formData: payload,
          submitterId: this.currentUser.id,
          submitterName: this.currentUser.name,
          submitterRole: 'SEIZURE_REPORT_DEFAULT',
        }



        addSeizureRecord(payload)
          .then((res) => {
            uni.showToast({ title: '提交成功', icon: 'success' });
            //开始流程
            console.log("res0", res)

            approvalStart({ ...params, businessId: res.data }).then(res => {
              setTimeout(() => uni.navigateBack(), 1500); // 提交成功后跳转
            })


          })
          .catch((error) => {
            uni.showToast({ title: '操作失败，请稍后重试！', icon: 'none' }); // 提交失败提示
            console.error('提交失败:', error);
          });


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

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

  .button-group {
    display: flex;
    justify-content: space-between;
    padding: 15px;
  }

  .collapse-card {
    border-radius: 12px;
    margin: 15px 0;
    box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;

    ::v-deep .uni-collapse-item__wrap {
      overflow: visible !important;
      border-radius: 12px;
    }
  }

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

    ::v-deep .uni-collapse-item__wrap {
      overflow: hidden !important;
      border-radius: 12px;
    }
  }


  .card {
    border-radius: 12px;
    overflow: hidden;
    margin: 15px 0;

    box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;

    .gridWrap {
      display: flex;
      column-gap: 8px;
      row-gap: 8px;
      flex-wrap: wrap;
    }

    ::v-deep .collapse {
      border-radius: 16px;
    }


  }

  .userInfo {
    display: flex;
    flex-direction: column;
    row-gap: 10px;

    .userName {
      font-size: 18px;
      font-weight: 500;
    }

    .teamInfo {
      display: flex;
      column-gap: 10px;
      font-size: 14px;
      color: #666;

      .team {
        display: flex;
      }
    }
  }
}


.form-scroll {
  height: calc(100vh - 50px);
  padding: 1px;
  box-sizing: border-box;
}

/* 折叠面板标题 */
.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;
  }
}

.picker-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;

  .picker-value {
    font-size: 15px;
    color: #333;

    &:empty::after {
      content: attr(placeholder);
      color: #999;
    }
  }

  &.disabled {
    opacity: 0.5;
  }
}

.form-value {
  font-size: 15px;
  color: #333;
  height: 44px;
  line-height: 44px;
}

.number-input {
  display: flex;
  align-items: center;
  height: 44px;

  .input-number {
    flex: 1;
  }

  .unit-picker {
    width: 80px;
    margin-left: 10px;
  }
}

.location-input {
  display: flex;
  height: 44px;

  .picker-box {
    width: 120px;
  }

  .custom-location {
    flex: 1;
    margin-left: 0px;
  }
}

// .radio-group {
//   display: flex;
//   padding: 8px 0;

//   .radio-item {
//     display: flex;
//     align-items: center;
//     margin-right: 30px;

//     text {
//       font-size: 15px;
//       color: #333;
//       margin-left: 5px;
//     }
//   }

//   &.disabled-group {
//     opacity: 0.5;
//     pointer-events: none;
//   }
// }

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

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

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

  .uni-data-pickerview {
    padding-bottom: 20px;
  }
}
</style>