<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="unitId">
                    <treeselect
                        v-model="queryParams.unitId"
                        :disabled="backId != ''"
                        :options="unitList"
                        :normalizer="normalizer"
                        :show-count="true"
                        style="width: 240px"
                        :disable-branch-nodes="true"
                        noChildrenText="没有数据了"
                        noOptionsText="没有数据"
                        noResultsText="没有搜索结果"
                        placeholder="请选择退料单位"
                        @select="unitChange"
                    />
                    <!-- <el-cascader v-model="unitId"
                        :show-all-levels="false"
                        :options="unitList"
                        :props="selectTreeProps"
                        filterable
                        clearable
                        collapse-tags
                        @change="unitChange"
                        placeholder="请选择退料单位"
                    ></el-cascader> -->
                </el-form-item>
                <el-form-item label="退料工程" prop="proId">
                    <treeselect
                        v-model="queryParams.proId"
                        :disabled="backId != ''"
                        :options="proList"
                        :normalizer="normalizer"
                        :show-count="true"
                        style="width: 240px"
                        :disable-branch-nodes="true"
                        noChildrenText="没有数据了"
                        noOptionsText="没有数据"
                        noResultsText="没有搜索结果"
                        placeholder="请选择退料工程"
                        @select="proChange"
                    />
                    <!-- <el-cascader v-model="projectId"
                        :show-all-levels="false"
                        :options="proList"
                        :props="selectTreeProps"
                        filterable clearable
                        collapse-tags
                        @change="proChange"
                        placeholder="请选择退料工程"
                    ></el-cascader>   -->
                </el-form-item>
                <!-- <el-form-item label="协议号" prop="agreementCode">
                    <el-input
                        v-model="queryParams.agreementCode"
                        disabled
                        style="width: 240px"
                    ></el-input>
                </el-form-item> -->
                <el-form-item label="退料人" prop="backPerson">
                    <el-input
                        v-model="queryParams.backPerson"
                        placeholder="请输入退料人"
                        clearable
                        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-cascader
                        :key="propsKey"
                        v-model="deviceType"
                        :show-all-levels="false"
                        :options="deviceTypeTree"
                        :props="deviceTypeTreeProps"
                        filterable
                        collapse-tags
                        style="width: 240px"
                        placeholder="请选择规格型号"
                        ref="deviceTypeCascader"
                        popper-class="popper-select"
                        @change="deviceTypeChange"
                    ></el-cascader> -->
                <!-- </el-form-item> -->
                <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="success"
                    plain
                    icon="el-icon-back"
                    size="mini"
                    @click="handleBack"
                    >退料管理</el-button
                >
            </el-col> -->
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">保存</el-button>
            </el-col>

            <el-col :span="1.5">
                <!-- <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:role:export']"
          >导出</el-button> -->
            </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="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="typeModel" :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">
                    <div
                        style="color: rgb(2, 167, 240)"
                        @click="openAddCode(scope.row)"
                        v-if="scope.row.manageType == 0"
                    >
                        {{ scope.row.maCodeList && scope.row.maCodeList.length > 0 ? scope.row.maCodeList.length : '添加编码' }}
                    </div>
                    <el-input
                        v-if="scope.row.manageType == 1"
                        v-model.number="scope.row.preNum"
                        placeholder="退料数量"
                        type="number"
                        min="1"
                        clearable
                        @input="checkNum(scope.row)"
                        style="width: 100%"
                    />
                </template>
            </el-table-column>
            <el-table-column label="完好数量" align="center" prop="goodNum" min-width="100">
                <template slot-scope="scope">
                    <el-input
                        v-model.number="scope.row.goodNum"
                        placeholder="退料数量"
                        clearable
                        style="width: 100%"
                        @input="changeNum(scope.row)"
                        :disabled="scope.row.manageType == 0"
                    />
                </template>
            </el-table-column>
            <el-table-column label="损坏数量" align="center" prop="badNum" min-width="100">
                <template slot-scope="scope">
                    <el-input
                        v-model.number="scope.row.badNum"
                        placeholder="退料数量"
                        clearable
                        style="width: 100%"
                        @input="changeNum(scope.row)"
                        :disabled="scope.row.manageType == 0"
                    />
                </template>
            </el-table-column>
            <!-- <el-table-column label="外观判定11" 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" prop="file">
                <template slot-scope="scope">
                    <div style="display: flex; align-items: center; justify-content: center">
                        <el-upload
                            ref="upload"
                            :limit="3"
                            :headers="upload.headers"
                            :action="upload.url"
                            :show-file-list="false"
                            accept=".png, .jpg, .jpeg, .pdf, .doc, .docx"
                            :on-success="handleFileSuccess"
                            :auto-upload="true"
                        >
                            <el-button size="mini" type="text" @click="beforeFileUpload(scope.row)">上传</el-button>
                        </el-upload>
                        <el-button
                            size="mini"
                            type="text"
                            @click="picturePreview(scope.row)"
                            v-if="scope.row.bmFileInfos && scope.row.bmFileInfos.length > 0"
                            fileName
                        >
                            查看
                        </el-button>
                    </div>
                </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-row :gutter="10" class="mb8">
                <el-col :span="6">
                    <div style="width: 100%;height: 100%;display: flex;align-items: center;">
                        <span style="width: 80px;">编码：</span>
                        <el-select v-model="maId" clearable filterable style="width: 240px" placeholder="请选择" @change="changeMachine">
                            <el-option v-for="item in machineList"
                                :key="item.maId"
                                :label="item.maCode"
                                :value="item.maId">
                        </el-option>
                    </el-select>
                    </div>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="primary" size="mini" @click="handleAddCode">添加编码</el-button>
                </el-col>
            </el-row> -->
            <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="typeName"
                    align="center"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="规格型号"
                    prop="materialName"
                    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="maStatus" 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%"
                        /> -->
                        <el-radio-group v-model="scope.row.apDetection">
                            <el-radio label="1">完好</el-radio>
                            <el-radio label="0">损坏</el-radio>
                        </el-radio-group>
                    </template>
                </el-table-column>
                <el-table-column label="附件" align="center" width="120" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <div style="display: flex; align-items: center; justify-content: space-between">
                            <el-upload
                                ref="upload"
                                :limit="3"
                                :headers="upload.headers"
                                :action="upload.url"
                                :show-file-list="false"
                                accept=".png, .jpg, .jpeg, .pdf, .doc, .docx"
                                :on-success="handleFileSuccess2"
                                :auto-upload="true"
                            >
                                <el-button size="mini" type="text" @click="beforeFileUpload(scope.row)">上传</el-button>
                            </el-upload>
                            <el-button
                                size="mini"
                                type="text"
                                @click="picturePreview(scope.row)"
                                v-if="scope.row.bmFileInfos && scope.row.bmFileInfos.length > 0"
                            >
                                查看
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column
                    label="文件名称"
                    prop="fileName"
                    align="center"
                    :show-overflow-tooltip="true"
                ></el-table-column> -->
                <!-- <el-table-column label="操作" align="center"   width="120px">
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger"
                            @click="handleDeleteCode({ ...scope.row, index: scope.$index })">删除</el-button>
                    </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 {
    getProjectList,
    getUnitList,
    getAgreementInfoById,
    getDeviceTreeByAgreementId,
    addBackApply,
    getBackApplyInfo,
    editBackApply,
    getMachineById
} from '@/api/back/index.js'
import { mapState } from 'vuex'
import { getInfo, h } from '@/api/login'
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: [], //单位 集合
            proList: [], // 工程 集合
            unitId: null,
            lastUnitId: null,
            projectId: null,
            lastProjectId: null,
            // 查询参数
            queryParams: {
                unitId: null,
                proId: null,
                agreementId: null, //协议id
                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: {
                unitId: [
                    {
                        required: true,
                        message: '请选择退料单位',
                        trigger: 'change'
                    }
                ],
                proId: [
                    {
                        required: true,
                        message: '请选择退料工程',
                        trigger: 'change'
                    }
                ],
                backPerson: [
                    {
                        required: true,
                        message: '请输入退料人',
                        trigger: 'blur'
                    },
                  {
                    validator: (rule, value, callback) => {
                      // 判断是否包含至少两个汉字
                      const regex = /[\u4e00-\u9fa5].*[\u4e00-\u9fa5]/;
                      if (!regex.test(value)) {
                        callback(new Error('退料人必须包含至少两个汉字'));
                      } else {
                        callback();
                      }
                    },
                    trigger: 'blur'
                  }
                ],
                // backTime: [
                //     {
                //         required: true,
                //         message: '请选择退料时间',
                //         trigger: 'change',
                //     },
                // ],
                phone: [
                    // {
                    //     required: true,
                    //     trigger: 'blur',
                    //     message: '请输入退料人的手机号'
                    // },
                    {
                        pattern: /^1[3456789]\d{9}$/,
                        message: '请输入正确的手机号码',
                        trigger: 'blur'
                    }
                ]
            },

            deviceTypeTree: [], // 设备 树结构数据
            // 设备 树显示 配置
            deviceTypeTreeProps: {
                children: 'children',
                label: 'typeName',
                // multiple: false,
                value: 'typeId',
                multiple: true
            },
            // 选中的设备类型
            deviceType: [],
            // defaultProps: {
            //   children: "children",
            //   label: "label"
            // },
            // companyId: '',
            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()
        }
        // getInfo().then((res) => {
        //     this.companyId = res.user.companyId
        //     this.createBy = res.user.userName
        // })
    },
    computed: {
        ...mapState(['user'])
    },
    methods: {
        changeNum(row) {
            console.log('🚀 ~ changeNum ~ row:', row)
            // 将badNum 和 goodNum 向上取整
            // 只能输入正整数 过滤掉除正整数外的东西
            if (row.badNum) {
                row.badNum = Math.ceil(String(row.badNum).replace(/[^\d]/g, ''))
            }
            if (row.goodNum) {
                row.goodNum = Math.ceil(String(row.goodNum).replace(/[^\d]/g, ''))
            }
            // 不能大于preNum
            if (row.badNum + row.goodNum > row.preNum) {
                console.log(
                    '🚀 ~ changeNum ~ row.badNum + row.goodNum > row.preNum:',
                    row.badNum + row.goodNum > row.preNum
                )
                this.$message.error('完好数量和损坏数量之和不能大于退料数量')
                row.badNum = 0
                row.goodNum = 0
            }
        },
        /** 转换菜单数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children
            }
            return {
                id: node.id,
                label: node.name,
                children: node.children
            }
        },
        // 获取 来往单位 列表数据
        async GetUnitData() {
            const params = {
                // projectId: this.queryParams.proId /*  */,
            }
            const res = await getUnitList(params)
            this.unitList = res.data
            this.GetAgreementInfoById()
        },
        unitChange(val) {
            // if(val&&val.length>0){
            //     this.queryParams.unitId=this.unitId[this.unitId.length - 1]
            // }else if(val&&val.length==0){
            //     this.queryParams.unitId=""
            // }
            // this.GetProData()
            setTimeout(() => {
                this.GetProData()
            }, 500)
        },
        // 获取 工程名称 列表数据
        async GetProData() {
            const params = {
                unitId: this.queryParams.unitId
            }
            const res = await getProjectList(params)
            this.proList = res.data
            this.queryParams.proId = null
            this.GetAgreementInfoById()
        },
        proChange(val) {
            // if(val&&val.length>0){
            //     this.queryParams.proId=this.projectId[this.projectId.length - 1]
            // }else if(val&&val.length==0){
            //     this.queryParams.proId=""
            // }
            // this.GetUnitData()
            setTimeout(() => {
                this.GetUnitData()
            }, 500)
        },
        // 获取 设备树结构数据
        async GetDeviceTypeTreeFn(agreementId) {
            const params = {
                unitId: this.queryParams.unitId,
                proId: this.queryParams.proId,
                agreementId: agreementId
            }
            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] || '',
                        unitName: node.unitName,
                        unitValue: node.unitValue,
                        manageType: node.manageType,
                        isAlert: node.isAlert,
                    })
                }

                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('xxxxxxxxxxxxxxxxxx',typeData)
                    if(typeData.isAlert){
                        this.$message({
                            message: '当前工器具仍有班组在用，请核实退料单位',
                            type: 'warning'
                        })
                      
                    }
                    // 将新项添加到数组开头，实现倒序
                    this.equipmentList.unshift({
                        ...typeData,
                        preNum: 0,
                        typeModel: typeData.typeName,
                        typeName: typeData.maTypeName,
                        apDetection: '',
                        remark: '',
                        maCodeList: [],
                        bmFileInfos: []
                    })
                    this.deviceType.push(lastSelected)
                    if(!typeData.isAlert){
                        this.$message({
                            message: `已添加 ${typeData.typeName}`,
                            type: 'success'
                        })
                    }
                }
            }

            // 清空临时选中值
            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.unitId && this.queryParams.proId) {
                const params = {
                    unitId: this.queryParams.unitId,
                    projectId: this.queryParams.proId
                }
                const res = await getAgreementInfoById(params)
                console.log(res)
                if (!(res.data && res.data.agreementId)) {
                    this.$message.error('当前单位和工程无协议！')
                    this.queryParams.unitId = null
                    this.queryParams.proId = null
                    this.equipmentList = []
                    this.GetUnitData()
                    this.GetProData()
                } else {
                    this.queryParams.agreementId = res.data.agreementId
                    this.queryParams.agreementCode = res.data.agreementCode
                    this.equipmentList = []
                    this.GetDeviceTypeTreeFn(res.data.agreementId)
                }
            }
        },

        // 获取 任务详情数据
        async GetViewByApply(params) {
            const res = await getBackApplyInfo(this.rowId)
            if (res.msg && res.msg != '操作成功') {
                this.$message.warning(res.msg)
            }
            console.log(res)
            const data = res.data
            this.queryParams.unitId = data.backApplyInfo.unitId
            // this.unitId = this.treeParentsById(this.unitList, this.queryParams.unitId)
            await this.GetProData()
            setTimeout(() => {
                this.queryParams.proId = data.backApplyInfo.proId
            }, 500)
            // this.projectId = this.treeParentsById(this.proList, this.queryParams.proId)
            this.queryParams.phone = data.backApplyInfo.phone
            this.queryParams.backPerson = data.backApplyInfo.backPerson
            this.queryParams.agreementId = data.backApplyInfo.agreementId
            this.queryParams.remark = data.backApplyInfo.remark
            this.equipmentList = data.backApplyDetailsList || []
            // this.equipmentList.forEach(item => {
            //     // item.tempMaCodeList = item.maCodeList
            //     const list = Array.isArray(item.maCodeList) ? item.maCodeList : []
            //     item.goodNum = list.filter(code => code.apDetection === '1' || code.apDetection === '完好').length
            //     item.badNum  = list.filter(code => code.apDetection === '0' || code.apDetection === '不合格').length
            // })
            this.GetDeviceTypeTreeFn(data.backApplyInfo.agreementId)
        },
        //单位，工程树结构数据获取父
        treeParentsById(list, id) {
            for (let i in list) {
                if (list[i].id == id) {
                    //查询到就返回该数组对象的value
                    return [list[i].id]
                }
                if (list[i].children) {
                    let node = this.treeParentsById(list[i].children, id)
                    if (node !== undefined) {
                        //查询到把父节把父节点加到数组前面
                        node.unshift(list[i].id)
                        return node
                    }
                }
            }
        },
        //是否可用勾选框
        selectable(row) {
            console.log(row)
            if (row.preNum != 0) {
                return true
            } else {
                return false
            }
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.queryParams.equipmentList = selection
        },

        /** 保存按钮操作 */
        handleAdd() {
            this.$refs.queryForm.validate(async valid => {
                if (!valid) {
                    return false
                } else {
                    // let backApplyInfo = []
                    if (this.equipmentList.length == 0) {
                        this.$message.error('请先添加数据')
                        return
                    }
                    if (this.queryParams.equipmentList.length == 0) {
                        this.$message.error('请先勾选数据')
                        return
                    }
                    // const isRemark = this.queryParams.equipmentList.some(
                    //   (item) => item.remark == '' || item.remark == undefined
                    // );
                    const isNum = this.queryParams.equipmentList.some(
                        item => item.preNum == '' || item.preNum == undefined
                    )
                    if (isNum) {
                        this.$message.error('退料数量不能为空！')
                        return
                    }
                    // this.queryParams.createBy = this.user.name
                    // this.queryParams.companyId = this.companyId
                    this.queryParams.backApplyInfo = {
                        id: this.rowId,
                        backPerson: this.queryParams.backPerson,
                        phone: this.queryParams.phone,
                        remark: this.queryParams.remark,
                        unitId: this.queryParams.unitId,
                        proId: this.queryParams.proId,
                        agreementId: this.queryParams.agreementId,
                        // backTime: this.queryParams.backTime,
                        // createBy: this.queryParams.createBy,
                        // companyId: this.queryParams.companyId,
                    }
                    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')
                            }, 1000)
                        }
                    } 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('addToolsSuccess')
                            }, 1000)
                        }
                    }
                }
            })
        },

        /** 删除按钮操作 */
        handleDelete(row, index) {
            this.$modal
                .confirm('是否确认删除所选择的数据项？')
                .then(() => {
                    // this.deviceType.forEach((e, index) => {
                    //     if (e[3] === row.typeId) {
                    //         this.deviceType.splice(index, 1)
                    //         this.propsKey++
                    //     }
                    // })
                    // this.equipmentList.splice(index+1, 1)
                    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() {
          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(
                'system/role/export',
                {
                    ...this.queryParams
                },
                `role_${currentTime}.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 deviceTypeChange(val) {
            const deviceTypeList = this.$refs.deviceTypeCascader.getCheckedNodes()
            console.log(deviceTypeList)
            let tempList = []
            if (val.length > 0) {
                const items = val.map(e => {
                    return e[3]
                })
                for (let i of items) {
                    for (let z of deviceTypeList) {
                        if (z.data.typeId === i) {
                            const obj = JSON.parse(JSON.stringify(z.data))
                            console.log(obj)
                            obj.typeModel = obj.typeName
                            obj.typeName = obj.materialName
                            obj.preNum = 0
                            obj.apDetection = ''
                            obj.remark = ''
                            obj.maCodeList = []
                            obj.bmFileInfos = []
                            tempList.push(obj)
                            break
                        }
                    }
                }
                const newDataListNew = [...this.equipmentList, ...tempList]
                const map = new Map()
                for (let item of newDataListNew) {
                    if (!map.has(item.typeId)) {
                        map.set(item.typeId, item)
                    }
                }
                const newArray = [...map.values()]
                let newArray_array = []
                items.forEach(e => {
                    newArray.forEach(j => {
                        if (e == j.typeId) {
                            newArray_array.push(j)
                        }
                    })
                })
                this.equipmentList = newArray_array
            } else {
                this.equipmentList = []
            }
        },
        //// 将数据处理成 表格中需要的数据
        handelTableItemData(node) {
            const template = JSON.parse(JSON.stringify(this.leaseApplyDetailsItem))
            template.createBy = this.createBy
            template.typeId = node.data.typeId
            // template.companyId = node.data.companyId
            // template.typeId = node.data.id
            template.unitName = node.data.unitName
            template.preNum = node.data.num
            template.typeName = node.pathLabels[2]
            template.typeCode = node.pathLabels[3]
            template.num = node.data.num
            template.useNum = node.data.useNum
            return template
        },
        // changeMachine(val){
        //     console.log(val)
        //     this.maData = this.machineList.find(option => option.maId == val);
        //     //  = this.machineList[index]
        // },

        //编码数据
        async getMachineById(typeId) {
            let param = {
                unitId: this.queryParams.unitId,
                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 = '1'
                })
            })
        },
        //编码类型-弹窗
        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.apDetection == '完好') {
                                sub.apDetection = '1'
                            } else if (sub.apDetection == '不合格' || sub.apDetection == '损坏') {
                                sub.apDetection = '0'
                            }
                            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) {
            console.log('yyyyyyyyyyyyyyyy',selection)
            if (!this.open) return
            // 检查新选中的行是否有isActive为true的情况
            const previousSelectionIds = new Set(this.maCodeList.map(item => item.maId))
             console.log('zzzzzzzzzzz',previousSelectionIds)
            const newlySelected = selection.filter(item => !previousSelectionIds.has(item.maId))
             console.log('pppppppppppppp',newlySelected)
            newlySelected.forEach(row => {
                if (row.isAlert) {
                    this.$message({
                        message: '当前工器具仍有班组在用，请核实退料单位',
                        type: 'warning'
                    })
                }
            })
            
            this.maCodeList = selection
            // console.log(selection)
            // this.queryParams.equipmentList = selection
        },
        //查询添加
        handleAddCode() {
            // console.log(this.rowData)
            // console.log(this.maCodeList)
            // console.log(this.maId)
            // console.log(this.maData)
            // if(this.maId!=""){
            // let obj = {
            //     materialName:this.maData.materialName,
            //     typeId:this.maData.typeId,
            //     typeName:this.maData.typeName,
            //     maId:this.maData.maId,
            //     maCode:this.maData.maCode,
            //     maStatus:this.maData.maStatus,
            //     bmFileInfos:[],
            //     apDetection:"",
            // }
            // let index = this.maCodeList.findIndex(v=>v.maId==this.maId)
            // if(index>-1){
            //     this.$message.error('设备编码已存在！')
            // }else{
            //     this.maCodeList.push(obj)
            // }
            // }else{
            //     this.$message.error('请先填写设备编码！')
            // }
        },
        // /** 删除按钮操作 */
        // handleDeleteCode(row) {
        //     this.maCodeList.splice(row.index, 1)
        // },
        // 弹窗保存
        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)
        },
        //文件上传前
        beforeFileUpload(row) {
            this.fileData = row
        },
        // 文件上传成功处理-退料列表上传
        handleFileSuccess(response, file, fileList) {
            if (response.code == 200) {
                let obj = {
                    name: response.data.name,
                    url: response.data.url
                }
                let index = this.equipmentList.findIndex(v => v.typeId == this.fileData.typeId)
                this.equipmentList[index].bmFileInfos = [obj]
            }
        },
        // 文件上传成功处理-编码弹窗上传
        handleFileSuccess2(response, file, fileList) {
            console.log(1111)
            if (response.code == 200) {
                let obj = {
                    name: response.data.name,
                    url: response.data.url
                }
                this.machineList.map((item, index2) => {
                    if (item.maCode == this.fileData.maCode) {
                        this.$set(item, 'bmFileInfos', [obj])
                        this.$set(item, 'fileName', response.data.name)
                    }
                })
                // let index = this.machineList.findIndex(v => v.maCode == this.fileData.maCode)
                // console.log(index)
                // this.machineList[index].bmFileInfos = [obj];
                // this.machineList[index].fileName = response.data.name;
                // this.machineList[index].showBtn = true;
                // this.machineList[index].apDetection = '1';
                // setTimeout(()=>{
                //     this.$forceUpdate()
                // },1000)
                console.log(this.machineList)
            }
        },
        //图片查看
        picturePreview(row) {
            console.log(row)
            console.log(row.bmFileInfos)
            if (row.bmFileInfos.length > 0) {
                let file = row.bmFileInfos[0]
                this.dialogImageUrl = file.url.replaceAll('#', '%23')
                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
                }
            }
        },
        // 高亮文本
        highlightText(text, keyword) {
            // console.log("vvvvvvvvvvv",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;
        }
    }
}
</style>
