<template>
    <!-- 新增工机具 -->
    <div class="app-container">
        <el-form :model="maForm" ref="maForm" size="small" :rules="rules" :inline="true" label-width="120px">
            <el-form-item label="到货日期" prop="arrivalTime">
                <el-date-picker
                    v-model="maForm.arrivalTime"
                    style="width: 240px"
                    value-format="yyyy-MM-dd hh:mm:ss"
                    type="date"
                    placeholder="请选择到货日期"
                    @change="arrivalTimeChange"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="物资厂家" prop="supplierId">
                <el-select v-model="maForm.supplierId" placeholder="物资厂家" clearable filterable style="width: 240px">
                    <el-option
                        v-for="item in supplierList"
                        :key="item.supplierId"
                        :label="item.supplier"
                        :value="item.supplierId"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="出厂日期" prop="productionTime">
                <div style="display: flex; align-items: center; gap: 10px">
                    <el-radio-group v-model="dateType" @change="handleDateTypeChange">
                        <el-radio-button label="day">选择某天</el-radio-button>
                        <el-radio-button label="month">选择月份</el-radio-button>
                    </el-radio-group>
                    <!-- <div style="height: 40px; flex: 1;"> -->
                    <el-date-picker
                        v-show="dateType === 'day'"
                        v-model="maForm.productionTime"
                        style="width: 240px"
                        value-format="yyyy-MM-dd"
                        type="date"
                        placeholder="请选择出厂日期"
                        @change="productionTimeChange"
                        :picker-options="pickerOptionsForProduction"
                    ></el-date-picker>

                    <el-date-picker
                        v-show="dateType === 'month'"
                        v-model="maForm.productionTime"
                        style="width: 240px"
                        value-format="yyyy-MM"
                        type="month"
                        placeholder="请选择出厂月份"
                        @change="productionMonthChange"
                        :picker-options="pickerOptionsForProductionMonth"
                    ></el-date-picker>
                    <!-- </div> -->
                </div>
            </el-form-item>
            <el-form-item label="税率" prop="taxRate">
                <el-input
                    v-model="maForm.taxRate"
                    placeholder="请输入税率"
                    clearable
                    maxlength="10"
                    style="width: 240px"
                    @input="taxRateChange"
                />
                <span>%</span>
            </el-form-item>

            <!-- <el-form-item label="类型规格" prop="deviceType">
                <el-row :gutter="10">
                    <el-col :span="15">
                        <el-select
                            ref="typeSelect"
                            v-model="tempDeviceType"
                            multiple
                            filterable
                            placeholder="请输入类型规格"
                            style="width: 500px"
                            @change="handleTypeChange"
                            clearable
                            collapse-tags
                            :filter-method="handleSearchImpl"
                            :popper-class="'type-select-dropdown'"
                            :popper-append-to-body="false"
                            @visible-change="handleVisibleChange"
                        >
                            <el-option
                                v-for="item 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> -->

            <el-form-item label="备注" prop="remark">
                <el-input
                    v-model="maForm.remark"
                    placeholder="请输入备注"
                    clearable
                    maxlength="150"
                    type="textarea"
                    style="width: 240px"
                    rows="2"
                />
            </el-form-item>
        </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">
                    导出
                </el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
            <!-- <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 label="采购数量" prop="purchaseNum" align="center" width="120">
                <template v-slot="scope">
                    <el-input
                        v-model="scope.row.purchaseNum"
                        type="text"
                        style="width: 100%"
                        @input="handlePreNum(scope.row, $event, 'input')"
                        @blur="handlePreNum(scope.row, $event, 'blur')"
                    />
                </template>
            </el-table-column>
            <el-table-column label="购置单价(元含税)" prop="purchaseTaxPrice" align="center" width="150">
                <template v-slot="scope">
                    <el-input-number
                        v-model="scope.row.purchaseTaxPrice"
                        controls-position="right"
                        style="width: 100%"
                        @blur="
                            scope.row.purchaseTaxPrice = scope.row.purchaseTaxPrice > 0 ? scope.row.purchaseTaxPrice : 0
                        "
                        :min="0"
                        :step="1"
                        @change="purchaseTaxPriceChange(scope.row, scope.$index)"
                    ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="购置单价(元不含税)" prop="purchasePrice" align="center" width="150">
                <template slot-scope="scope">
                    <el-input-number
                        v-model="scope.row.purchasePrice"
                        controls-position="right"
                        style="width: 100%"
                        :min="0"
                        :step="1"
                        disabled
                        @input="purchasePriceChange(scope.row, scope.$index)"
                    ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="是否为固定资产" prop="fixCode" align="center" width="120">
                <template slot-scope="scope">
                    <el-select v-model="scope.row.fixCode" placeholder="固定资产" filterable clearable>
                        <el-option label="是" value="1"></el-option>
                        <el-option label="否" value="0"></el-option>
                    </el-select>
                </template>
            </el-table-column>

            <el-table-column label="出厂日期" align="center" prop="productionTime" width="200">
                <template slot-scope="scope">
                    <el-date-picker
                        v-model="scope.row.productionTime"
                        style="width: 100%"
                        :value-format="dateType === 'day' ? 'yyyy-MM-dd' : 'yyyy-MM'"
                        :type="dateType === 'day' ? 'date' : 'month'"
                        :placeholder="dateType === 'day' ? '请选择出厂日期' : '请选择出厂月份'"
                        clearable
                    ></el-date-picker>
                </template>
            </el-table-column>

            <el-table-column label="相关配套资料" align="center" width="120" prop="bmFileInfos">
                <template slot-scope="scope">
                    <div
                        style="color: #02a7f0; cursor: pointer"
                        @click="openFileDialog(scope.row)"
                        v-if="scope.row.isExitFile == 1"
                    >
                        报告管理
                    </div>
                    <div
                        style="color: red; cursor: pointer"
                        @click="openFileDialog(scope.row)"
                        v-if="scope.row.isExitFile == 0"
                    >
                        报告管理
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.purchase_task_status" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        style="color: red"
                        @click="handleDelete(scope.row)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog title="报告管理" :visible.sync="open" width="900px" append-to-body>
            <el-table :data="fileDataList" width="100%" height="350px">
                <el-table-column label="序号" type="index" width="55" align="center" />
                <el-table-column label="报告类型" align="center" prop="dictLabel" :show-overflow-tooltip="true" />
                <el-table-column label="类型名称" align="center" :show-overflow-tooltip="true">
                    <template>
                        <div>{{ this.rowData.maTypeName }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="规格型号" align="center" :show-overflow-tooltip="true">
                    <template>
                        <div>{{ this.rowData.typeName }}</div>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="报告日期" align="center" prop="orgName" :show-overflow-tooltip="true"/>
                <el-table-column label="截止有效期" align="center" prop="orgName" :show-overflow-tooltip="true"/> -->
                <el-table-column label="操作" align="center" width="100">
                    <template slot-scope="scope">
                        <div style="display: flex; align-items: center; justify-content: space-between">
                            <el-upload
                                ref="upload"
                                :headers="upload.headers"
                                :action="upload.url"
                                :show-file-list="false"
                                accept=".png, .jpg, .jpeg, .pdf, .doc, .docx"
                                :on-success="
                                    (response, file, fileList) => handleFileSuccess(scope.row, response, file, fileList)
                                "
                                :auto-upload="true"
                                :before-upload="file => beforeUpload(scope.row, file)"
                            >
                                <el-button size="mini" type="text" @click="beforeFileUpload(scope.row)">上传</el-button>
                            </el-upload>

                            <el-button
                                size="mini"
                                type="text"
                                @click="picturePreviewFile(scope.row)"
                                v-if="scope.row.fileListTemp != 0"
                                style="margin-left: 20px"
                            >
                                查看
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

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

        <!-- 文件查看列表 -->
        <el-dialog title="文件列表" :visible.sync="dialogVisibleFile" width="500px" height="500px">
            <el-table :data="fileListInfo" width="100%" height="350px">
                <el-table-column label="序号" type="index" width="55" align="center" />
                <el-table-column label="文件名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="picturePreview(scope.row)" v-if="scope.row.url">
                            查看
                        </el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="pictureDelete(scope.row, scope.$index)"
                            v-if="scope.row.url"
                            style="color: red"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import {
    getPurchaseCheckInfo,
    equipmentTypeTree,
    addPurchaseCheckInfo,
    updatePurchaseCheckInfoApi
} from '@/api/purchase/goodsArrived'
import { getListFacturer } from '@/api/ma/supplier'
import { getToken } from '@/utils/auth'
import { uploadPurchaseFile, getPurchaseFileList } from '@/api/purchase/goodsAccept'

export default {
    name: 'editTools',
    dicts: ['purchase_task_status'],
    data() {
        return {
            taskId: '',
            // isEdit: false,
            // 遮罩层
            loading: false,
            loadingTwo: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            //物资厂家
            supplierList: [],
            //机具类型
            equipmentTypeList: [],
            // 角色表格数据
            equipmentList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            rowData: {},
            fileDataList: [
                { dictLabel: '合格证', fileType: '0', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '型式试验报告', fileType: '1', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '其他', fileType: '4', name: '', url: '', fileList: [], fileListTemp: [] }
            ],
            fileListInfo: [],
            //图片查看弹窗
            dialogImageUrl: '',
            dialogVisible: false,
            dialogVisibleFile: false,
            //上传
            upload: {
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/file/upload'
            },
            // 查询参数
            queryParams: {
                equipmentId: undefined,
                productionTime: ''
            },
            dateType: 'day', // 默认选择天
            maForm: {
                taxRate: 13,
                arrivalTime: '',
                purchaser: '',
                remark: '',
                purchaseNumber: '',
                productionTime: ''
            },
            // 表单参数
            form: {},
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            // 表单校验
            rules: {
                taxRate: [
                    {
                        required: true,
                        message: '请填写税率',
                        trigger: 'blur'
                    }
                ],
                arrivalTime: [
                    {
                        required: true,
                        message: '请选择到货日期',
                        trigger: 'blur'
                    }
                ]
                // purchaser: [
                //   { required: true, message: "采购员不能为空", trigger: "blur" }
                // ]
            },
            deviceTypeTreeProps: {
                children: 'children',
                label: 'typeName',
                // multiple: false,
                value: 'typeId',
                multiple: true
            },
            deviceType: [],
            propsKey: 1000,
            // taxRate:0,
            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 // 添加搜索状态标记
        }
    },
    computed: {
        pickerOptions() {
            return {
                disabledDate(time) {
                    const currentDate = new Date()
                    currentDate.setHours(0, 0, 0, 0)
                    return time.getTime() < currentDate.getTime()
                }
            }
        },
        //限制出厂日期不能大于到货日期
        pickerOptionsForProduction() {
            return {
                disabledDate: time => {
                    if (this.maForm.arrivalTime) {
                        const standardFormat = this.maForm.arrivalTime.replace(
                            /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/,
                            '$1-$2-$3T$4:$5:$6'
                        )
                        const arrivalDate = new Date(standardFormat)
                        arrivalDate.setHours(23, 59, 59, 999)
                        return time.getTime() >= arrivalDate.getTime()
                    }
                    return false
                }
            }
        },

        pickerOptionsForProductionMonth() {
            return {
                disabledDate: time => {
                    if (this.maForm.arrivalTime) {
                        const standardFormat = this.maForm.arrivalTime.replace(
                            /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/,
                            '$1-$2-$3T$4:$5:$6'
                        )
                        const arrivalDate = new Date(standardFormat)
                        arrivalDate.setHours(23, 59, 59, 999)
                        // 禁用整月，如果该月的任何一天大于到货日期
                        const monthStart = new Date(time.getFullYear(), time.getMonth(), 1)
                        const monthEnd = new Date(time.getFullYear(), time.getMonth() + 1, 0)
                        return monthStart.getTime() >= arrivalDate.getTime()
                    }
                    return false
                }
            }
        }
    },
    watch: {},
    mounted() {
        // 获取路由参数
        this.isEdit = true
        const { taskId, id } = this.$route.query
        console.log('🚀 ~ mounted ~ isEdit, taskId, id:', taskId, id)
        this.taskId = taskId
        this.id = id
        this.supplierInfoList()
        this.equipmentType()
        this.getTaskInfo()
    },
    methods: {
        handlePreNum(row, val, type) {
            if (type === 'input') {
                const reg = row.unitValue == 1
                ? val.replace(/[^\d.]/g, '')  // 允许小数
                : val.replace(/[^\d]/g, '')   // 只能整数
                row.purchaseNum = reg
            } else if (type === 'blur') {
                if (row.purchaseNum !== '') {
                    row.purchaseNum = Number(row.purchaseNum)
                }
            }
        },
        handleDateTypeChange(val) {
            console.log('xxxxx', val)
            if (val === 'day') {
                // 切换到选择某天时，清空月份选择
                this.maForm.productionTime = ''
                // 将表格中的月份数据转换为该月第一天
                this.equipmentList.forEach(item => {
                    if (item.status === 1 || (item.status === 12 && item.productionTime)) {
                        item.productionTime = `${item.productionTime}-01`
                    }
                })
            } else {
                // 切换到选择月份时，清空日期选择
                this.maForm.productionTime = ''
                // 将表格中的日期数据转换为月份
                this.equipmentList.forEach(item => {
                    if (item.status === 1 || (item.status === 12 && item.productionTime)) {
                        item.productionTime = item.productionTime.slice(0, 7)
                    }
                })
            }
        },
        // 格式化日期的函数
        formatDate(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}`
        },
        // 税率
        taxRateChange(val) {
            this.maForm.taxRate = val.replace(/[^\d.]/g, '')
            this.equipmentList.forEach(item => {
                if (item.status == 1 || item.status == 12) {
                    item.purchasePrice = ((item.purchaseTaxPrice / (100 + Number(this.maForm.taxRate))) * 100).toFixed(
                        10
                    )
                }
            })
        },
        // 含税单价
        purchaseTaxPriceChange(row, val) {
            row.purchaseTaxPrice = row.purchaseTaxPrice.toFixed(2)
            row.purchasePrice = ((row.purchaseTaxPrice / (100 + Number(this.maForm.taxRate))) * 100).toFixed(10)
        },
        // 不含税单价
        purchasePriceChange(row, val) {
            // row.purchaseTaxPrice = ((row.purchasePrice*(100 + this.maForm.taxRate))/100).toFixed(2)
        },
        /** 物资厂家-下拉选 */
        supplierInfoList() {
            let param = {
                pageNum: 1,
                pageSize: 1000,
                keyWord: undefined
            }
            getListFacturer(param).then(response => {
                this.supplierList = response.rows
            })
        },

        /** 机具类型 */
        equipmentType() {
            equipmentTypeTree().then(response => {
                this.equipmentTypeList = response.data
                // 处理并扁平化所有类型数据
                this.flattenTypeOptions = this.processTypeData(response.data)
                // 初始显示所有选项
                this.filteredOptions = [...this.flattenTypeOptions]
                //反显
                // let selectList = []
                // console.log(this.equipmentList)
                // this.equipmentList.forEach(e => {
                //     console.log(this.equipmentList)
                //     selectList.push(this.getParentsById(this.equipmentTypeList, e.typeId, e.status))
                // })
                // this.deviceType = selectList
                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,
                        maxSortPriority: node.maxSortPriority
                        // rentPrice: node.rentPrice,
                    })
                }

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

            data.forEach(node => traverse(node))
            result.sort((a, b) => b.maxSortPriority - a.maxSortPriority)
            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 {
                    console.log(typeData, 'typeData')
                    // if(typeData.rentPrice>0){//判断是否有租赁价格：有禁用;无修改;
                    //     typeData.rentPriceDisabled=true
                    // }else{
                    //     typeData.rentPriceDisabled=false
                    // }
                    // 将新项添加到数组开头，实现倒序
                    this.equipmentList.unshift({
                        ...typeData,
                        createTime: null,
                        productionTime: this.maForm.productionTime,
                        purchaseTaxPrice: 0,
                        purchasePrice: 0,
                        purchaseNum: 1,
                        fixCode: '0',
                        status: 1,
                        isExitFile: '1',
                        bmFileInfos: []
                    })
                    this.deviceType.push(lastSelected)
                    this.$message({
                        message: `已添加 ${typeData.typeName}`,
                        type: 'success'
                    })
                }
            }

            // 清空临时选中值
            this.$nextTick(() => {
                this.tempDeviceType = []
            })
        },
        //树结构数据获取父
        getParentsById(list, id, status) {
            for (let i in list) {
                if (list[i].typeId == id) {
                    console.log(id)
                    console.log(status)
                    if (status != 1 && status != 12) {
                        list[i].disabled = true
                    }
                    //查询到就返回该数组对象的value
                    return [list[i].typeId]
                }
                if (list[i].children) {
                    let node = this.getParentsById(list[i].children, id, status)
                    if (node !== undefined) {
                        //查询到把父节把父节点加到数组前面
                        node.unshift(list[i].typeId)
                        return node
                    }
                }
            }
        },
        //添加机具类型
        deviceTypeChange(val) {
            const deviceTypeList = this.$refs.deviceTypeCascader.getCheckedNodes()
            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(z.data)
                            // obj.supplierId = ''
                            obj.createTime = null
                            obj.productionTime = this.maForm.productionTime
                            obj.purchaseTaxPrice = 0
                            obj.purchasePrice = 0
                            obj.purchaseNum = 1
                            obj.fixCode = '0'
                            obj.status = 1
                            obj.bmFileInfos = []
                            // if(obj.rentPrice>0){//判断是否有租赁价格：有禁用;无修改;
                            //     obj.rentPriceDisabled=true
                            // }else{
                            //     obj.rentPriceDisabled=false
                            // }
                            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
                console.log(this.equipmentList)
            } else {
                this.equipmentList = []
            }
        },
        //选择到货日期
        arrivalTimeChange(val) {
            this.maForm.productionTime = ''
            // 同时清空表格中每行的出厂日期
            this.equipmentList.forEach(item => {
                if (item.status === 1 || item.status === 12) {
                    item.productionTime = ''
                }
            })
        },
        //选择出厂日期
        productionTimeChange(val) {
            this.equipmentList.forEach(item => {
                if (item.status == 1 || item.status == 12) {
                    item.productionTime = val
                }
            })
        },
        //选择出厂日期
        productionMonthChange(val) {
            console.log('yyyyyyy', val)
            this.equipmentList.forEach(item => {
                if (item.status === 1 || item.status === 12) {
                    item.productionTime = val
                }
            })
        },
        //获取任务详情--- 编辑回显数据
        async getTaskInfo() {
            // this.loading = true;
            await getPurchaseCheckInfo({ taskId: this.taskId, id: this.id, taskStage: 2 }).then(response => {
                this.maForm = response.data.purchaseCheckInfo
                this.maForm.id = response.data.purchaseCheckInfo.id
                this.maForm.taskId = response.data.purchaseCheckInfo.taskId
                this.maForm.arrivalTime = response.data.purchaseCheckInfo.arrivalTime
                this.maForm.supplierId = response.data.purchaseCheckInfo.supplierId
                this.maForm.remark = response.data.purchaseCheckInfo.remark
                this.maForm.taxRate = response.data.purchaseCheckInfo.taxRate
                // 判断 productionTime 格式
                const productionTime = response.data.purchaseCheckInfo.productionTime
                if (productionTime && productionTime.length === 10) {
                    // 假设 10 位长度为 yyyy-MM-dd
                    this.dateType = 'day'
                    this.maForm.productionTime = productionTime
                } else if (productionTime && productionTime.length === 7) {
                    // 假设 7 位长度为 yyyy-MM
                    this.dateType = 'month'
                    this.maForm.productionTime = productionTime
                } else {
                    // 默认选择某天
                    this.dateType = 'day'
                    this.maForm.productionTime = ''
                }
                this.equipmentList = response.data.purchaseCheckDetailsList
                this.equipmentList.forEach(item => {
                    item.rentPriceDisabled = true
                })
                console.log(this.equipmentList)
                // this.loading = false;
            })
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.roleId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 保存按钮操作 */
        handleSave() {
            if (this.equipmentList.length > 0) {
                // 每个物资至少上传一个报告
                const noReportIndex = this.equipmentList.findIndex(
                    item => !item.bmFileInfos || item.bmFileInfos.length === 0
                )
                if (noReportIndex > -1) {
                    this.$modal.msgError(`第${noReportIndex + 1}行未上传报告，请补充后再提交！`)
                    return
                }
                this.$refs['maForm'].validate(valid => {
                    if (valid) {
                        this.maForm.taskId = this.taskId
                        let index = this.equipmentList.findIndex(item => item.purchaseNum == 0)
                        // let index1 =this.equipmentList.findIndex(item=>item.rentPrice==0)
                        let index2 = this.equipmentList.findIndex(item => item.purchaseTaxPrice == 0)
                        if (index > -1) {
                            this.$modal.msgError('采购数量不能为0！')
                        }
                        // else if(index1>-1){
                        //     this.$modal.msgError('租赁价格不能为0！')
                        // }
                        else if (index2 > -1) {
                            this.$modal.msgError('购置单价(含税)不能为0！')
                        } else {
                            this.$modal
                                .confirm('是否确认保存当前页面')
                                .then(function () {})
                                .then(() => {
                                    this.loading = true
                                    updatePurchaseCheckInfoApi({
                                        purchaseCheckDetailsList: this.equipmentList,
                                        purchaseCheckInfo: this.maForm
                                    }).then(response => {
                                        if (response.code == 200) {
                                            this.$modal.msgSuccess('编辑成功')
                                        }
                                        this.loading = false
                                        //关闭页面
                                        this.$router.push({ name: 'GoodsAccept', params: { isReset: 'true' }}).then(res => {
                                            this.$tab.closePage({ path: '/purchase/editTools'})
                                        })
                                    })
                                })
                                .catch(() => {
                                    this.loading = false
                                })
                        }
                    }
                })
            } else {
                this.$modal.msgError('请先添加机具类型')
            }
        },
        //文件管理
        async openFileDialog(row) {
            console.log('1111111', row)
            this.rowData = row
            if (this.taskId == '') {
                this.fileDataList = [
                    { dictLabel: '合格证', fileType: '0', name: '', url: '', fileList: [], fileListTemp: [] },
                    { dictLabel: '型式试验报告', fileType: '1', name: '', url: '', fileList: [], fileListTemp: [] },
                    { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '', fileList: [], fileListTemp: [] },
                    { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '', fileList: [], fileListTemp: [] },
                    { dictLabel: '其他', fileType: '4', name: '', url: '', fileList: [], fileListTemp: [] }
                ]
                // 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
                        this.fileDataList[index].fileList.push({
                            name: item.name,
                            url: item.url
                        })
                        this.fileDataList[index].fileListTemp.push({
                            name: item.name,
                            url: item.url
                        })
                    })
                }
            } else {
                this.fileDataList = [
                    { dictLabel: '合格证', fileType: '0', name: '', url: '', fileList: [], fileListTemp: [] },
                    { dictLabel: '型式试验报告', fileType: '1', name: '', url: '', fileList: [], fileListTemp: [] },
                    { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '', fileList: [], fileListTemp: [] },
                    { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '', fileList: [], fileListTemp: [] },
                    { dictLabel: '其他', fileType: '4', name: '', url: '', fileList: [], fileListTemp: [] }
                ]
                if (this.rowData.bmFileInfos == null) {
                    await this.getFileData()

                    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
                            this.fileDataList[index].fileList.push({
                                name: item.name,
                                url: item.url
                            })
                            this.fileDataList[index].fileListTemp.push({
                                name: item.name,
                                url: item.url
                            })
                        })
                    }
                } else {
                    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
                            this.fileDataList[index].fileList.push({
                                name: item.name,
                                url: item.url
                            })
                            this.fileDataList[index].fileListTemp.push({
                                name: item.name,
                                url: item.url
                            })
                        })
                    }
                }
            }
            this.open = true
        },
        async getFileData() {
            let param = {
                modelId: this.rowData.typeId,
                taskType: 0,
                taskId: this.rowData.taskId
            }
            this.rowData.bmFileInfos = []
            await getPurchaseFileList(param)
                .then(response => {
                    if (response.rows.length > 0) {
                        response.rows.forEach(item => {
                            let index = this.fileDataList.findIndex(v => v.fileType == item.fileType)
                            item.fileDetailList.forEach(item2 => {
                                // this.fileDataList[index].fileList.push({
                                //     name:item2.name,
                                //     url:item2.url
                                // })
                                // this.fileDataList[index].fileListTemp.push({
                                //     name:item2.name,
                                //     url:item2.url
                                // })
                                const obj = {
                                    taskId: this.taskId,
                                    taskType: '0',
                                    name: item2.name,
                                    url: item2.url,
                                    modelId: this.rowData.partId,
                                    fileType: item2.fileType
                                }
                                this.rowData.bmFileInfos.push(obj)
                                console.log('77777777', this.rowData)
                            })
                        })
                    }
                })
                .catch(() => {})
        },
        beforeFileUpload(row) {
            this.rowData.fileType = row.fileType
        },

        beforeUpload(row, file) {
            row.fileList.push(file)
            console.log('6666666', row.fileList)
            if (row.fileList.length > 3) {
                this.$message.warning('最多只能上传三张图片')
                // 删除最后一个文件
                row.fileList.pop()
                return false // 阻止上传
            }
            return true // 允许上传
        },
        // 文件上传成功处理
        handleFileSuccess(row, response, file, fileList) {
            if (response.code == 200) {
                if (this.taskId == '') {
                    //新增逻辑
                    row.fileListTemp.push({
                        name: response.data.name,
                        url: response.data.url
                    })
                    // 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.partId,
                        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 {
                    //编辑逻辑
                    row.fileListTemp.push({
                        name: response.data.name,
                        url: response.data.url
                    })
                    let obj = {
                        taskId: this.taskId,
                        taskType: '0',
                        name: response.data.name,
                        url: response.data.url,
                        modelId: this.rowData.partId,
                        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)
                    }
                    uploadPurchaseFile(obj)
                        .then(response => {
                            this.$modal.msgSuccess('上传成功')
                        })
                        .catch(() => {
                            this.$modal.msgError('上传失败')
                        })
                }
            }
        },

        picturePreviewFile(row) {
            row.fileList = []
            row.fileListTemp.forEach(item => {
                row.fileList.push({
                    name: item.name,
                    url: item.url
                })
            })
            this.fileId = row.fileType
            this.fileListInfo = row.fileListTemp

            this.dialogVisibleFile = true
        },

        //图片查看
        picturePreview(file) {
            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
            }
        },

        //删除图片
        pictureDelete(row, id) {
            let index = id
            this.fileListInfo = this.fileListInfo.filter(item => item.url !== row.url)
            this.fileDataList[this.fileId].fileList = this.fileDataList[this.fileId].fileList.filter(
                item => item.url !== row.url
            )
            this.fileDataList[this.fileId].fileListTemp = this.fileDataList[this.fileId].fileListTemp.filter(
                item => item.url !== row.url
            )
            let bmFiles = []
            this.rowData.bmFileInfos.forEach(item => {
                if (item.fileType != this.fileId) {
                    bmFiles.push(item)
                } else {
                    if (item.url != row.url) {
                        bmFiles.push(item)
                    }
                }
            })
            this.rowData.bmFileInfos = bmFiles
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            // console.log(row.id)
            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`
            )
        },
        // 高亮文本
        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>
::v-deep .el-picker-panel {
    z-index: 999999 !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>
