<template>
  <!-- 新增工机具 -->
  <div>
    <el-form :model="maForm" ref="maForm" size="small" :rules="rules" :inline="true" label-width="120px">
      <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 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.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>
      <div>
        <el-form-item label="附件" prop="bmFileInfos">
          <el-upload
            :action="uploadUrl"
            :file-list="maForm.bmFileInfos"
            :headers="upload.headers"
            :show-file-list="true"
            :auto-upload="true"
            :key="uploadKey"
            :limit="5"
            list-type="picture-card"
            accept=".png, .jpg, .jpeg, .pdf"
            :on-change="handleChangeBusinessList"
            :class="{ disabledFbs: uploadDisabled }"
            :on-preview="picturePreviewFbs"
            :on-remove="handleRemoveElectricianImgList"
            :on-success="handleUploadSuccess"
          >
            <!-- 文件格式下载，图片格式预览 -->
            <div slot="file" slot-scope="{ file }">
              <img v-if="isImage(file)" class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <div v-else class="picture-card-container">
                <img class="picture-card" :src="urlTemp" alt="" />
                <p class="file-name">{{ file.name }}</p>
              </div>
              <span class="el-upload-list__item-actions">
                <span v-if="updataIf(file)" class="el-upload-list__item-delete" @click="handleDownload(file)">
                  <i class="el-icon-download" />
                </span>
                <span v-else class="el-upload-list__item-preview" @click="picturePreviewFbs(file)">
                  <i class="el-icon-zoom-in" />
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemoveElectricianImgList(file)">
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleSave">保存</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-if="isEdit">导出</el-button>
            </el-col> -->
    </el-row>

    <el-table v-loading="loading" :data="equipmentList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <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 label="报废数量" prop="scrapNum" align="center">
        <template v-slot="scope">
          <template v-if="scope.row.manageType === '1'">
            <el-input
              v-model.number="scope.row.scrapNum"
              controls-position="right"
              type="number"
              style="width: 100%"
              :min="0"
              @input="v => (scope.row.scrapNum = Number(v.replace(/[^\d.]/g, '')))"
            ></el-input>
          </template>
          <template v-else>
            <span>{{ scope.row.scrapNum }}</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="设备编号" align="center" prop="maCodeList" width="200px">
        <template v-slot="scope">
          <template v-if="scope.row.manageType === '0'">
            <el-select
              v-model="scope.row.maCodeList"
              placeholder="请选择设备编号"
              multiple
              collapse-tags
              filterable
              @change="handleDeviceCodeChange(scope.row)"
              style="width: 180px"
            >
              <el-option
                v-for="item in scope.row.deviceCodeOptions"
                :key="item.id"
                :label="item.code"
                :value="item.id"
              ></el-option>
            </el-select>
          </template>
          <template v-else-if="scope.row.manageType === '1'">
            <span>计数</span>
          </template>
          <template v-else>
            <span>{{ scope.row.maCodeList }}</span>
          </template>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="出库数量" prop="alNum" /> -->
      <el-table-column label="报废原因" prop="scrapReason" align="center" label-width="500px">
        <template v-slot="scope">
          <el-input v-model="scope.row.scrapReason" 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>

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

<script>
import { getPurchaseCheckInfo, equipmentTypeTree } from '@/api/purchase/goodsArrived'

import { getToken } from '@/utils/auth'
import { uploadPurchaseFile, getPurchaseFileList } from '@/api/purchase/goodsAccept'
import { downloadFile, downloadFileData } from '@/utils/download'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getMachineListByCode, addScrapInfo, getScrapInfo, editScrapInfo } from '@/api/repair/scrapLedgerReview'

export default {
  name: 'AddTools',
  dicts: ['purchase_task_status'],
  components: { Treeselect },
  props: {
    isEdit: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    editTaskId: {
      type: [String, Number],
      default: () => {
        return ''
      }
    },
    editId: {
      type: [String, Number],
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      taskId: '',
      // isEdit: false,
      // 遮罩层
      loading: false,
      loadingTwo: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //机具类型
      equipmentTypeList: [],
      // 角色表格数据
      equipmentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      rowData: {},
      unitId: null,
      projectId: null,
      // 查询参数
      queryParams: {
        equipmentId: undefined,
        productionTime: ''
      },
      maForm: {
        unitId: undefined,
        projectId: undefined,
        arrivalTime: '',
        purchaser: '',
        remark: '',
        purchaseNumber: '',
        bmFileInfos: []
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        bmFileInfos: [
          {
            required: true, //是否分包商(是：合同编号必填)
            message: '请上传附件',
            trigger: 'change'
          }
        ]
      },
      deviceTypeTreeProps: {
        children: 'children',
        label: 'typeName',
        value: 'typeId',
        multiple: true,
        emitPath: true
      },
      deviceType: [],
      propsKey: 1000,
      projectTemp: undefined,
      unitTemp: undefined,
      agreementId: undefined,
      // taxRate:0,
      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, // 添加搜索状态标记

      urlTemp: '',
      delBusinessFileIdList: [],
      //图片查看弹窗
      dialogImageUrl: '',
      dialogVisible: false,
      uploadKey: Date.now(),
      //上传
      // upload: {
      //   // 设置上传的请求头部
      //   headers: {Authorization: 'Bearer ' + getToken()},
      //   // 上传的地址
      //   url: process.env.VUE_APP_BASE_API + '/file/upload'
      // },
      uploadUrl: process.env.VUE_APP_BASE_API + '/file/upload', // 上传的图片服务器地址
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() }
      },
      equipmentListTemp: []
    }
  },
  computed: {
    //图片上传1张后，隐藏上传框
    uploadDisabled() {
      return this.maForm.bmFileInfos && this.maForm.bmFileInfos.length == 5
    },
    pickerOptions() {
      return {
        disabledDate(time) {
          const currentDate = new Date()
          currentDate.setHours(0, 0, 0, 0)
          return time.getTime() < currentDate.getTime()
        }
      }
    }
  },
  mounted() {
    this.equipmentType() //机具类型下拉选
    if (this.isEdit) {
      console.log('isEdit', this.isEdit)
      this.taskId = this.editTaskId
      this.id = this.editId
      this.getTaskInfo()
      this.equipmentType()
    }
  },
  methods: {
    handleDeviceCodeChange(row) {
      const newDeviceCount = row.maCodeList.length
      row.scrapNum = newDeviceCount
    },

    /** 机具类型 */
    equipmentType() {
      equipmentTypeTree().then(response => {
        this.equipmentTypeList = response.data
        console.log('this.equipmentTypeList', this.equipmentTypeList)
        // 处理并扁平化所有类型数据
        this.flattenTypeOptions = this.processTypeData(response.data)
        // 初始显示所有选项
        this.filteredOptions = [...this.flattenTypeOptions]

        // 反显选中数据
        if (this.equipmentList.length > 0) {
          this.deviceType = this.equipmentList.map(item => item.typeId)
        }
      })
    },
    // 处理类型数据
    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.storageNum || 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)
      console.log('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 if (typeData.storageNum <= 0) {
          this.$message.error('所选物资规格类型暂时无库存，无法申请！')
          this.tempDeviceType = this.tempDeviceType.filter(id => id !== lastSelected)
        } else {
          const newItem = {
            ...typeData,
            scrapNum: 0,
            isNew: true
          }

          // 将新项添加到数组开头，实现倒序
          this.equipmentList.unshift(newItem)

          this.deviceType.push(lastSelected)
          this.$message({
            message: `已添加 ${typeData.typeName}`,
            type: 'success'
          })
          // 调用 getDeviceCodeOptions 并赋值
          this.getDeviceCodeOptions(newItem).then(options => {
            this.$set(newItem, 'deviceCodeOptions', options)
          })

          console.log('this.equipmentList', this.equipmentList)
        }
      }

      // 清空临时选中值
      this.$nextTick(() => {
        this.tempDeviceType = []
      })
    },

    async getDeviceCodeOptions(row) {
      // 这里假设 handleTypeChange 中有相关数据，你需要根据实际情况调整
      // 例如，假设 this.equipmentList 中有相关数据
      console.log('xxxxxxxxxxxxxxxxx')
      const response = await getMachineListByCode({ typeId: row.typeId, taskId: this.taskId })
      console.log('response', response)
      const relatedData = response.data.map(item => ({ id: item.maId, code: item.maCode }))
      console.log('relatedData', relatedData)
      return relatedData
    },

    //获取任务详情--- 编辑回显数据
    async getTaskInfo() {
      // this.loading = true;
      await getScrapInfo({ taskId: this.taskId }).then(async response => {
        this.maForm.bmFileInfos = response.data.fileList

        this.equipmentList = response.data.scrapApplyDetailsList.map(item => {
          let newMaCodeList = []
          if (item.manageType == '0') {
            newMaCodeList = item.maCodeList.map(maCode => maCode.maId)
          }
          return {
            ...item,
            manageType: item.manageType,
            maCodeList: newMaCodeList,
            deviceCodeOptions: [] // 初始化设备编码选项
          }
        })

        // 为每个设备项获取设备编码选项
        for (let i = 0; i < this.equipmentList.length; i++) {
          if (this.equipmentList[i].manageType == '0') {
            const options = await this.getDeviceCodeOptions(this.equipmentList[i])
            console.log('options', options)
            this.$set(this.equipmentList[i], 'deviceCodeOptions', options)
          }
        }
        console.log('xxxxxxxxxx', this.equipmentList[0].maCodeList)
        // this.loading = false;
      })
      // await this.projectInfoList();
    },
    checkNum(row) {
      // let maxNum = row.storageNum
      // if (row.preNum <= 1) {
      //     row.preNum = 1
      // } else if (row.preNum > maxNum) {
      //     row.preNum = maxNum-1
      // }
    },

    getEquipmentListTemp() {
      return this.equipmentList
    },

    /** 保存按钮操作 */
    handleSave() {
      // console.log(this.equipmentList)
      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].scrapNum <= 0) {
                this.$message.error(`第 ${i + 1} 行的 ${'报废数量必须大于0'} `)
                return
              }
              if (this.equipmentList[i].scrapNum > this.equipmentList[i].storageNum) {
                this.$message.error(`第 ${i + 1} 行的 ${'报废数量不可大于库存量'} `)
                return
              }
            }

            // this.maForm.taskId = this.taskId;
            // this.maForm.checkDetailsList = this.equipmentList
            await this.$modal
              .confirm('是否确认保存当前页面')
              .then(function () {})
              .then(() => {
                if (this.isEdit) {
                  console.log('编辑')
                  this.loading = true
                  let dataList = []
                  this.equipmentList.forEach(item => {
                    if (item.manageType == 0) {
                      let maCodeList = []
                      item.maCodeList.forEach(param => {
                        maCodeList.push({ maId: param })
                      })
                      console.log('maCodeListxxxxxxxxxxxxxxx', maCodeList)
                      dataList.push({
                        typeId: item.typeId,
                        scrapNum: item.scrapNum,
                        storageNum: item.storageNum,
                        maCodeList: maCodeList,
                        scrapReason: item.scrapReason
                      })
                    } else {
                      dataList.push({
                        typeId: item.typeId,
                        scrapNum: item.scrapNum,
                        storageNum: item.storageNum,
                        scrapReason: item.scrapReason
                      })
                    }
                  })
                  let list = {
                    fileList: this.maForm.bmFileInfos,
                    scrapApplyDetailsList: dataList,
                    taskId: this.taskId
                  }
                  editScrapInfo(list).then(response => {
                    if (response.code == 200) {
                      this.$modal.msgSuccess('修改成功')
                      // this.$tab.closeOpenPage({
                      //     path: '/store/newBuy/newDevicesList',
                      // })

                      this.$emit('addToolsSuccess')
                    }
                    this.loading = false
                  })
                } else if (!this.isEdit) {
                  console.log('新增')
                  // console.log(this.equipmentList)
                  this.loading = true
                  let dataList = []
                  this.equipmentList.forEach(item => {
                    if (item.manageType == 0) {
                      let maCodeList = []
                      item.maCodeList.forEach(param => {
                        maCodeList.push({ maId: param })
                      })
                      console.log('maCodeListxxxxxxxxxxxxxxx', maCodeList)
                      dataList.push({
                        typeId: item.typeId,
                        scrapNum: item.scrapNum,
                        storageNum: item.storageNum,
                        maCodeList: maCodeList,
                        scrapReason: item.scrapReason
                      })
                    } else {
                      dataList.push({
                        typeId: item.typeId,
                        scrapNum: item.scrapNum,
                        storageNum: item.storageNum,
                        scrapReason: item.scrapReason
                      })
                    }
                  })
                  let list = {
                    fileList: this.maForm.bmFileInfos,
                    scrapApplyDetailsList: dataList
                  }
                  addScrapInfo(list).then(response => {
                    if (response.code == 200) {
                      this.$modal.msgSuccess('新增成功')
                      // this.$tab.closeOpenPage({
                      //     path: '/store/newBuy/newDevicesList',
                      // })

                      this.$emit('addToolsSuccess')
                    }
                    this.loading = false
                  })
                }
              })
              .catch(() => {})
          }
        })
      } else {
        this.$modal.msgError('请先添加类型规格')
      }
    },
    //文件管理
    openFileDialog(row) {
      this.rowData = row
      this.fileDataList = [
        { dictLabel: '合格证', fileType: '0', name: '', url: '' },
        { dictLabel: '型式试验报告', fileType: '1', name: '', url: '' },
        { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '' },
        { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '' },
        { dictLabel: '其他', fileType: '4', name: '', url: '' }
      ]
      if (this.taskId == '') {
        // console.log(this.rowData)
        // console.log(this.rowData.bmFileInfos)
        if (this.rowData.bmFileInfos.length > 0) {
          this.rowData.bmFileInfos.forEach(item => {
            let index = this.fileDataList.findIndex(v => v.fileType == item.fileType)
            this.fileDataList[index].name = item.name
            this.fileDataList[index].url = item.url
          })
        }
      } else {
        this.getFileData()
      }
      this.open = true
    },
    getFileData() {
      let param = {
        modelId: this.rowData.typeId,
        taskType: 0,
        taskId: this.rowData.taskId
      }
      getPurchaseFileList(param)
        .then(response => {
          if (response.rows.length > 0) {
            response.rows.forEach(item => {
              let index = this.fileDataList.findIndex(v => v.fileType == item.fileType)
              this.fileDataList[index].name = item.name
              this.fileDataList[index].url = item.url
            })
          }
        })
        .catch(() => {})
    },
    beforeFileUpload(row) {
      this.rowData.fileType = row.fileType
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code == 200) {
        if (this.taskId == '') {
          //新增逻辑
          // console.log(response)
          // console.log(this.rowData)
          // console.log(this.rowData.bmFileInfos)
          let obj = {
            taskId: this.taskId,
            taskType: '0',
            name: response.data.name,
            url: response.data.url,
            modelId: this.rowData.typeId,
            fileType: this.rowData.fileType
            //   "dictLabel": this.rowData.dictLabel,
          }
          //根据文件上传返回更新文件管理弹窗内容
          let index = this.fileDataList.findIndex(v => v.fileType == this.rowData.fileType)
          this.fileDataList[index].name = response.data.name
          this.fileDataList[index].url = response.data.url
          //判断当前上传的文件是否已上传过-再往机具类型数据中插入
          if (this.rowData.bmFileInfos.length > 0) {
            let index2 = this.rowData.bmFileInfos.findIndex(v => v.fileType == this.rowData.fileType)
            if (index2 > -1) {
              //相同类型文件重复上传-替换
              this.rowData.bmFileInfos.splice(index2, 0, obj)
            } else {
              //不存在相同类型文件-添加
              this.rowData.bmFileInfos.push(obj)
            }
          } else {
            this.rowData.bmFileInfos.push(obj)
          }
        } else {
          //编辑逻辑
          let param = {
            taskId: this.taskId,
            taskType: '0',
            name: response.data.name,
            url: response.data.url,
            modelId: this.rowData.typeId,
            fileType: this.rowData.fileType
            //   "dictLabel": this.rowData.dictLabel,
          }
          uploadPurchaseFile(param)
            .then(response => {
              this.$modal.msgSuccess('上传成功')
              this.getFileData()
            })
            .catch(() => {
              this.$modal.msgError('上传失败')
            })
        }
      }
    },

    //图片查看
    picturePreview(file) {
      this.dialogImageUrl = file.url
      const parts = file.name.split('.')
      const extension = parts.pop()
      if (
        extension === 'doc' ||
        extension === 'DOC' ||
        extension === 'docx' ||
        extension === 'DOCX' ||
        extension === 'pdf' ||
        extension === 'PDF'
      ) {
        const windowName = file.name
        window.open(file.url, windowName)
      } else {
        this.dialogVisible = true
      }
    },
    /** 删除按钮操作 */
    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(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      this.download(
        '/material/purchase_check_info/exportDetails',
        { taskId: this.taskId },
        `新购到货详情_${currentTime}.xlsx`
      )
    },

    //委托书文件
    handleChangeBusinessList(file, fileList) {
      const fileListTemp = fileList.filter(item => {
        return item.uid != file.uid
      })
      const parts = file.name.split('.')
      const extension = parts.pop()
      if (fileList.length > 5) {
        this.$message.warning('最多上传5张附件')
        fileList = fileList.filter(item => {
          return item.uid != file.uid
        })
      } else if (!(extension === 'pdf' || extension === 'png' || extension === 'jpg' || extension === 'jpeg')) {
        this.$message.warning('文件格式不正确')
        fileList = fileList.filter(item => {
          return item.uid != file.uid
        })
      } else if (file.size > 1024 * 1024 * 10) {
        this.$message.warning('文件大小不能超过10Mb')
        fileList = fileList.filter(item => {
          return item.uid != file.uid
        })
      } else if (file.name.length > 40) {
        this.$message.warning('文件名长度不能超过40个字符')
        fileList = fileList.filter(item => {
          return item.uid != file.uid
        })
      } else if (fileListTemp.some(item => item.name === file.name)) {
        this.$message.warning('文件名重复')
        fileList = fileList.filter(item => {
          return item.uid != file.uid
        })
      }
      fileList.forEach(file => {
        if (extension === 'pdf') {
          this.urlTemp = require('../../../../../assets/file.png')
        }
      })
      // this.maForm.bmFileInfos = fileList
      // console.log('🚀 ~ handleChangeBusinessList ~ this.bmFileInfos:', this.bmFileInfos)
      // 手动触发表单验证
      this.$refs.maForm.validateField('bmFileInfos')
      // // 根据 bmFileInfos 是否有值来控制 bmFileInfos 的验证
      // if (this.bmFileInfos.length > 0) {
      //   // this.maForm.bmFileInfos = fileList.map(item => item.raw); // 假设需要上传文件对象;
      //   // 有值，手动标记验证通过
      //   console.log('222222222222222')
      //   this.$refs.maForm.clearValidate('bmFileInfos');
      // } else {
      //   // maForm.bmFileInfos = false;
      //   console.log('33333333')
      //   // 无值，手动触发验证失败
      //   this.$refs.maForm.validateField('bmFileInfos');
      // }

      console.log('4444444444')
    },
    handleUploadSuccess(res, file, fileList) {
      if (res.code === 200) {
        this.maForm.bmFileInfos.push({...res.data, fileName: res.data.name, fileUrl: res.data.url})
      }
      console.log('🚀 ~ handleUploadSuccess ~ this.maForm.bmFileInfos:', this.maForm.bmFileInfos)
    },

    isImage(file) {
      this.urlTemp = require('@/assets/file.png')
      if (this.updataIf(file)) {
        return false
      } else {
        return true
      }
    },

    // 判断文件类型,图片预览，文件下载
    updataIf(e) {
      if (e.fileName) {
        const parts = e.fileName.split('.')
        const extension = parts.pop()
        if (extension === 'png' || extension === 'jpeg' || extension === 'jpg') {
          return false
        } else {
          return true
        }
      } else {
        const parts = e.name.split('.')
        const extension = parts.pop()
        if (extension === 'png' || extension === 'jpeg' || extension === 'jpg') {
          return false
        } else {
          return true
        }
      }
    },

    //上传组件-图片查看
    picturePreviewFbs(file) {
      this.dialogImageUrl = file.url.replaceAll('#', '%23')
      const parts = file.name.split('.')
      const extension = parts.pop()
      if (extension === 'pdf') {
        const windowName = file.name
        window.open(file.url, windowName)
      } else {
        this.dialogVisible = true
      }
    },

    //上传组件-图片删除
    handleRemoveElectricianImgList(file, fileList) {
      let sum = 0
      this.maForm.bmFileInfos.forEach((item, index) => {
        if (item.uid == file.uid) {
          sum = index
        }
      })
      this.maForm.bmFileInfos.splice(sum, 1)
      if (file.status == 'success') {
        this.delBusinessFileIdList.push(file.url)
      }
      console.log('delBusinessFileIdList', this.delBusinessFileIdList)
    },

    handleDownload(file) {
      console.log(file)
      if (file.status === 'ready') {
        downloadFile({ fileName: file.name, fileData: file.raw, fileType: 'application/vnd.ms-excel;charset=utf-8' })
      } else if (file.status === 'success') {
        downloadFileData({ fileName: file.name, fileUrl: file.url })
        // downloadFileData({ fileName: file.name,fileUrl:file.url })
      }
    },

    // 高亮文本
    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>
