<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="proName">
                    <el-input
                        v-model="queryParams.proName"
                        placeholder="退料单位"
                        clearable
                        style="width: 240px"
                        :disabled="isView"
                    />
                </el-form-item>
                <el-form-item label="退料工程" prop="unitName">
                    <el-input
                        v-model="queryParams.unitName"
                        placeholder="退料工程"
                        clearable
                        style="width: 240px"
                        :disabled="isView"
                    />
                </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"
                        :disabled="isView"
                    />
                </el-form-item>
                <el-form-item label="退料人电话" prop="phone">
                    <el-input
                        v-model="queryParams.phone"
                        placeholder="请输入退料人电话"
                        clearable
                        style="width: 240px"
                        :maxlength="11"
                        :disabled="isView"
                    />
                </el-form-item>
                <!-- <el-form-item label="物品类型" prop="deviceType">
                    <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="1" :disabled="isView"
                        type="textarea" maxlength="100"
                        style="width: 240px"
                    />
                </el-form-item>
            </el-row>
            <el-row> </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.preNum }}</div>
                    <!-- <el-input
                        v-if="scope.row.manageType==1"
                        v-model.number="scope.row.preNum"
                        placeholder="退料数量"
                        type="number"
                        min="1"
                        clearable :readonly="isView"
                        @input="checkNum(scope.row)"
                        style="width: 100%"
                    /> -->
                    <div v-if="scope.row.manageType==1">{{ scope.row.preNum }}</div>
                </template>
            </el-table-column>
            <el-table-column
                label="完好数量"
                align="center"
                prop="goodNum"
                min-width="120"
            >
            </el-table-column>
            <el-table-column
                label="损坏数量"
                align="center"
                prop="badNum"
                min-width="120"
            >
            </el-table-column>
            <!-- <el-table-column
                label="外观判定22"
                align="center"
                prop="apDetection"
                min-width="120"
            >
                <template slot-scope="scope">
                    <el-input
                        v-model.number="scope.row.apDetection"
                        placeholder="外观判定"
                        type="text" :readonly="isView"
                        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="备注" :readonly="isView"
                        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="1" :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">
                            查看
                        </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, index: scope.$index })">删除</el-button>
                </template>
            </el-table-column> -->
        </el-table>

        <el-dialog title="编码退料" :visible.sync="open" width="1000px" 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="maCodeList" width="100%" height="450px">
                <el-table-column label="序号" type="index" width="55" align="center"/>
                <el-table-column label="类型名称" prop="materialName" align="center" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="规格型号" prop="typeName" align="center" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="设备编码" prop="maCode" align="center" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="设备状态" prop="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 :readonly="isView"
                        style="width: 100%"
                    /> -->
                    <!-- <el-radio-group v-model="scope.row.apDetection" disabled>
                        <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="100">
                    <template slot-scope="scope">
                        <div style="display: flex;align-items: center;justify-content: center;">
                            <!-- <el-upload ref="upload" :limit="1" :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="操作" 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'
export default {
    name: 'ReturnApplyAdd',
    dicts: ['ma_machine_status'],
    props: {
        backId: {
            type: [String, Number],
        },
        agreementId: {
            type: [String, Number],
        },
        isView: {
            type: Boolean,
            default:true
        },
    },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            rowData:{},
            maId:"",
            maData:{},
            maCodeList: [],//编码表格
            machineList: [], // 编码下拉选 集合
            //图片查看弹窗
            dialogImageUrl: '',
            dialogVisible: false,
            fileData:{},
            //上传
            upload: {
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/file/upload'
            },
            unitId: null,
            projectId: 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: 'blur',
                        type: 'number',
                    },
                ],
                proId: [
                    {
                        required: true,
                        message: '请选择退料工程',
                        trigger: 'blur',
                        type: 'number',
                    },
                ],
                backPerson: [
                    {
                        required: true,
                        message: '请输入退料人',
                        trigger: 'blur',
                    },
                ],
                // backTime: [
                //     {
                //         required: true,
                //         message: '请选择退料时间',
                //         trigger: 'change',
                //     },
                // ],
                phone: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入退料人的手机号',
                    },
                    {
                        pattern: /^1[3456789]\d{9}$/,
                        message: '请输入正确的手机号码',
                        trigger: 'blur',
                    },
                ],
            },
            unitList: [], //单位 集合
            proList: [], // 工程 集合

            deviceTypeTree: [], // 设备 树结构数据
            // 设备 树显示 配置
            deviceTypeTreeProps: {
                children: 'children',
                label: 'typeName',
                // multiple: false,
                value: 'typeId',
                multiple: true,
            },
            // 选中的设备类型
            deviceType: null,
            // defaultProps: {
            //   children: "children",
            //   label: "label"
            // },
            // companyId: '',
            createBy: '',
            rowId: '',
            propsKey: 1000,
        }
    },
    mounted() {
        this.GetUnitData()
        this.GetProData()

        if (this.backId) {//编辑
            console.log(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: {
        // 获取 来往单位 列表数据
        async GetUnitData(val) {
            // if(this.equipmentList.length>0){
            //     this.$modal.confirm('是否确认更改退料单位，此操作将清空当前列表？').then(() => {

            //         this.$message.success('操作成功!')
            //     }).catch(() => {
            //         console.log(this.unitId)
            //         setTimeout(()=>{
            //             this.$set(this.queryParams,"unitId",this.unitId)
            //             console.log(this.queryParams.unitId)
            //             this.$forceUpdate()
            //         },500)

            //     })
            // }else{
            //     this.unitId=val
                const params = {
                    projectId: this.queryParams.proId /*  */,
                }
                const res = await getUnitList(params)
                this.unitList = res.data
                this.GetAgreementInfoById()
            // }

        },
        // 获取 工程名称 列表数据
        async GetProData(val) {
            // if(this.equipmentList.length>0){

            //     this.$modal.confirm('是否确认更改退料工程，此操作将清空当前列表？').then(() => {

            //         this.$message.success('操作成功!')
            //     }).catch(() => {
            //         // this.queryParams.proId=this.projectId
            //         console.log(this.projectId)
            //         setTimeout(()=>{
            //             this.$set(this.queryParams,"proId",this.projectId)
            //             console.log(this.queryParams.proId)
            //             this.$forceUpdate()
            //         },500)
            //     })
            // }else{
            //     this.projectId=val
                const params = {
                    unitId: this.queryParams.unitId,
                }
                const res = await getProjectList(params)
                this.proList = res.data
                this.GetAgreementInfoById()
            // }
        },

        // 获取 设备树结构数据
        async GetDeviceTypeTreeFn(agreementId) {
            const params = {
                agreementId: agreementId,
                unitId: this.queryParams.unitId,
            }
            const res = await getDeviceTreeByAgreementId(params)
            console.log('resgetUseTypeTreee==========', res)
            this.deviceTypeTree = res.data;
            //反显
            let selectList = []
            this.equipmentList.forEach((e) => {
                selectList.push(
                    this.getParentsById(this.deviceTypeTree, e.typeId),
                )
            })
            this.deviceType = selectList
            this.$forceUpdate()

        },
        //树结构数据获取父
        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.GetUnitData()
                    this.GetProData()
                } else {
                    this.queryParams.agreementId = res.data.agreementId
                    this.queryParams.agreementCode = res.data.agreementCode
                    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
            console.log(data)
            this.queryParams.unitId = data.backApplyInfo.unitId
            this.queryParams.proId = data.backApplyInfo.proId
            this.queryParams.unitName = data.backApplyInfo.unitName
            this.queryParams.proName = data.backApplyInfo.proName
            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.GetDeviceTypeTreeFn(data.backApplyInfo.agreementId)
            // this.$set(this.queryParams, 'phone', data.phone)
            // this.queryParams.backPerson = data.backPerson
            // this.queryParams.backTime = data.backTime
            // this.queryParams.agreementCode = data.agreementCode
            // this.queryParams.agreementId = data.agreementId
            // this.queryParams.remark = data.remark
            // this.equipmentList = res.data
            //
        },

        //是否可用勾选框
        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 = {
                        backPerson: this.queryParams.backPerson,
                        phone: this.queryParams.phone,
                        remark: this.queryParams.remark,
                        agreementId: this.queryParams.agreementId,
                        // backTime: this.queryParams.backTime,
                        // createBy: this.queryParams.createBy,
                        // companyId: this.queryParams.companyId,
                    }
                    if (this.rowId != '') {
                        let params = {
                            id:this.rowId,
                            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('goBackPage')
                            }, 1000)
                        }
                    }
                }
            })
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            this.$modal
                .confirm('是否确认删除所选择的数据项？')
                .then(() => {
                    this.deviceType.forEach((e, index) => {
                        if (e[3] === row.typeId) {
                            this.deviceType.splice(index, 1)
                            this.propsKey++
                        }
                    })
                    this.equipmentList.forEach((item, index) => {
                        if (item.id == row.id) {
                            this.equipmentList.splice(index, 1)
                        }
                    })
                })
                .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) {
            let maxNum = row.num
            if (row.preNum <= 1) {
                row.preNum = 1
            } else 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 = deviceTypeList[2].data.typeName
                            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
        },
        //编码下拉选数据
        getMachineById(typeId){
            let param = {
                unitId:this.queryParams.unitId,
                proId:this.queryParams.proId,
                typeId:typeId
            }
            getMachineById(param).then((res) => {
                this.machineList=res.data
            })
        },
        changeMachine(val){
            console.log(val)
            this.maData = this.machineList.find(option => option.maId == val);
            //  = this.machineList[index]
        },
        //编码类型-弹窗
        openAddCode(row){
            this.rowData=row;
            this.getMachineById(row.typeId)
            this.maId=""
            this.maCodeList=[]
            if(this.rowData.maCodeList&&this.rowData.maCodeList.length>0){
                this.maCodeList = this.rowData.maCodeList
            }
            this.open=true;
        },
        //查询添加
        handleAddCode(){
            console.log(this.rowData)
            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.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) {
            if(response.code==200){
                let obj = {
                    "name": response.data.name,
                    "url": response.data.url,
                }
                let index = this.maCodeList.findIndex(v=>v.maCode==this.fileData.maCode)
                this.maCodeList[index].bmFileInfos=[obj]

            }
        },
        //图片查看
        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
                }
            }
        },
    },
}
</script>
<style lang="scss">
.popper-select {
    .el-cascader-panel .el-scrollbar .el-checkbox {
        display: none;
    }

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