<template>
  <div>
    <el-form :model="maForm" ref="maForm" size="small" :rules="rules" :inline="true" label-width="120px">
      <el-form-item label="领用类型" prop="pickType" v-if="isView">
        <el-select
          v-model="maForm.pickType"
          placeholder="请选择租赁工程"
          filterable
          style="width: 240px"
          @change="changePickType"
        >
          <el-option label="班组" :value="0" />
          <el-option label="项目部" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="租赁工程" prop="proId">
        <el-select
          v-model="maForm.proId"
          placeholder="请选择租赁工程"
          filterable
          style="width: 240px"
          @change="changePro"
        >
          <el-option v-for="(item, index) in projectList" :key="index" :label="item.proName" :value="item.proId" />
        </el-select>
      </el-form-item>
      <el-form-item label="领用项目部" prop="departId" v-if="maForm.pickType == 1">
        <el-select
          v-model="maForm.departId"
          placeholder="请选择项目部"
          filterable
          style="width: 240px"
          @change="changePeoDept"
        >
          <el-option
            v-for="(item, index) in proDeptList"
            :key="index"
            :label="item.departName"
            :value="item.departId"
            :data-key="item.departId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="领用班组" prop="teamId" v-if="maForm.pickType == 0">
        <el-select
          v-model="maForm.teamId"
          placeholder="请选择班组"
          filterable
          style="width: 240px"
          @change="changeTeam"
        >
          <el-option
            v-for="(item, index) in uniteList"
            :key="index"
            :label="item.teamName"
            :value="item.id"
            :data-key="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="领料人" prop="leasePerson">
        <el-input
          v-model="maForm.leasePerson"
          placeholder="请输入领料人"
          :disabled="maForm.pickType == 0"
          maxlength="50"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="relPhone">
        <el-input
          v-model="maForm.relPhone"
          placeholder="请输入联系电话"
          :disabled="!isView"
          clearable
          maxlength="11"
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="标准配置" prop="standardConfig">
        <treeselect
          v-model="maForm.standardConfig"
          :options="standardConfigList"
          :normalizer="normalizer"
          :show-count="true"
          style="width: 240px"
          :disable-branch-nodes="true"
          noChildrenText="没有数据了"
          noOptionsText="没有数据"
          noResultsText="没有搜索结果"
          placeholder="请选择标准配置"
          @select="standardConfigChange"
        />
      </el-form-item>

      <el-form-item label="所属分包" prop="subUnitName" v-if="maForm.pickType == 0">
        <el-input
          v-model="maForm.subUnitName"
          :placeholder="maForm.subUnitName ? '请输入所属分包' : '暂无分包'"
          disabled
          maxlength="50"
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="领料单号" prop="code">
        <el-input v-model="code" placeholder="请输入领料单号" clearable style="width: 240px" />
      </el-form-item>
      <el-button style="width: 100px" type="primary"  @click="handleQuery">查询单号</el-button>

      <el-form-item v-if="maForm.pickType == 1" label="备注" prop="remark">
        <el-input v-model="maForm.remark" placeholder="请输入备注" clearable style="width: 240px" />
      </el-form-item>

      <el-form-item label="类型规格" prop="deviceType">
        <el-row :gutter="10">
          <el-col :span="15">
            <el-select
              ref="typeSelect"
              v-model="tempDeviceType"
              multiple
              filterable
              placeholder="请输入类型规格"
              style="width: 500px"
              @change="handleTypeChange"
              clearable
              collapse-tags
              :filter-method="handleSearchImpl"
              :popper-class="'type-select-dropdown'"
              :popper-append-to-body="false"
              @visible-change="handleVisibleChange"
            >
              <el-option
                v-for="(item, index) in filteredOptions"
                :key="index"
                :label="item.fullPath"
                :value="item.typeId"
                :data-key="index"
              >
                <span v-html="highlightText(item.fullPath, searchKeyword)"></span>
                <span style="float: right; color: #8492a6; font-size: 13px">库存:{{ item.storageNum }}</span>
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input
              ref="searchInput"
              v-model="searchKeyword"
              placeholder="输入类型规格高亮搜索"
              prefix-icon="el-icon-search"
              clearable
              style="width: 300px"
              @input="handleHighlightSearch"
              @focus="handleSearchFocus"
              @click.native="handleSearchClick"
            >
              <template slot="append">
                <span v-if="matchedOptions.length" style="margin: 0 5px">
                  {{ currentMatchIndex + 1 }}/{{ matchedOptions.length }}
                </span>
              </template>
            </el-input>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-truck" size="mini" @click="handleSave(1)">出 库</el-button>
      </el-col>
      <el-col :span="1.5" v-if="maForm.pickType == 0">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleSave(0)">暂 存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="downloadQrCodes()">二维码下载</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList">
      <el-table-column align="center" label="序号" type="index" width="55" />
      <el-table-column align="center" label="物资名称" prop="maTypeName" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" label="规格型号" prop="typeName" show-overflow-tooltip />
      <el-table-column align="center" label="计量单位" prop="unitName" />
      <el-table-column align="center" label="当前库存" prop="storageNum" />
      <el-table-column align="center" label="在用数量" prop="useNum" />
      <el-table-column align="center" label="预领数量" prop="preNum" />
      <el-table-column label="出库数量" prop="outNum" align="center">
        <template v-slot="scope">
          <el-input-number
            v-if="scope.row.manageType == '1'"
            v-model.number="scope.row.outNum"
            controls-position="right"
            style="width: 100%"
            :min="0"
            :precision="scope.row.unitValue == 1 ? 3 : 0"
            @change="
              v =>
                scope.row.unitValue == 1
                  ? (scope.row.outNum = Number(String(v).replace(/[^\d.]/g, '')))
                  : (scope.row.outNum = Number(String(v).replace(/[^\d]/g, '')))
            "
          ></el-input-number>
          <el-button v-else size="mini" type="text" @click="handleOutCode(scope.row)">
            {{ scope.row.maCodeList ? scope.row.maCodeList.length : 0 }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="管理模式" prop="manageType" align="center">
        <template v-slot="{ row }">
          <span>{{ row.manageType == '0' ? '编码管理' : '数量管理' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center" label-width="500px">
        <template v-slot="scope">
          <el-input v-model="scope.row.remark" controls-position="right" style="width: 100%"></el-input>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            style="color: red"
            v-if="!scope.row.alNum || scope.row.alNum == 0"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <OutCodeDlg ref="outCode" @selectOutCode="selectOutCode" />
  </div>
</template>

<script>
import {
  equipmentTypeTree,
  getListProject,
  addApplyInfo,
  updateApplyInfo,
  getApplyInfo,
  getAgreement,
  getBmTeamApi,
  getListsByConfigId,
  getStandardConfigList,
  getLeaseDataByCode,
  getPickDepartListApi,
  getProListByDepartApi
} from '@/api/materialsStation'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import OutCodeDlg from './OutCodeDlg.vue'
import {downloadQrCodesApi} from "@/api/code/code";

export default {
  dicts: ['purchase_task_status'],
  components: { Treeselect, OutCodeDlg },
  props: {
    isEdit: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    isView: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    editTaskId: {
      type: [String, Number],
      default: () => {
        return ''
      }
    },
    editId: {
      type: [String, Number],
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      taskId: '',
      // 遮罩层
      loading: false,
      loadingTwo: false,
      // 选中数组
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      selectTreeProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      //租赁单位
      uniteList: [],
      proDeptList: [],
      //租赁工程
      projectList: [],
      //机具类型
      equipmentTypeList: [],
      // 角色表格数据
      equipmentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      rowData: {},
      unitId: null,
      projectId: null,
      // 查询参数
      queryParams: {
        equipmentId: undefined,
        productionTime: ''
      },
      maForm: {
        pickType: 0,
        teamId: undefined,
        teamName: '',
        proDept: '',
        proDeptName: '',
        projectId: undefined,
        projectName: '',
        arrivalTime: '',
        purchaser: '',
        remark: '',
        purchaseNumber: '',
        standardConfig: undefined,
        bmFileInfos: [],
        proId: undefined,
        relPhone: '',
        leasePerson:''
      },
      code: '',
      standardConfigList: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        teamId: [
          {
            required: true,
            message: '请选择班组',
            trigger: 'blur'
          }
        ],
        departId: [
          {
            required: true,
            message: '请选择项目部',
            trigger: 'blur'
          }
        ],
        proId: [
          {
            required: true,
            message: '请选择租赁工程',
            trigger: 'blur'
          }
        ],
        relPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        bmFileInfos: [
          {
            required: false,
            message: '请上传委托书',
            trigger: 'change'
          }
        ]
      },
      deviceTypeTreeProps: {
        children: 'children',
        label: 'typeName',
        value: 'typeId',
        multiple: true,
        emitPath: true
      },
      deviceType: [],
      propsKey: 1000,
      projectTemp: undefined,
      unitTemp: undefined,
      agreementId: undefined,
      flattenOptions: [],
      typePopoverVisible: false,
      typeOptions: [],
      allTypeList: [],
      flattenTypeOptions: [],
      typeGroups: [], // 分组后的类型选项
      typeGroupsBackup: [], // 备份原始分组数据，用于搜索
      typeMap: new Map(), // 用于快速查找类型数据
      tempDeviceType: [], // 临时选中值
      filteredOptions: [], // 过滤后的选项（用于显示）
      maxShowOptions: 100, // 最大显示选项数
      searchTimer: null, // 用于自定义防抖
      searchKeyword: '', // 高亮搜索关键字
      currentMatchIndex: -1, // 当前匹配项索引
      matchedOptions: [], // 匹配的选项
      keepSelectOpen: false, // 控制下拉框是否保持打开
      isSearching: false, // 添加搜索状态标记

      //是否是分包商
      isFileFbs: false,
      urlTemp: '',
      delBusinessFileIdList: [],
      parentId: undefined
    }
  },
  mounted() {
    this.getStandardConfigListApi()
    console.log('🚀 ~ mounted ~ this.isView:', this.isView)
    if (this.isEdit && this.isView == false) {
      console.log('isEdit', this.isEdit)
      this.taskId = this.editTaskId
      this.id = this.editId
      this.projectInfoList().then(() => {
        this.getTaskInfo()
      })
    } else if (this.isEdit && this.isView) {
      this.projectInfoList()
    }
  },
  watch: {
    'maForm.teamId'(newVal) {
      console.log('🚀 ~ maForm.teamId:', newVal)
      if (newVal && this.maForm.proId) {
        this.getAgreementId()
      } else {
        this.equipmentTypeList = []
      }
    },
    'maForm.proId'(newVal) {
      console.log('🚀 ~ maForm.proId:', newVal)
      if (newVal && this.maForm.teamId) {
        this.getAgreementId()
      } else {
        this.equipmentTypeList = []
      }
    }
  },
  methods: {
    downloadQrCodesApi,
    // 单号查询
    async handleQuery() {
      if (!this.code || String(this.code).trim() === '') {
        this.$message.warning('请输入领料单号')
        return
      }

      const loading = this.$loading({ text: '加载中...' })
      try {
        const params = { code: this.code }
        const res = await getLeaseDataByCode(params)
        // 处理接口返回
        if (!res || (!res.data && res.code !== 200)) {
          this.$message.error(res.msg || '未查询到该单号信息')
          return
        }

        const payload = res.data || res // 兼容不同后端包装
        const leaseApplyInfo = payload.leaseApplyInfo || payload.leaseApplyInfoVo || payload.leaseApplyInfoVo || {}
        const leaseApplyDetailsList = payload.leaseApplyDetailsList || payload.detailsList || []

        if (!leaseApplyInfo || !leaseApplyInfo.proId) {
          this.$message.error('返回结果缺少工程信息(proId)，无法继续')
          return
        }

        const isProIdValid = this.projectList.some(item => String(item.proId) == String(leaseApplyInfo.proId))

        if (!isProIdValid) {
          this.$message.warning('该领料单号不属于您负责的工程')
          return
        }

        // 自动带入工程（不论用户是否先选工程）
        this.maForm.proId = leaseApplyInfo.proId
        // 如果 projectList 中存在对应项，带入 projectId（你原 code 使用 projectId 字段关联）
        const matchedProject = this.projectList.find(item => String(item.proId) == String(leaseApplyInfo.proId))
        if (matchedProject) {
          this.maForm.projectId = matchedProject.projectId || matchedProject.projectId
        }
        // 回显其它基础字段
        // Object.assign(this.maForm, leaseApplyInfo)
        this.maForm.relPhone = leaseApplyInfo.phone || leaseApplyInfo.relPhone || this.maForm.relPhone || ''
        // 拉取班组（带入工程后需要取班组信息）
        await this.getBmTeam()

        console.log('开始加载类型数据...')
        await this.getAgreementId()
        console.log('flattenTypeOptions 加载前:', this.flattenTypeOptions)

        // 如果 equipmentType() 并不是在 getAgreementId 内被 await 到（保险起见），再主动等待一次 equipmentType
        if (!this.flattenTypeOptions || this.flattenTypeOptions.length === 0) {
          console.log('等待 equipmentType 数据加载...')
          // 直接调用 equipmentType 并等待
          await this.equipmentType()
        }
        console.log('flattenTypeOptions 加载后:', this.flattenTypeOptions)
        // 类型树已加载完毕，映射明细到列表
        this.mapLeaseDetailsToList(leaseApplyDetailsList)

        // 成功提示
        this.$message.success('单号数据已加载并带入页面')
      } catch (error) {
        console.error('handleQuery error:', error)
        this.$message.error('查询失败，请稍后重试')
      } finally {
        loading.close()
      }
    },
    mapLeaseDetailsToList(leaseApplyDetailsList = []) {
      if (!Array.isArray(leaseApplyDetailsList) || leaseApplyDetailsList.length === 0) {
        this.equipmentList = []
        return
      }

      const mapped = []
      leaseApplyDetailsList.forEach(detail => {
        const detailTypeId = detail.typeId
        console.log('detailTypeId:', detailTypeId)
        // 检查 flattenTypeOptions 是否存在且有数据
        if (!this.flattenTypeOptions || this.flattenTypeOptions.length === 0) {
          console.warn('flattenTypeOptions 为空，无法查找 typeId')
          return
        }
        // 在扁平化的 options 中查找（第四级叶子）
        const typeData = this.flattenTypeOptions.find(item => {
          return String(item.typeId).trim() === String(detailTypeId).trim()
        })

        if (typeData) {
          const item = {
            ...typeData,
            // 保留原来的字段名，注意数值/字符串处理按需求调整
            preNum: 0,
            // 优先使用 outNum，如果没有用 preNum
            outNum: detail.outNum != null ? detail.outNum : 0,
            parentId: detail.parentId || this.parentId || undefined,
            // 后端可能字段名为 maCodeVoList / maCodeList / maCode，保底取空数组
            maCodeList: detail.maCodeList || detail.maCodeVoList || detail.maCode || [],
            // 后端字段可能是 menageType 或 manageType，统一放到 manageType 字段（字符串 '0' / '1'）
            manageType: String(
              detail.menageType != null
                ? detail.menageType
                : detail.manageType != null
                ? detail.manageType
                : typeData.manageType || '1'
            ),
            remark: detail.remark || '',
            // 保留一些后端明细字段以便后续使用
            _rawDetail: detail
          }
          mapped.push(item)
        } else {
          // 若未在类型树中找到对应的 typeId，依然把它放进列表（避免丢数据），并打印警告
          console.warn(`未在类型树中找到 typeId=${detailTypeId}，已将该明细以最小结构加入 equipmentList`)
          const item = {
            typeId: detailTypeId,
            typeName: detail.typeName || '未知规格',
            maTypeName: detail.maTypeName || '',
            unitName: detail.unitName || '',
            storageNum: detail.storageNum || 0,
            preNum: detail.preNum || 0,
            outNum: detail.outNum != null ? detail.outNum : detail.preNum != null ? detail.preNum : 0,
            parentId: detail.parentId || this.parentId || undefined,
            maCodeList: detail.maCodeList || detail.maCodeVoList || [],
            manageType: String(
              detail.menageType != null ? detail.menageType : detail.manageType != null ? detail.manageType : '1'
            ),
            remark: detail.remark || '',
            _rawDetail: detail
          }
          mapped.push(item)
        }
      })

      // 按照你现有的添加逻辑，放到 equipmentList（这里直接替换）
      this.equipmentList = mapped

      // 如果有 parentId，保留第一个明细的 parentId
      if (mapped.length > 0) {
        this.parentId = mapped[0].parentId
      }

      // 维护 deviceType 备份（反显已经选中的类型）
      this.deviceType = this.equipmentList.map(i => i.typeId)
    },
    // 获取协议id
    async getAgreementId() {
      return new Promise((resolve, reject) => {
        getAgreement({
          teamId: this.maForm.teamId,
          proId: this.maForm.proId
        })
          .then(res => {
            console.log('🚀 ~ getAgreementId ~ res:', res)
            if (!res.data || !Array.isArray(res.data)) {
              this.agreementId = []
              this.equipmentTypeList = []
              resolve([])
              return
            }
            this.agreementId = res.data
            // 等待 equipmentType 完成
            this.equipmentType()
              .then(() => {
                resolve(res.data)
              })
              .catch(reject)
          })
          .catch(reject)
      })
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 获取班组
    async getBmTeam() {
      try {
        const idCard = sessionStorage.getItem('idCard')
        const res = await getBmTeamApi({ isAll: 0, idCard, projectId: this.maForm.projectId })
        if (!res.data || res.data.length === 0) return
        this.uniteList = res.data
        console.log('xxxxxxxxxxxxxxxxxxxxxx', this.maForm.projectId)
        console.log('yyyyyyyyyyyyyyyyyyyyyy', this.isEdit, this.isView)
        if (this.isEdit && this.isView == false) {
          const team = this.uniteList.find(item => item.teamName == this.maForm.teamName)
          this.maForm.teamId = team.id
          this.maForm.teamName = team.teamName
          if (this.maForm.pickType==0){
            this.maForm.leasePerson = team.relName
            this.maForm.relPhone = team.relPhone || ''
          }
          this.maForm.relName = team.relName
          this.maForm.teamLeaderIdCard = team.teamLeaderIdCard
          this.maForm.subUnitName = team.subUnitName || ''
        } else {
          this.maForm.teamId = res.data[0].id
          this.maForm.teamName = res.data[0].teamName
          if (this.maForm.pickType==0){
            this.maForm.leasePerson = res.data[0].relName
            this.maForm.relPhone = res.data[0].relPhone || ''
          }
          this.maForm.relName = res.data[0].relName
          this.maForm.teamLeaderIdCard = res.data[0].teamLeaderIdCard
          this.maForm.subUnitName = res.data[0].subUnitName || ''
        }
        // this.projectInfoList()
      } catch (error) {
        console.log('🚀 ~ getBmTeam ~ error:', error)
      }
    },
    // 获取项目部列表
    async getProDeptList() {
      try {
        const res = await getPickDepartListApi({ proId: this.maForm.projectId })
        this.proDeptList = res.data
      } catch (error) {
        console.log('🚀 ~ getProDeptList ~ error:', error)
      }
    },
    changePickType() {
      this.equipmentList = []
      this.filteredOptions = []
      if (this.maForm.proId && this.maForm.pickType == 0) {
        this.maForm.departId = ''
        this.getBmTeam()
      } else if (this.maForm.proId && this.maForm.pickType == 1) {
        this.maForm.teamId = ''
        this.maForm.leasePerson = ''
        this.maForm.relPhone = ''
        this.getProDeptList()
      }
    },
    async changePro(e) {
      console.log('🚀 ~ changePro ~ e:', e)
      this.maForm.proId = e
      this.maForm.projectId = this.projectList.find(item => item.proId == e)?.projectId
      this.maForm.teamId = ''
      this.maForm.leasePerson = ''
      this.equipmentList = []
      if (this.maForm.pickType == 0) {
        await this.getBmTeam()
      } else if (this.maForm.pickType == 1) {
        this.getProDeptList()
      }
    },
    changePeoDept(e) {
      console.log('🚀 ~ changePeoDept ~ e:', e)
      // 获取部门信息
      const dept = this.proDeptList.find(item => item.departId === e)
      this.maForm.teamId = dept.departId
      console.log('🚀 ~ changePeoDept ~ this.maForm.teamId:', this.maForm.teamId)
      this.maForm.teamName = dept.departName
      console.log('🚀 ~ changePeoDept ~ this.maForm.teamName:', this.maForm.teamName)
    },
    changeTeam(e) {
      console.log('🚀 ~ changeTeam ~ e:', e)
      // 查找对应的teamName
      const team = this.uniteList.find(item => item.id === e)
      this.maForm.teamName = team ? team.teamName : ''
      this.maForm.leasePerson = team ? team.relName : ''
      this.maForm.relName = team.relName
      this.maForm.relPhone = team.relPhone || ''
      this.maForm.phone = team.relPhone || ''
      this.maForm.teamLeaderIdCard = team.teamLeaderIdCard
      this.maForm.subUnitName = team.subUnitName || ''
      console.log('🚀 ~ changeTeam ~ this.maForm.teamName:', this.maForm.teamName)
      // this.projectInfoList()
    },
    /** 租赁单位和工程-下拉选 */
    async projectInfoList() {
      try {

        // const res = await getProListByDepartApi({ teamName: this.maForm.teamName })
        const res = await getListProject({ unitId: null, isApp: true, teamName: this.maForm.teamName })
        this.projectList = res.data
      } catch (error) {
        console.log('🚀 ~ projectInfoList ~ error:', error)
      }
    },
    /** 机具类型 */
    equipmentType() {
      const loading = this.$loading()
      // 返回 promise 以便外部 await
      return new Promise((resolve, reject) => {
        equipmentTypeTree({
          agreementIdList: this.agreementId,
          proId: this.maForm.proId,
          // teamId: this.maForm.teamId,
          teamName: this.maForm.teamName
        })
          .then(response => {
            this.equipmentTypeList = response.data || []
            // 处理并扁平化所有类型数据
            this.flattenTypeOptions = this.processTypeData(this.equipmentTypeList || [])
            // 初始显示所有选项
            this.filteredOptions = [...this.flattenTypeOptions]

            // 反显选中数据（如果已有 equipmentList）
            if (this.equipmentList.length > 0) {
              this.deviceType = this.equipmentList.map(item => item.typeId)
            }
            resolve(this.flattenTypeOptions)
          })
          .catch(err => {
            console.error('equipmentType error:', err)
            reject(err)
          })
          .finally(() => {
            loading.close()
          })
      })
    },
    // 处理类型数据
    processTypeData(data) {
      const result = []

      const traverse = (node, parents = []) => {
        const path = [...parents, node.typeName]

        if (!node.children || node.children.length === 0) {
          result.push({
            typeId: node.typeId,
            typeName: node.typeName,
            fullPath: path.join(' / '),
            searchKey: path.join('').toLowerCase(),
            storageNum: node.num || 0,
            maTypeName: parents[parents.length - 1] || '',
            specificationType: node.typeName,
            unitName: node.unitName,
            unitValue: node.unitValue,
            maxSortPriority: node.maxSortPriority,
            manageType: node.manageType,
            useNum: node.useNum
          })
        }

        if (node.children) {
          node.children.forEach(child => traverse(child, path))
        }
      }

      data.forEach(node => traverse(node))

      // 根据Api接口返回的Node节点中的 maxSortPriority字段 进行从大到小的排序
      result.sort((a, b) => b.maxSortPriority - a.maxSortPriority)

      return result
    },
    // 搜索处理函数
    handleSearchImpl(query) {
      console.log('🚀 ~ handleSearchImpl ~ query:', query)
      if (!query) {
        this.filteredOptions = [...this.flattenTypeOptions]
        return
      }

      const lowercaseQuery = query.toLowerCase()
      this.filteredOptions = this.flattenTypeOptions.filter(
        item => item.searchKey.includes(lowercaseQuery) || item.fullPath.toLowerCase().includes(lowercaseQuery)
      )
    },
    // 选择变化处理
    handleTypeChange(val) {
      console.log('🚀 ~ handleTypeChange ~ val:', val)
      if (!val || val.length === 0) return

      // 获取新选中的项
      const lastSelected = val[val.length - 1]
      console.log('🚀 ~ handleTypeChange ~ lastSelected:', lastSelected)
      const typeData = this.flattenTypeOptions.find(item => item.typeId === lastSelected)
      console.log('🚀 ~ handleTypeChange ~ typeData:', typeData)

      if (typeData) {
        if (this.equipmentList.some(item => item.typeId === lastSelected)) {
          this.$message({
            message: `${typeData.typeName} 已添加到列表中`,
            type: 'warning'
          })
          this.tempDeviceType = this.tempDeviceType.filter(id => id !== lastSelected)
        } else {
          // 将新项添加到数组开头，实现倒序
          this.equipmentList.unshift({
            ...typeData,
            preNum: 0,
            outNum: 0,
            parentId: this.parentId,
            maCodeList: []
          })
          this.deviceType.push(lastSelected)
          this.$message({
            message: `已添加 ${typeData.typeName}`,
            type: 'success'
          })
        }
        console.log('🚀 ~ handleTypeChange ~ this.equipmentList:', this.equipmentList)
      }

      // 清空临时选中值
      this.$nextTick(() => {
        this.tempDeviceType = []
      })
    },
    //获取任务详情--- 编辑回显数据
    async getTaskInfo() {
      // this.loading = true;
      await getApplyInfo(this.id).then(response => {
        if (response.msg && response.msg != '操作成功') {
          this.$message.warning(response.msg)
        }
        Object.assign(this.maForm, response.data.leaseApplyInfo)
        this.maForm.pickType = 0
        this.maForm.proId = String(response.data.leaseApplyInfo.proId)
        console.log("xxxxxxyyy", this.maForm.proId)
        this.maForm.projectId = this.projectList.find(
          item => item.proId == response.data.leaseApplyInfo.proId
        )?.projectId
        this.maForm.relPhone = response.data.leaseApplyInfo.phone || response.data.leaseApplyInfo.relPhone || ''
        this.getBmTeam()
        this.equipmentList = response.data.leaseApplyDetailsList || []
        if (this.equipmentList.length > 0) {
          this.equipmentList.forEach(item => {
            // item.preNum = item.preNum || 0
            item.outNum = item.preNum || 0
            item.maCodeList = item.maCodeList || item.maCodeVoList || []
          })
          this.parentId = this.equipmentList[0].parentId
          console.log('🚀 ~ awaitgetApplyInfo ~ this.parentId:', this.parentId)
        }
        this.getAgreementId()
        // 如果 bmFileInfos有值
        if (this.maForm.bmFileInfos.length > 0) {
          this.isFileFbs = true
        }
        // this.loading = false;
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 获取标准配置
    async getStandardConfigListApi() {
      try {
        const res = await getStandardConfigList()
        console.log('🚀 ~ getStandardConfigList ~ res:', res)
        this.standardConfigList = res.data
      } catch (error) {
        console.log('🚀  ~ error:', error)
      }
    },
    async standardConfigChange(val) {
      console.log('🚀 ~ standardConfigChange ~ val:', val)
      const loading = this.$loading()
      try {
        const params = {
          configId: val.id
        }
        const res = await getListsByConfigId(params)
        console.log('🚀 ~ standardConfigChange ~ res:', res)

        res.data.forEach(newItem => {
          const existingItem = this.equipmentList.find(item => item.typeId === newItem.typeId)
          if (existingItem) {
            existingItem.preNum += newItem.preNum
          } else {
            this.equipmentList.unshift(newItem)
          }
        })

        loading.close()
      } catch (error) {
        console.log('🚀  ~ error:', error)
        loading.close()
      }
    },
    /** 保存按钮操作 */
    handleSave(isOut) {
      console.log('maForm', this.maForm)
      if (this.equipmentList.length > 0) {
        this.$refs['maForm'].validate(async valid => {
          if (valid) {
            for (let i = 0; i < this.equipmentList.length; i++) {
              if (this.equipmentList[i].outNum > this.equipmentList[i].storageNum) {
                this.$message.error(`第 ${i + 1} 行的 ${'出库数量不可大于库存量'} `)
                return
              } else if (
                this.equipmentList[i].outNum == 0 ||
                (this.equipmentList[i].manageType == 0 && this.equipmentList[i].maCodeList.length == 0)
              ) {
                this.$message.error(`第 ${i + 1} 行 ${'请输入出库数量'} `)
                return
              }
            }
            this.equipmentList.forEach(item => {
              item.preNum = item.outNum
            })
            console.log('projectId', this.projectTemp)
            this.maForm.taskId = this.taskId
            this.maForm.phone = this.maForm.relPhone
            await this.$modal
              .confirm('是否确认保存当前页面')
              .then(() => {
                this.loading = true
                this.maForm.isOut = isOut
                this.maForm.createBy = sessionStorage.getItem('userName')
                if (this.isEdit && this.isView == false) {
                  this.maForm.leaseProjectId = this.maForm.proId
                  console.log('编辑')
                  updateApplyInfo({
                    leaseApplyDetailsList: this.equipmentList,
                    leaseApplyInfo: this.maForm
                  })
                    .then(response => {
                      if (response.code == 200) {
                        this.$modal.msgSuccess('操作成功')
                        // this.$emit('addToolsSuccess')
                        this.$tab.refreshPage({ path: this.$route.path })
                      }
                      this.loading = false
                    })
                    .catch(() => {
                      this.loading = false
                    })
                } else if (this.isEdit && this.isView) {
                  console.log('新增')
                  addApplyInfo({
                    leaseApplyDetailsList: this.equipmentList,
                    leaseApplyInfo: this.maForm
                  })
                    .then(response => {
                      if (response.code == 200) {
                        this.$modal.msgSuccess('操作成功')
                        // this.$emit('addToolsSuccess')
                        this.$tab.refreshPage({ path: this.$route.path })
                      }
                      this.loading = false
                    })
                    .catch(() => {
                      this.loading = false
                    })
                }
              })
              .catch(() => {})
          }
        })
      } else {
        this.$modal.msgError('请先添加类型规格')
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除所选择的数据项？')
        .then(() => {
          this.equipmentList = this.equipmentList.filter(item => item.typeId !== row.typeId)
          // 更新实际存储的选中值
          this.deviceType = this.equipmentList.map(item => item.typeId)
        })
        .catch(() => {})
    },
    // 二维码下载
    async downloadQrCodes() {
      try {
        // 1. 获取所有“编码管理”的数据行
        const codeManagedRows = this.equipmentList.filter(row => row.manageType == '0')

        if (codeManagedRows.length === 0) {
          this.$message.warning('当前列表中没有编码管理的数据')
          return
        }

        // 2. 汇总所有的 maCodeList
        const maCodeList = []
        codeManagedRows.forEach(row => {
          if (Array.isArray(row.maCodeList) && row.maCodeList.length > 0) {
            row.maCodeList.forEach(codeItem => {
              maCodeList.push({
                ...codeItem,
                typeName: row.typeName,
                model: row.model,
              })
            })
          }
        })

        if (maCodeList.length === 0) {
          this.$message.warning('没有可下载的二维码数据（未选择编码或编码为空）')
          return
        }
        console.log("编码列表",maCodeList)
        const payload = {
          maCodeList: maCodeList,
        }
        this.downloadZip(
          '/material/material_lease_apply_info/downloadQrCode',
          JSON.stringify(payload),
          `QrCode_${new Date().toISOString().slice(0, 10)}.zip`
        )
      } catch (err) {
        console.error('downloadQrCodes error:', err)
        this.$message.error('二维码下载失败，请稍后重试')
      }
    },
    // 打开出库编码弹窗
    handleOutCode(row) {
      this.rowData = row
      this.$refs.outCode.handleOpenCode({ ...row, teamId: this.maForm.teamId, proId: this.maForm.proId })
    },
    // 选择的出库编码
    selectOutCode(val) {
      console.log('🚀 ~ selectOutCode ~ val:', val)
      this.$set(this.rowData, 'outNum', val.length)
      this.$set(this.rowData, 'maCodeList', val)
    },
    // 高亮文本
    highlightText(text, keyword) {
      if (!keyword) return text
      const reg = new RegExp(keyword, 'gi')
      return text.replace(reg, match => `<span class="highlight-text">${match}</span>`)
    },

    // 处理下拉框可见性变化
    handleVisibleChange(visible) {
      if (!visible && this.keepSelectOpen && !this.isSearching) {
        // 只有在非搜索状态下才重新打开下拉框
        this.$nextTick(() => {
          this.$refs.typeSelect.focus()
        })
      }
    },

    // 处理搜索框点击
    handleSearchClick() {
      this.isSearching = true
      this.keepSelectOpen = true
      // 确保下拉框打开
      this.$refs.typeSelect.focus()
      // 立即将焦点返回给搜索框
      this.$nextTick(() => {
        this.$refs.searchInput.focus()
      })
    },

    // 处理搜索框获得焦点
    handleSearchFocus() {
      this.isSearching = true
      if (!this.$refs.typeSelect.visible) {
        this.$refs.typeSelect.focus()
        this.$nextTick(() => {
          this.$refs.searchInput.focus()
        })
      }
    },

    // 高亮搜索处理
    handleHighlightSearch() {
      this.isSearching = true
      this.keepSelectOpen = true

      if (!this.searchKeyword) {
        this.currentMatchIndex = -1
        this.matchedOptions = []
        return
      }

      // 找到所有匹配项
      this.matchedOptions = this.filteredOptions.filter(item =>
        item.fullPath.toLowerCase().includes(this.searchKeyword.toLowerCase())
      )

      if (this.matchedOptions.length > 0) {
        this.currentMatchIndex = 0
        this.$nextTick(() => {
          this.scrollToMatch()
        })
      }
    },

    // 滚动到匹配项
    scrollToMatch() {
      if (this.currentMatchIndex === -1 || !this.matchedOptions.length) return

      const option = this.matchedOptions[this.currentMatchIndex]
      const selectDom = this.$el.querySelector('.type-select-dropdown')
      const optionDom = selectDom?.querySelector(`[data-key="${option.typeId}"]`)
      if (optionDom) {
        optionDom.scrollIntoView({ block: 'center', behavior: 'smooth' })
      }
    }
  },
  // 添加组件销毁时的清理
  beforeDestroy() {
    this.keepSelectOpen = false
    this.isSearching = false
  }
}
</script>
<style lang="scss" scoped>
//隐藏图片上传框的css
::v-deep.disabledFbs {
  .el-upload--picture-card {
    display: none;
  }
}
::v-deep .el-upload-list__item {
  margin-bottom: 20px;
  overflow: unset !important;
}
::v-deep .el-upload-list__item-actions {
  overflow: unset !important;
}

.popper-select {
  .el-cascader-panel .el-scrollbar .el-checkbox {
    display: none;
  }

  .el-cascader-panel .el-scrollbar:nth-child(4) .el-checkbox {
    display: block !important;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-icon-arrow-down.is-reverse {
  transform: rotateZ(180deg);
}

// .el-tree {
//   max-height: 300px;
//   overflow-y: auto;
// }

::v-deep .highlight-text {
  background-color: #ffd04b;
  color: #000;
}

::v-deep .el-input-group__append {
  padding: 0;
  .el-button {
    padding: 0 10px;
    border: none;
    height: 100%;
    &:first-child {
      border-right: 1px solid #dcdfe6;
    }
    &[disabled] {
      color: #c0c4cc;
    }
  }
}

.type-select-dropdown {
  .el-select-dropdown__wrap {
    max-height: 400px !important;
  }

  .el-select-dropdown__item {
    height: auto;
    padding: 8px 20px;
    white-space: normal;
    word-break: break-all;
  }
}

.el-input-group__append {
  padding: 0;
  .el-button {
    padding: 0 10px;
    border: none;
    height: 100%;
    &:first-child {
      border-right: 1px solid #dcdfe6;
    }
    &[disabled] {
      color: #c0c4cc;
    }
  }
}

.el-upload-list__item-thumbnail {
  height: 145px !important;
}

.picture-card-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.picture-card {
  width: 100%;
  height: 100%;
  object-fit: cover;
  justify-content: center;

  // border: 1px solid  #ddd;
  // border-radius: 4px;
}

.file-name {
  width: 90%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  position: absolute;
  bottom: -35px;
  margin-top: 8px;
  text-align: center;
  font-size: 12px;
  color: #333;
  z-index: 999999;
}

.file-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 20px;
}
</style>
