<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;">
          <view style="background-color: white;">
            <view class="header-section collapse-title userInfo">
              <view>
                <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>
              <view>
                <uni-icons type="headphones" size="30" color="#409EFF" @click="playAudio"></uni-icons>
              </view>
            </view>
            <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.reportTeamText" />
            </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.label }}</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>
          </view>


        </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-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 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 { getVoiceInfo, deleteVoiceDraft } from '@/api/voiceSubmissionDraft/voiceSubmissionDraft.js'
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'
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 : {}
    },
    // 将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则为详情模式，否则为新增模式
    }
  },
  data() {
    return {
      // 路由参数id，用于判断详情模式
      businessId: null,
      // 表单数据
      formData: {
        // 安检员信息
        inspectUserName: this.$store.state.user.name,
        inspectUserId: this.$store.state.user.id,
        seizureTime: this.formatDateTime(new Date()),
        securityLocation: '',
        audioFilePath: '', // 音频文件路径

        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: '',

        // 查获部位
        partCategory: '',
        partCategoryText: '',
        partType: '',
        partTypeText: '',
        location: '',
        locationText: '',
        customLocation: '',
        handlingMethod: 'ABANDON',
        handlingMethodDesc: '自弃',
        isActiveConcealment: '0',

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

        // 照片
        images: [],

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

      },
      // 验证规则
      rules: {
        seizureTime: {
          rules: [{ required: true, errorMessage: '请选择查获时间' }]
        },
        checkMethodText: {
          rules: [{ required: true, errorMessage: '请选择安检岗位' }]
        },
        reportTeam: {
          rules: [{ required: true, errorMessage: '请选择查获班组' }]
        },
        forbiddenCategory: {
          rules: [{ required: true, errorMessage: '请选择违禁品类别' }]
        },
        forbiddenType: {
          rules: [{ required: true, errorMessage: '请选择违禁品类型' }]
        },
        powerOnInstruction: {
          rules: [{ required: true, errorMessage: '请选择开机指令' }]
        },
        xrayOperatorId: {
          rules: [{ required: true, errorMessage: '请选择X光开机员' }]
        },
        // forbiddenName: {
        //   rules: [{ required: true, errorMessage: '请输入违禁品名称' }]
        // },
        quantity: {
          rules: [
            { required: true, errorMessage: '请输入数量' },
            { format: 'number', errorMessage: '数量必须为数字' }
          ]
        },
        securityLocation: {
          rules: [{ required: true, errorMessage: '请选择查获位置' }]
        },
        partCategory: {
          rules: [{ required: true, errorMessage: '请选择部位类别' }]
        },
        unit: {
          rules: [{ required: true, errorMessage: '请选择违禁品数量单位' }]
        },
        partType: {
          rules: [{ required: true, errorMessage: '请选择部位类别/类型' }]
        },
        // location: {
        //   rules: [{ required: true, errorMessage: '请选择或输入具体位置' }]
        // },
        handlingMethod: {
          rules: [{ required: true, errorMessage: '请选择处理方式' }]
        },
        isActiveConcealment: {
          rules: [{ required: true, errorMessage: '请选择是否有意隐匿' }]
        },
        // passengerName: {
        //   rules: [{ required: true, errorMessage: '请输入旅客姓名' }]
        // }
      },
      // 数据选项
      item_check_method_options: [],   // 检查岗位
      position_options: [],  // 位置通道
      teams: [],
      item_category_options: [], // 物品分类
      typeData: [],
      item_unit_options: [],
      check_point_options: [],
      partTypeData: [],
      locations: [
      ],
      item_handling_method_options: [], // 处理方式
      concealOptions: [
        { name: '是', value: '1' },
        { name: '否', value: '0' }
      ],
      // 开机指令选项
      powerOnInstructionOptions: [
        { label: '指令', value: '0' },
        { label: '非指令', value: '1' }
      ],
      // 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: [],
      voiceId: null,
    }
  },
  async onLoad(options) {
    console.log('options', this.$store.state.user);
    if (options && options?.params) {
      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.voiceId = params?.voiceId;
    }
    await this.initPageData();
    this.invokerCategoryInfo()
    // 如果有路由ID，获取详情信息
    if (this.businessId) {
      this.getDetailInfo();
    }
    // 如果有语音ID，获取语音详情信息
    if (this.voiceId) {
      await this.getVoiceDetailInfo();
    }
    this.invokerGetLocationsbyTime()

  },
  methods: {
    // 获取语音详情信息
    async getVoiceDetailInfo() {
      try {
        uni.showLoading({ title: '加载语音详情中...', mask: true });
        const res = await getVoiceInfo(this.voiceId);
        if (res.code === 200) {

          uni.hideLoading();
          let data = res.data || {};
          // 获取用户信息
          let user = await this.getUser(data.userId);
          console.log('user', user);
          const { parentNode = {} } = this.findParentCategory(data.categoryCode, this.item_category_options) || {};
          const { parentNode: checkPointParentNode = {} } = this.findParentCategory(data.checkPointId, this.check_point_options) || {};
          console.log(checkPointParentNode, "checkPointParentNode")

          this.formData = {
            ...this.formData,
            ...data,
            inspectUserName: user?.nickName || '',
            createBy: user?.userName || '',
            seizureTime: data.createTime || '',
            inspectUserRoleName: user?.roles[0]?.roleName || '',
            checkMethod: data.postDictCode == 0 ? '' : data.postDictCode || '',
            checkMethodText: data.postLabel == '未知岗位' ? '' : data.postLabel,
            reportTeam: data.teamId || '',
            securityLocation: data.channelId || '',
            forbiddenName: data.name || '',
            isActiveConcealment: '0',
            handlingMethod: 'ABANDON',
            quantity: Number(this.convertQuantityToNumber(data.extractedQuantity)) || 1,
            inspectUserId: data.userId || '',
            forbiddenCategory: parentNode?.id || '',
            forbiddenCategoryText: parentNode?.label || '',
            forbiddenType: data.categoryCode == 'UNKNOWN' ? null : Number(data.categoryCode),
            forbiddenTypeText: data.categoryName === '未分类' ? null : data.categoryName,
            partCategory: checkPointParentNode?.id || null,
            partCategoryText: checkPointParentNode?.label || null,
            partType: data.checkPointId,
            partTypeText: data.checkPointName
          };
          const locationResult = this.getParentLocation(data.channelId, 'id')
          // 安全地处理可能为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;
            this.formData.securityLocation = locationResult.current?.value;
          }




        } else {
          uni.hideLoading();
          uni.showToast({ title: '加载语音详情失败', icon: 'none' });
        }
      } catch (err) {
        uni.hideLoading();
        uni.showToast({ title: '加载语音详情失败', icon: 'none' });
        console.error('加载语音详情失败:', err);
      }
    },
    //根据用户id获取用户信息
    async getUser(userId) {
      try {
        uni.showLoading({ title: '加载用户信息中...', mask: true });
        const res = await getUserInfoById(userId);
        if (res.code === 200) {
          uni.hideLoading();
          return res.data || {};
        } else {
          uni.hideLoading();
          uni.showToast({ title: '加载用户信息失败', icon: 'none' });
          return {};
        }
      } catch (err) {
        uni.hideLoading();
        uni.showToast({ title: '加载用户信息失败', icon: 'none' });
        console.error('加载用户信息失败:', err);
        return {};
      }
    },

    //审批通过
    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);
      }
    },

    // 根据categoryCode在item_category_options中查找匹配元素及其上二级别信息
    findParentCategory(categoryCode, options) {
      if (!categoryCode || !options || !options.length) {
        return null;
      }

      // 递归查找匹配的节点及其上二级别信息
      const findNode = (nodes, targetCode, parentNode = null, grandParentNode = null) => {
        for (const node of nodes) {
          // 如果当前节点匹配
          if (node.code == targetCode || node.id == targetCode) {
            return {
              parentId: node.parentId,
              parentName: node.parentName || node.label,
              // 返回匹配元素本身的信息
              matchedNode: node,
              // 返回上一级别信息（父级）
              parentNode: parentNode,
              // 返回上上一级别信息（父级的父级）
              grandParentNode: grandParentNode,
              // 上上一级别的label和id
              grandParentLabel: grandParentNode?.label || grandParentNode?.parentName || '',
              grandParentId: grandParentNode?.id || grandParentNode?.parentId || ''
            };
          }

          // 如果有子节点，递归查找
          if (node.children && node.children.length > 0) {
            const result = findNode(node.children, targetCode, node, parentNode);
            if (result) return result;
          }
        }
        return null;
      };

      return findNode(options, categoryCode);
    },

    // 将中文数字/阿拉伯数字+量词转换为纯数字
    convertQuantityToNumber(quantityStr) {
      if (!quantityStr || typeof quantityStr !== 'string') return '';

      // 定义中文数字映射
      const chineseNumbers = {
        '零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5,
        '六': 6, '七': 7, '八': 8, '九': 9, '十': 10,
        '壹': 1, '贰': 2, '叁': 3, '肆': 4, '伍': 5, '陆': 6, '柒': 7, '捌': 8, '玖': 9, '拾': 10,
        '两': 2, '俩': 2
      };

      // 定义量词映射（将量词转换为对应的乘数）
      const unitMultipliers = {
        '个': 1, '件': 1, '只': 1, '双': 2, '对': 2,
      };

      let result = quantityStr;

      // 1. 先提取数字部分（阿拉伯数字或中文数字）
      const numberMatch = quantityStr.match(/^(\d+|[一二三四五六七八九十壹贰叁肆伍陆柒捌玖拾两俩零]+)/);
      if (numberMatch) {
        const numberPart = numberMatch[1];

        // 如果是阿拉伯数字，直接使用
        if (/^\d+$/.test(numberPart)) {
          result = parseInt(numberPart, 10);
        } else {
          // 如果是中文数字，转换为阿拉伯数字
          let numberValue = 0;
          let tempValue = 0;

          for (let i = 0; i < numberPart.length; i++) {
            const char = numberPart[i];
            const num = chineseNumbers[char];

            if (num !== undefined) {
              if (num === 10) { // 处理"十"
                if (tempValue === 0) {
                  tempValue = 10;
                } else {
                  tempValue = tempValue * 10;
                }
              } else {
                tempValue += num;
              }
            }
          }

          numberValue = tempValue > 0 ? tempValue : 0;
          result = numberValue;
        }

        // 2. 如果有量词，根据量词进行转换
        const unitMatch = quantityStr.match(/[零一二三四五六七八九十壹贰叁肆伍陆柒捌玖拾两俩\d]+([^\d零一二三四五六七八九十壹贰叁肆伍陆柒捌玖拾两俩]+)$/);
        if (unitMatch && unitMultipliers[unitMatch[1]]) {
          result = result * unitMultipliers[unitMatch[1]];
        }
      }

      console.log(`转换数量: "${quantityStr}" -> ${result}`);

      return result;
    },

    // 播放音频
    playAudio() {
      // 详细日志：检查 audioFilePath
      console.log('=== 播放音频调试信息 ===');
      console.log('原始 audioFilePath:', this.formData.audioFilePath);
      console.log('audioFilePath 类型:', typeof this.formData.audioFilePath);

      if (!this.formData.audioFilePath) {
        console.error('audioFilePath 为空！');
        uni.showToast({ title: '暂无音频文件', icon: 'none' });
        return;
      }

      // 从路径中提取文件名
      // 例如: /uploads/audio/audio_xxx.wav -> audio_xxx.wav 或 audio_xxx.mp3
      const fileName = this.formData.audioFilePath.split('/').pop();
      console.log('提取的文件名:', fileName);

      // 使用新的 8082 端口 Nginx 静态资源服务器
      const audioUrl = `http://airport.samsundot.com:8089/uploads/audio/${fileName}`;
      console.log('完整音频 URL:', audioUrl);
      console.log('========================');

      // 显示加载提示
      uni.showLoading({ title: '准备播放音频...', mask: true });

      // 创建音频上下文并播放
      const innerAudioContext = uni.createInnerAudioContext();

      // 设置音频源
      innerAudioContext.src = audioUrl;
      console.log('已设置 innerAudioContext.src:', innerAudioContext.src);

      // Android 优化配置
      innerAudioContext.obeyMuteSwitch = false; // 不遵循静音开关
      innerAudioContext.mixWithOther = true; // 允许与其他音频混合

      // 不依赖 autoplay，手动调用 play()
      innerAudioContext.autoplay = false;

      // 监听事件：准备播放
      innerAudioContext.onCanplay(() => {
        console.log('✅ onCanplay: 音频可以播放了');
        uni.hideLoading();
        // 手动开始播放
        innerAudioContext.play();
      });

      // 监听事件：开始播放
      innerAudioContext.onPlay(() => {
        console.log('✅ onPlay: 音频开始播放');
        uni.showToast({ title: '正在播放音频', icon: 'none', duration: 1500 });
      });

      // 监听事件：加载中
      innerAudioContext.onWaiting(() => {
        console.log('⏳ onWaiting: 音频加载中...');
      });

      // 监听事件：时间更新
      innerAudioContext.onTimeUpdate(() => {
        const current = innerAudioContext.currentTime;
        const duration = innerAudioContext.duration;
        console.log(`⏱️ 播放进度: ${current.toFixed(2)}s / ${duration.toFixed(2)}s`);
      });

      // 监听事件：播放结束
      innerAudioContext.onEnded(() => {
        console.log('✅ onEnded: 音频播放结束');
        uni.hideLoading();
        innerAudioContext.destroy();
      });

      // 监听事件：播放错误
      innerAudioContext.onError((err) => {
        console.error('❌ onError: 音频播放失败', err);
        console.error('错误详情:', JSON.stringify(err, null, 2));

        uni.hideLoading();

        let errorMsg = '音频播放失败';
        if (err.errCode) {
          errorMsg += ` (错误码: ${err.errCode})`;
        }
        if (err.errMsg) {
          errorMsg += ` - ${err.errMsg}`;
        }

        console.error('完整错误信息:', errorMsg);
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 3000
        });

        innerAudioContext.destroy();
      });

      // 手动触发播放（关键！）
      try {
        console.log('🎵 手动调用 play() 开始播放...');
        innerAudioContext.play();
      } catch (e) {
        console.error('❌ 调用 play() 失败:', e);
        uni.hideLoading();
        uni.showToast({
          title: '播放失败: ' + e.message,
          icon: 'none'
        });
      }

      // 添加超时处理（重要！）
      // setTimeout(() => {

      //   const currentTime = innerAudioContext.currentTime;
      //   console.log('⏱️ 超时检查: currentTime =', currentTime);

      //   if (currentTime === 0) {
      //     console.error('❌ 音频加载超时，10秒内未开始播放');
      //     uni.hideLoading();
      //     uni.showToast({
      //       title: '音频加载超时，请检查网络或文件',
      //       icon: 'none',
      //       duration: 3000
      //     });
      //     innerAudioContext.destroy();
      //   }
      // }, 10000); // 10秒超时
    },

    // 填充表单数据
    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
        // })) : [],
        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,
        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')
        }) || {}
        console.log(curUserInfo, "curUserInfo", this.formData)
        // 修复：只有当打卡数据确实存在时才覆盖securityLocation
        if (curUserInfo.channelCode) {

          this.formData.securityLocation = curUserInfo.channelCode;
          this.formData.securityLocationText = `${curUserInfo?.terminlName}/${curUserInfo?.regionalName}/${curUserInfo?.channelName}`;
        }
        console.log(this.formData.securityLocation, "this.formData.securityLocation");

        this.formData.team = curUserInfo.attendanceTeamId;
        //打卡的优先于语音，所以后请求打卡的数据，先请求语音的，但是如果打卡的数据没有，就不清空语音的数据
        this.formData.reportTeam = curUserInfo.attendanceTeamId ?? this.formData.reportTeam;
        if (curUserInfo.attendanceStationName && curUserInfo.attendanceDepartmentName) {
          this.formData.teamName = `${curUserInfo.attendanceStationName} / ${curUserInfo.attendanceDepartmentName} / ${curUserInfo.attendanceTeamName}`
          this.formData.reportTeamText = curUserInfo.attendanceTeamName ? `${curUserInfo.attendanceStationName} / ${curUserInfo.attendanceDepartmentName} / ${curUserInfo.attendanceTeamName}` : this.formData.reportTeamText
        }
        console.log(this.formData);
        const locationResult = this.getParentLocation(this.formData.securityLocation)
        // 安全地处理可能为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;
        }
      })
    },
    //根据securityLocation,从this.position_options中向上找到前两级别的父级对象和当前级别对象
    getParentLocation(securityLocation, value) {

      if (!securityLocation || !this.position_options || !this.position_options.length) {
        return null;
      }
      const getValue = value || 'value';

      // 递归查找节点及其父级
      const findNodeAndParents = (nodes, targetValue, parents = []) => {
        for (const node of nodes) {
          if (node[getValue] === 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)
        ]);
        // 查询用户岗位列表
        const postListsRes = await getPostListsByUserId(this.currentUser.id);


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




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

        // 岗位  item_check_method_options （x光机  人身检查）字典  item_check_method
        // 处理方式  item_handling_method_options  字典  item_handling_method
        // 单位 units  字典  item_unit
        const dict = await this.useDict(
          // 'item_check_method',
          'item_handling_method',
          'item_unit'
        )




        this.item_check_method_options = postListsRes.data || [];
        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 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) {
      console.log("e.detail.value", e.detail.value)
      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)
      // 安全地处理可能为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;
      }
    },

    // 查获班组变化
    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;
    },

    // 部位类型变化
    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

      // }

      //console.log(this.formData, "this.formData")


      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: '无',
        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(),

      }



      this.formData.inspectUserName = this.userInfo.nickName
      const payload = {
        ...this.formData,
        itemSeizureItemsList: [item],
      };
      console.log(this.formData, "payload")

      return payload
    },

    // 提交表单
    submitForm() {
      console.log("generateNumericID", this.formData)
      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: this.currentUser.roles.includes('banzuzhang') ? 'SEIZURE_REPORT_LEADER' : this.currentUser.roles.includes('SecurityCheck') ? 'SEIZURE_REPORT_STAFF' : '',
        }



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

              deleteVoiceDraft(this.formData.id).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;
  }

  .card {
    border-radius: 12px;
    overflow: hidden;
    margin: 15px 0;
    // overflow: visible;
    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;
    }

    // ::v-deep .uni-collapse-item__wrap {
    //   overflow: visible !important;
    // }
  }

  .userInfo {
    display: flex;
    row-gap: 10px;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;

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