<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :rules="queryRules"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-row>
        <el-form-item label="退料工程" prop="proId">
          <el-select
            v-if="backId == ''"
            v-model="queryParams.proId"
            placeholder="请选择退料工程"
            style="width: 240px"
            clearable
            filterable
            @change="handleProChange"
          >
            <el-option v-for="item in proList" :key="item.id" :label="item.proName" :value="item.proId"></el-option>
          </el-select>
          <el-input v-else v-model="queryParams.proName" disabled style="width: 240px" />
        </el-form-item>
        <el-form-item label="退料班组" prop="teamId">
          <el-select
            v-if="backId == ''"
            v-model="queryParams.teamId"
            :disabled="backId != ''"
            placeholder="请选择班组"
            clearable
            filterable
            style="width: 240px"
            @change="changeTeam"
          >
            <el-option
              v-for="(item, index) in teamList"
              :key="index"
              :label="item.teamName"
              :value="item.id"
              :data-key="item.id"
            />
          </el-select>
          <el-input v-else v-model="queryParams.teamName" disabled style="width: 240px" />
        </el-form-item>
        <el-form-item label="班组长" prop="backPerson">
          <el-input v-model="queryParams.backPerson" placeholder="请输入班组长" disabled style="width: 240px" />
        </el-form-item>
        <el-form-item label="班组长电话" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入班组长电话"
            clearable
            style="width: 240px"
            :maxlength="11"
          />
        </el-form-item>
      </el-row>
      <el-row :gutter="24" style="display: flex; align-items: center">
        <el-col :span="1.5" style="text-align: center; margin-left: 20px">
          <span style="color: red">*</span>
          <span style="font-size: 14px; font-weight: 600; color: #606266">物品类型</span>
        </el-col>
        <el-col :span="7">
          <el-select
            ref="typeSelect"
            v-model="tempDeviceType"
            multiple
            filterable
            placeholder="请输入物品类型"
            style="width: 400px"
            @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 in filteredOptions"
              :key="item.typeId"
              :label="item.fullPath"
              :value="item.typeId"
              :data-key="item.typeId"
            >
              <span v-html="highlightText(item.fullPath, searchKeyword)"></span>
              <span style="float: right; color: #8492a6; font-size: 13px">出库:{{ item.num }}</span>
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <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-form-item label="备注" prop="roleName">
          <el-input
            v-model="queryParams.remark"
            placeholder="请输入备注"
            clearable
            rows="2"
            maxlength="100"
            type="textarea"
            style="width: 240px"
          />
        </el-form-item>
      </el-row>
    </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="handleAdd(1)">退 料</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd(0)">暂 存</el-button>
      </el-col>
      <el-col :span="1.5"></el-col>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" min-width="55" align="center" :selectable="selectable" />
      <el-table-column label="序号" type="index" align="center" min-width="80" />
      <el-table-column label="物资名称" align="center" prop="maTypeName" :show-overflow-tooltip="true" />
      <el-table-column label="规格型号" align="center" prop="typeName" :show-overflow-tooltip="true" />
      <el-table-column label="计量单位" align="center" prop="unitName" />
      <el-table-column label="当前在用量" align="center" prop="num"></el-table-column>
      <el-table-column label="管理模式" align="center" prop="manageType">
        <template slot-scope="scope">
          <!-- 0编码1数量 -->
          <div v-if="scope.row.manageType == 0">编码管理</div>
          <div v-if="scope.row.manageType == 1">数量管理</div>
        </template>
      </el-table-column>
      <el-table-column label="退料数量" align="center" prop="preNum" min-width="100">
        <template slot-scope="scope">
          <span
            style="color: rgb(2, 167, 240); cursor: pointer"
            @click="openAddCode(scope.row)"
            v-if="scope.row.manageType == 0"
          >
            {{ scope.row.preNum > 0 ? scope.row.preNum : '添加编码' }}
          </span>
          <el-input-number
            v-if="scope.row.manageType == 1"
            v-model.number="scope.row.preNum"
            controls-position="right"
            placeholder="退料数量"
            :min="0"
            :precision="scope.row.unitValue == 1 ? 3 : 0"
            @input="checkNum(scope.row)"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column label="损坏价值判定" align="center" prop="apDetection" min-width="120">
        <template slot-scope="scope">
          <el-input
            v-model.number="scope.row.apDetection"
            placeholder="损坏价值判定"
            type="text"
            clearable
            maxlength="20"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" min-width="120">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remark" placeholder="备注" clearable maxlength="100" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100px">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="编码退料" :visible.sync="open" width="1200px" append-to-body>
      <el-table
        :data="machineList"
        width="100%"
        ref="codeTableList"
        height="450px"
        row-key="maId"
        @selection-change="codeSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column
          label="物资名称"
          prop="materialName"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="规格型号"
          prop="typeName"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="设备编码" prop="maCode" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="设备状态" prop="maStatusName" align="center" :show-overflow-tooltip="true">
          <!-- <template slot-scope="scope">
            <dict-tag :options="dict.type.ma_machine_status" :value="scope.row.maStatus" />
          </template> -->
        </el-table-column>
        <el-table-column
          label="损坏价值判断"
          prop="apDetection"
          align="center"
          width="160"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-input
              v-model.number="scope.row.apDetection"
              placeholder="损坏价值判断"
              maxlength="20"
              type="text"
              clearable
              style="width: 100%"
            />
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%; height: 50px; display: flex; justify-content: flex-end; align-items: center">
        <el-button type="primary" size="mini" @click="saveDevCode">保存</el-button>
        <el-button type="normal" size="mini" @click="open = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 图片查看弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="500px" height="500px">
      <img width="100%" height="500px" :src="dialogImageUrl" />
    </el-dialog>
  </div>
</template>

<script>
import {
  getListProject,
  getAgreementInfoByIdBackApi,
  getDeviceTreeByAgreementId,
  addBackApply,
  getBackApplyInfo,
  editBackApply,
  getMachineById,
  getTeamListApi
} from '@/api/materialsStation'
import { mapState } from 'vuex'
import { getToken } from '@/utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  components: { Treeselect },
  name: 'ReturnApplyAdd',
  dicts: ['ma_machine_status'],
  props: {
    backId: {
      type: [String, Number]
    },
    agreementId: {
      type: [String, Number]
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      rowData: {},
      maId: '',
      maData: {},
      maCodeList: [], //编码表格
      tempMaCodeList: [], //编码表格
      machineList: [], // 编码下拉选 集合
      //图片查看弹窗
      dialogImageUrl: '',
      dialogVisible: false,
      fileData: {},
      //上传
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/file/upload'
      },
      selectTreeProps: {
        children: 'children',
        label: 'name',
        // multiple: false,
        value: 'id'
        // multiple: true,
      },
      unitList: [], //单位 集合
      teamList: [], //班组 集合
      proList: [], // 工程 集合
      unitId: null,
      lastUnitId: null,
      projectId: null,
      lastProjectId: null,
      // 查询参数
      queryParams: {
        teamId: null,
        proId: null,
        agreementId: null, //协议id
        agreementIds: [],
        agreementCode: null, //协议code
        // companyId: '', //登录信息中取
        // createBy: '', //用户名
        // backTime: '', //申请时间
        //班组长信息
        backPerson: '',
        phone: '',
        remark: '',
        //退料详情集合
        equipmentList: []
      },
      equipmentList: [],
      //退料详情单条模板
      leaseApplyDetailsItem: {
        createBy: null,
        // companyId: null,
        status: 0,
        typeId: null, //  树结构第4级   规格id
        typeName: '', //显示的设备类型
        typeCode: '', //显示的设备规格
        unitName: '', //显示的设备 单位
        useNum: '', //当前在用量
        remark: '', //单条备注
        preNum: 1 //预领数量
      },
      //
      queryRules: {
        teamId: [
          {
            required: true,
            message: '请选择退料班组',
            trigger: 'change'
          }
        ],
        proId: [
          {
            required: true,
            message: '请选择退料工程',
            trigger: 'change'
          }
        ],
        phone: [
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },

      deviceTypeTree: [], // 设备 树结构数据
      // 设备 树显示 配置
      deviceTypeTreeProps: {
        children: 'children',
        label: 'typeName',
        // multiple: false,
        value: 'typeId',
        multiple: true
      },
      // 选中的设备类型
      deviceType: [],
      createBy: '',
      rowId: '',
      propsKey: 1000,
      flattenOptions: [], // 扁平化后的选项数据
      typePopoverVisible: false,
      typeOptions: [], // 类型选项
      typeLoading: false, // 搜索加载状态
      allTypeList: [], // 所有类型数据
      flattenTypeOptions: [], // 扁平化后的选项数据（缓存所有选项）
      typeGroups: [], // 分组后的类型选项
      typeGroupsBackup: [], // 备份原始分组数据，用于搜索
      typeMap: new Map(), // 用于快速查找类型数据
      tempDeviceType: [], // 临时选中值
      filteredOptions: [], // 过滤后的选项（用于显示）
      maxShowOptions: 100, // 最大显示选项数
      searchTimer: null, // 用于自定义防抖
      searchKeyword: '', // 高亮搜索关键字
      currentMatchIndex: -1, // 当前匹配项索引
      matchedOptions: [], // 匹配的选项
      keepSelectOpen: false, // 控制下拉框是否保持打开
      isSearching: false // 添加搜索状态标记
    }
  },
  mounted() {
    // this.GetUnitData()
    this.GetProData()
    if (this.backId) {
      //编辑
      this.rowId = this.backId
      this.GetViewByApply()
    }
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    changeTeam(val) {
      console.log('🚀 ~ changeTeam ~ val:', val, this.queryParams)
      const team = this.teamList.find(item => item.id === val)
      this.queryParams.backPerson = team ? team.relName : ''
      this.queryParams.teamName = team ? team.teamName : ''
      this.queryParams.relName = team ? team.relName : ''
      this.queryParams.phone = team ? team.relPhone : ''
      // this.GetProData()
      setTimeout(() => {
        this.GetAgreementInfoById()
      }, 300)
    },
    handleProChange(val) {
      console.log('🚀 ~ handleProChange ~ val:', val, this.queryParams)
      this.GetUnitData()
    },
    // 获取 来往单位 列表数据
    async GetUnitData() {
      try {
        const res = await getTeamListApi({ isAll: 0, proId: this.queryParams.proId })
        this.teamList = res.data
        this.GetAgreementInfoById()
      } catch (error) {
        console.log('🚀 ~ GetUnitData ~ error:', error)
      }
    },
    // 获取 工程名称 列表数据
    async GetProData() {
      const res = await getListProject({ unitId: null, isApp: true })
      this.proList = res.data
      // this.queryParams.proId = null
      // this.GetAgreementInfoById()
    },
    // 获取 设备树结构数据
    async GetDeviceTypeTreeFn(agreementIds) {
      const params = {
        agreementIds: agreementIds
      }
      const res = await getDeviceTreeByAgreementId(params)
      console.log('resgetUseTypeTreee==========', res)
      this.deviceTypeTree = res.data

      // 处理并扁平化所有类型数据
      this.flattenTypeOptions = this.processTypeData(res.data)
      console.log('🚀 ~ GetDeviceTypeTreeFn ~ this.flattenTypeOptions:', this.flattenTypeOptions)
      // 初始显示所有选项
      this.filteredOptions = [...this.flattenTypeOptions]

      //反显
      let selectList = []
      this.equipmentList.forEach(e => {
        selectList.push(this.getParentsById(this.deviceTypeTree, e.typeId))
      })
      this.deviceType = selectList
      this.$forceUpdate()
    },
    // 处理类型数据
    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(),
            num: node.num || 0,
            maTypeName: parents[parents.length - 1] || '',
            specificationType: node.typeName,
            unitName: node.unitName,
            unitValue: node.unitValue,
            manageType: node.manageType
          })
        }

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

      data.forEach(node => traverse(node))
      return result
    },
    // 搜索处理函数
    handleSearchImpl(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) {
      if (!val || val.length === 0) return

      // 获取新选中的项
      const lastSelected = val[val.length - 1]
      const typeData = this.flattenTypeOptions.find(item => item.typeId === lastSelected)

      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 if (typeData.num <= 0) {
          this.$message.error('所选物资规格类型暂时无出库，无法申请！')
          this.tempDeviceType = this.tempDeviceType.filter(id => id !== lastSelected)
        } else {
          console.log(typeData)
          // 将新项添加到数组开头，实现倒序
          this.equipmentList.unshift({
            ...typeData,
            preNum: 0,
            // typeModel: typeData.typeName,
            // typeName: typeData.specificationType,
            apDetection: '',
            remark: '',
            maCodeList: [],
            bmFileInfos: []
          })
          this.deviceType.push(lastSelected)
          this.$message({
            message: `已添加 ${typeData.typeName}`,
            type: 'success'
          })
        }
        console.log('🚀 ~ handleTypeChange ~ this.equipmentList:', this.equipmentList)
      }

      // 清空临时选中值
      this.$nextTick(() => {
        this.tempDeviceType = []
      })
    },
    //树结构数据获取父
    getParentsById(list, id) {
      for (let i in list) {
        if (list[i].typeId == id) {
          //查询到就返回该数组对象的value
          return [list[i].typeId]
        }
        if (list[i].children) {
          let node = this.getParentsById(list[i].children, id)
          if (node !== undefined) {
            //查询到把父节把父节点加到数组前面
            node.unshift(list[i].typeId)
            return node
          }
        }
      }
    },
    // 获取 协议id
    async GetAgreementInfoById() {
      if (this.queryParams.teamId && this.queryParams.proId) {
        const params = {
          teamId: this.queryParams.teamId,
          projectId: this.queryParams.proId
        }
        const res = await getAgreementInfoByIdBackApi(params)
        console.log(res)
        if (!(res.data && res.data.length > 0)) {
          // this.$message.error('当前单位和工程无协议！')
          this.queryParams.teamId = null
          this.queryParams.proId = null
          this.equipmentList = []
          this.GetUnitData()
          this.GetProData()
        } else {
          this.queryParams.agreementIds = res.data.map(item => item.agreementId)
          // this.queryParams.agreementCode = res.data.agreementCode
          this.equipmentList = []
          this.GetDeviceTypeTreeFn(this.queryParams.agreementIds)
        }
      }
    },

    // 获取 任务详情数据
    async GetViewByApply(params) {
      const res = await getBackApplyInfo(this.rowId)
      console.log('🚀 ~ GetViewByApply ~ res:', res)
      if (res.msg && res.msg != '操作成功') {
        this.$message.warning(res.msg)
      }
      const data = res.data
      console.log('🚀 ~ GetViewByApply ~ data:', data)
      this.queryParams = data.backApplyInfo
      this.equipmentList = data.backApplyDetailsList
      this.equipmentList.forEach(item => {
        item.tempMaCodeList = item.maCodeList || item.maCodeVoList || []
        item.maTypeName = item.materialName
      })
      this.GetDeviceTypeTreeFn(data.backApplyInfo.agreementIds)
    },
    //是否可用勾选框
    selectable(row) {
      console.log(row)
      if (row.preNum != 0) {
        return true
      } else {
        return false
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.queryParams.equipmentList = selection
    },

    /** 保存按钮操作 */
    handleAdd(isBack) {
      this.$refs.queryForm.validate(async valid => {
        if (!valid) {
          return false
        } else {
          // let backApplyInfo = []
          if (!this.equipmentList || this.equipmentList.length == 0) {
            this.$message.error('请先添加数据')
            return
          }
          if (!this.queryParams.equipmentList || this.queryParams.equipmentList.length == 0) {
            this.$message.error('请先勾选数据')
            return
          }
          const isNum = this.queryParams.equipmentList.some(item => item.preNum == '' || item.preNum == undefined)
          if (isNum) {
            this.$message.error('退料数量不能为空！')
            return
          }
          // 弹框二次确认
          this.$confirm(`是否确认${isBack == 1 ? '退料' : '暂存'}`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            const loading = this.$loading()
            try {
              this.queryParams.backApplyInfo = {
                id: this.rowId,
                backPerson: this.queryParams.backPerson,
                phone: this.queryParams.phone,
                remark: this.queryParams.remark,
                agreementIds: this.queryParams.agreementIds,
                isBack,
                taskId: this.queryParams.taskId,
                createBy: sessionStorage.getItem('userName')
              }
              if (this.rowId != '') {
                let params = {
                  backApplyInfo: this.queryParams.backApplyInfo,
                  backApplyDetailsList: this.queryParams.equipmentList
                }
                if (params.backApplyInfo.signUrl) delete params.backApplyInfo.signUrl
                const res = await editBackApply(params)
                if (res.code == 200) {
                  this.$message({ type: 'success', message: res.msg })
                  setTimeout(() => {
                    // this.$emit('goBackPage')
                    // 刷新页面
                    this.$tab.refreshPage({ path: '/materialsStation/toolsBack/back' })
                  }, 500)
                }
              } else {
                let params = {
                  backApplyInfo: this.queryParams.backApplyInfo,
                  backApplyDetailsList: this.queryParams.equipmentList
                }
                const res = await addBackApply(params)
                if (res.code == 200) {
                  this.$message({ type: 'success', message: res.msg })
                  setTimeout(() => {
                    // this.$emit('goBackPage')
                    this.$tab.refreshPage({ path: '/materialsStation/toolsBack/back' })
                  }, 500)
                }
              }
            } catch (error) {
              console.log('🚀 ~ handleAdd ~ error:', error)
            } finally {
              loading.close()
            }
          })
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row, index) {
      this.$modal
        .confirm('是否确认删除所选择的数据项？')
        .then(() => {
          this.equipmentList = this.equipmentList.filter(item => item.typeId !== row.typeId)
          // 更新实际存储的选中值
          this.deviceType = this.equipmentList.map(item => item.typeId)
        })
        .catch(() => {})
      // this.equipmentList.splice(row.index, 1)
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/role/export',
        {
          ...this.queryParams
        },
        `role_${new Date().getTime()}.xlsx`
      )
    },
    checkNum(row) {
      console.log(row)
      let maxNum = row.num
      if (row.unitValue == 1) {
        row.preNum = Number(String(row.preNum).replace(/[^\d.]/g, ''))
      } else {
        row.preNum = Number(String(row.preNum).replace(/[^\d]/g, ''))
      }
      if (row.preNum <= 0) {
        row.preNum = 0
      }
      if (row.preNum > maxNum) {
        row.preNum = maxNum
      }
    },
    //编码数据
    async getMachineById(typeId) {
      let param = {
        teamId: this.queryParams.teamId,
        proId: this.queryParams.proId,
        typeId: typeId
      }
      await getMachineById(param).then(res => {
        console.log('🚀 ~ awaitgetMachineById ~ res.data:', res.data)
        this.machineList = res.data
        this.machineList.forEach(item => {
          item.bmFileInfos = []
          item.apDetection = ''
        })
      })
    },
    //编码类型-弹窗
    async openAddCode(row) {
      this.rowData = row
      await this.getMachineById(row.typeId)
      // this.maId=""
      if (this.rowData.maCodeList && this.rowData.maCodeList.length > 0) {
        console.log(this.maCodeList)
        console.log(this.machineList)
        if (this.rowId != '') {
          this.maCodeList = this.rowData.maCodeList
          console.log('🚀 ~ 编辑 ~ this.maCodeList:', this.maCodeList)
          this.machineList.forEach(item => {
            this.maCodeList.forEach(sub => {
              if (sub.maId == item.maId) {
                this.$nextTick(() => {
                  setTimeout(() => {
                    this.$refs.codeTableList.toggleRowSelection(item, true)
                    item.apDetection = sub.apDetection
                  }, 200)
                })
              }
            })
          })
        } else {
          //新增回显勾选
          // console.log("新增")
          console.log(this.maCodeList, '新增')
          this.machineList.forEach(item => {
            this.maCodeList.forEach(sub => {
              if (sub.maId == item.maId) {
                this.$nextTick(() => {
                  this.$refs.codeTableList.toggleRowSelection(item, true)
                  item.apDetection = sub.apDetection
                })
              }
            })
          })
        }
      } else {
        this.maCodeList = []
      }
      this.open = true
    },
    codeSelectionChange(selection) {
      if (!this.open) return
      this.maCodeList = selection
    },
    // 弹窗保存
    saveDevCode() {
      console.log(this.rowData)
      console.log(this.maCodeList)
      this.rowData.maCodeList = this.maCodeList
      this.rowData.preNum = this.maCodeList.length
      // this.rowData.goodNum = this.maCodeList 中 apDetection 为 1 的数量
      this.rowData.goodNum = this.maCodeList.filter(item => item.apDetection === '1').length
      this.rowData.badNum = this.maCodeList.filter(item => item.apDetection === '0').length
      this.open = false
      console.log(this.equipmentList)
    },
    // 高亮文本
    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' })
      }
    },

    // 上一个匹配项
    handlePrevMatch() {
      if (this.matchedOptions.length === 0) return

      this.currentMatchIndex = this.currentMatchIndex <= 0 ? this.matchedOptions.length - 1 : this.currentMatchIndex - 1

      this.scrollToMatch()
    },

    // 下一个匹配项
    handleNextMatch() {
      if (this.matchedOptions.length === 0) return

      this.currentMatchIndex = this.currentMatchIndex >= this.matchedOptions.length - 1 ? 0 : this.currentMatchIndex + 1

      this.scrollToMatch()
    }
  },
  // 添加组件销毁时的清理
  beforeDestroy() {
    this.keepSelectOpen = false
    this.isSearching = false
  }
}
</script>
<style lang="scss">
.form-select {
  .el-cascader-panel .el-scrollbar .el-checkbox {
    display: none;
  }
  .el-cascader-panel .el-scrollbar:nth-child(3) .el-checkbox {
    display: block !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;
}
</style>
