<template>
    <div>
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :rules="queryRules"
            :inline="true"
            v-show="showSearch"
            label-width="100px"
        >
            <el-form-item label="领用类型" prop="leaseType">
                <el-select
                    v-model="queryParams.leaseType"
                    filterable
                    placeholder="请选择领用类型"
                    clearable
                    style="width: 240px"
                    :disabled="isEdit"
                    @change="leaseTypeChange"
                >
                    <el-option
                        v-for="item in typeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        :disabled="isEdit"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="领料单位" prop="unitId">
                <el-select
                    v-model="queryParams.unitId"
                    filterable
                    clearable
                    @change="GetProData"
                    style="width: 240px"
                    placeholder="请选择"
                    :disabled="isEdit"
                >
                    <el-option
                        v-for="item in unitList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="领料工程" prop="proId">
                <el-select
                    v-model="queryParams.proId"
                    filterable
                    clearable
                    @change="GetUnitData"
                    style="width: 240px"
                    placeholder="请选择"
                    :disabled="isEdit"
                >
                    <el-option
                        v-for="item in proList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="协议号" prop="agreementCode">
                <el-input
                    maxlength="50"
                    v-model="queryParams.agreementCode"
                    disabled
                    style="width: 240px"
                ></el-input>
            </el-form-item>
            <el-form-item label="抱杆设备" prop="agreementCode">
                <el-select
                    clearable
                    style="width: 240px"
                    placeholder="请选择抱杆设备"
                    @change="onChangeWholeTypeName"
                    v-model="queryParams.wholeTypeName"
                >
                    <el-option
                        v-for="item in holdingPoleSelList"
                        :key="item.id"
                        :label="item.wholeTypeName"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="规格型号" prop="status">
                <el-cascader
                    filterable
                    collapse-tags
                    :key="propsKey"
                    style="width: 240px"
                    v-model="deviceType"
                    :show-all-levels="false"
                    ref="deviceTypeCascader"
                    :options="deviceTypeTree"
                    @change="deviceTypeChange"
                    placeholder="请输入规格型号"
                    popper-class="popper-select"
                    :props="deviceTypeTreeProps"
                    :disabled="
                        (isEdit && !isView) ||
                        isCost ||
                        wholeTypeNameList.length > 0
                    "
                ></el-cascader>
            </el-form-item>
            <el-form-item label="预计领料时间" prop="estimateLeaseTime">
                <el-date-picker
                    v-model="queryParams.estimateLeaseTime"
                    style="width: 240px"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="预计领料时间"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="领料人" prop="leasePerson">
                <el-input
                    maxlength="50"
                    v-model="queryParams.leaseApplyInfo.leasePerson"
                    placeholder="请输入领料人"
                    clearable
                    style="width: 240px"
                />
            </el-form-item>
            <el-form-item label="领料人电话" prop="phone">
                <el-input
                    v-model="queryParams.leaseApplyInfo.phone"
                    placeholder="请输入领料人电话"
                    clearable
                    style="width: 240px"
                    maxlength="11"
                    onkeyup="this.value = this.value.replace(/[^\d]/g,'');"
                />
            </el-form-item>
            <el-form-item
                label="费用承担方"
                prop="costBearingParty"
                v-if="queryParams.leaseType && queryParams.leaseType == 0"
            >
                <el-select
                    v-model="queryParams.costBearingParty"
                    filterable
                    clearable
                    style="width: 240px"
                    placeholder="请选择费用承担方"
                    :disabled="isEdit"
                >
                    <el-option
                        v-for="item in costBearingList"
                        :key="item"
                        :label="item"
                        :value="item"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="roleName">
                <el-input
                    maxlength="100"
                    v-model="queryParams.leaseApplyInfo.remark"
                    placeholder="请输入备注"
                    clearable
                    rows="1"
                    type="textarea"
                    style="width: 240px"
                />
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    plain
                    size="mini"
                    v-if="isView"
                    type="primary"
                    icon="el-icon-plus"
                    @click="handleAdd"
                >
                    保存
                </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-show="wholeTypeNameList.length > 0"
            :data="wholeTypeNameList"
        >
            <el-table-column type="index" align="center" />
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-table :data="props.row.childrenList">
                        <el-table-column
                            align="center"
                            prop="typeName"
                            label="设备名称"
                        />
                        <el-table-column
                            align="center"
                            label="规格型号"
                            prop="deviceType"
                        />
                        <el-table-column
                            align="center"
                            label="设备所属"
                            prop="deviceAscription"
                        />
                        <el-table-column
                            label="预领数量"
                            prop="deviceNum"
                            align="center"
                        />
                        <el-table-column
                            align="center"
                            label="库存数量"
                            prop="num"
                        />
                    </el-table>
                </template>
            </el-table-column>
            <el-table-column
                prop="wholeTypeName"
                align="center"
                label="抱杆设备名称"
            />
            <el-table-column align="center" label="抱杆设备数量" width="260">
                <template slot-scope="scope">
                    <el-input-number
                        :min="1"
                        :max="1000"
                        @change="onChangeInput($event, scope.$index)"
                        v-model="scope.row.wholeTypeNum"
                    />
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="180">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="danger"
                        @click="onHandelDelete(scope.$index)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <el-table
            v-loading="loading"
            :data="leaseApplyDetails"
            v-show="wholeTypeNameList.length === 0"
            @selection-change="handleSelectionChange"
        >
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column label="序号" type="index" width="80" />
            <el-table-column
                label="机具名称"
                prop="typeCn"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                label="规格型号"
                prop="guigeCn"
                :show-overflow-tooltip="true"
            />
            <el-table-column label="计量单位" prop="unitCn" />
            <el-table-column label="库存数量" prop="num" />
            <el-table-column label="预领数量" align="center">
                <template slot-scope="scope">
                    <el-input
                        v-model.number="scope.row.preNum"
                        placeholder="请输入预领数量"
                        type="number"
                        min="1"
                        @input="checkNum(scope.row)"
                        clearable
                        style="width: 100%"
                    />
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="createTime">
                <template slot-scope="scope">
                    <el-input
                        maxlength="100"
                        v-model="scope.row.remark"
                        placeholder="请输入备注"
                        clearable
                        style="width: 100%"
                    />
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                fixed="right"
                class-name="small-padding fixed-width"
                v-if="isView"
            >
                <template slot-scope="scope">
                    <!--          <el-button-->
                    <!--            size="mini"-->
                    <!--            type="text"-->
                    <!--            icon="el-icon-edit"-->
                    <!--            @click="handleBack(scope.row)"-->
                    <!--            v-hasPermi="['system:role:edit']"-->
                    <!--          >修改</el-button>-->
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="
                            handleDelete({
                                ...scope.row,
                                index: scope.$index,
                            })
                        "
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import {
    addCompleteSetToolsApi,
    queryCompleteSetToolsApi,
    getCompleteSetToolsApi,
    delCompleteSetToolsApi,
} from '@/api/store/completeTools.js'
import {
    getProData,
    getUnitData,
    getDeviceTypeTree,
    getAgreementInfoById,
    submitLeaseApply,
    getTaskDetail,
    editLeaseApply,
    getLeaseApplyListAll,
    getLeaseApplyAuditListAll,
    getCostBearingApi,
    getAgreementInfoByIdApi,
    getHoldingPoleSelListApi,
} from '@/api/claimAndRefund/receive'
import { getInfo } from '@/api/login'
export default {
    name: 'ReceiveApplyAdd',
    props: {
        isView: {
            type: Boolean,
            default: () => {
                return false
            },
        },
        isEdit: {
            type: Boolean,
            default: () => {
                return false
            },
        },
        viewTaskId: {
            type: [String, Number],
        },
        rejectTaskStatus: {
            type: [String, Number],
            default: () => {
                return null
            },
        },
    },
    data() {
        const validatePhone = (rule, value, callback) => {
            if (!value) {
                callback(new Error('退料人电话不能为空'))
                // this.$message.error("手机号不为空");
            } else if (value.length < 11) {
                callback(new Error('电话号码格式不正确'))
                // this.$message.error("手机号格式不正确");
            } else {
                callback()
            }
        }
        return {
            user: null, // 用户信息
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 角色表格数据
            roleList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 是否显示弹出层（数据权限）
            openDataScope: false,
            menuExpand: false,
            menuNodeAll: false,
            deptExpand: true,
            deptNodeAll: false,
            // isEdit: 'true',
            // 日期范围
            dateRange: [],
            // 数据范围选项
            dataScopeOptions: [
                {
                    value: '1',
                    label: '全部数据权限',
                },
                {
                    value: '2',
                    label: '自定数据权限',
                },
                {
                    value: '3',
                    label: '本部门数据权限',
                },
                {
                    value: '4',
                    label: '本部门及以下数据权限',
                },
                {
                    value: '5',
                    label: '仅本人数据权限',
                },
            ],
            // 菜单列表
            menuOptions: [],
            // 部门列表
            deptOptions: [],
            // 查询参数
            queryParams: {
                types: 2,
                unitId: null,
                proId: null,
                agreementId: null, //协议id
                agreementCode: null, //协议code
                companyId: '', //登录信息中取
                createBy: '', //用户名
                estimateLeaseTime: '',
                leaseType: '',
                taskType: 29,
                taskStatus: 31,
                //领料人信息
                leaseApplyInfo: {
                    leasePerson: '',
                    phone: '',
                    remark: '',
                },
                //领料详情集合
                leaseApplyDetails: [],
                wholeTypeName: '',
            },
            typeList: [
                { id: '0', name: '工程租赁' },
                { id: '1', name: '长期领用' },
            ], //集合
            leaseApplyDetails: [],
            leaseApplyInfoList: [],
            //领料详情单条模板
            leaseApplyDetailsItem: {
                parenntId: null,
                createBy: null,
                companyId: null,
                status: 0,
                typeId: null, //  树结构第4级   规格id
                typeCn: '', //显示的设备类型
                guigeCn: '', //显示的设备规格
                unitCn: '', //显示的设备 单位
                remark: '', //单条备注
                preNum: 1, //预领数量
                deviceNum: '',
            },
            //
            queryRules: {
                leaseType: [
                    {
                        required: true,
                        message: '请选择领用类型',
                        trigger: 'change',
                    },
                ],
                unitId: [
                    {
                        required: true,
                        message: '请选择领料单位',
                        trigger: 'change',
                    },
                ],
                proId: [
                    {
                        required: true,
                        message: '请选择领料工程',
                        trigger: 'change',
                    },
                ],
                costBearingParty: [
                    {
                        required: true,
                        message: '请选择费用承担方',
                        trigger: 'change',
                    },
                ],
                // leasePerson: [
                //   {
                //     required: true, message: '请输入领料人', trigger: 'blur',
                //   }
                // ],
                // phone: [
                //     {required: true, message: '请输入领料人手机号', trigger: 'change'},
                //     { validator: validatePhone, trigger: "blur" },
                //     { min: 11, message: "手机号不足11位", trigger: "blur" },
                // ],
            },
            unitList: [], //单位 集合
            proList: [], // 工程 集合
            deviceTypeTree: [], // 设备 树结构数据

            taskId: null, // 是否编辑

            // 设备 树显示 配置
            deviceTypeTreeProps: {
                multiple: true,
                value: 'id',
            },
            // 选中的设备类型
            deviceType: [],

            // 表单参数
            form: {},
            defaultProps: {
                children: 'children',
                label: 'label',
            },
            // 表单校验
            rules: {
                roleName: [
                    {
                        required: true,
                        message: '角色名称不能为空',
                        trigger: 'blur',
                    },
                ],
                roleKey: [
                    {
                        required: true,
                        message: '权限字符不能为空',
                        trigger: 'blur',
                    },
                ],
                roleSort: [
                    {
                        required: true,
                        message: '角色顺序不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            costBearingList: [],
            isCost: false,
            propsKey: 1000,
            holdingPoleSelList: [],
            wholeTypeNameList: [],
            wholeTypeItemsList: [],
        }
    },
    mounted() {
        this.GetUserInfo()

        this.GetUnitData()

        this.GetProData()

        this.getCostBearingFun()

        this.getHoldingPoleSelListData()

        // this.GetDeviceTypeTree()
        // this.getList();
        if (this.$route.query.taskId && !this.$route.query.isBack) {
            console.log('查看')
            this.GetTaskDetail(this.$route.query.taskId)
        }
        if (this.$route.query.taskId && this.$route.query.isBack) {
            console.log('驳回提交查看')
            this.GetTaskDetail2(this.$route.query.taskId)
        }
        // this.taskId = this.$route.query.taskId
        // this.isEdit = this.$route.query.isEdit
        this.taskId = this.viewTaskId

        if (this.taskId) {
            Promise.all([
                this.GetTaskDetail(this.taskId),
                this.GetDeviceTypeTree(),
            ]).then(() => {
                let selectList = []
                this.leaseApplyDetails.forEach((e) => {
                    selectList.push(
                        this.getParentsById(this.deviceTypeTree, e.typeId),
                    )
                })
                this.$nextTick(() => {
                    this.deviceType = selectList
                    this.propsKey++
                })
            })
        } else {
            this.GetDeviceTypeTree()
        }

        // console.log(typeof(this.isEdit))
        // this.$set('isEdit',this.$route.query.isEdit)
    },

    methods: {
        // 获取用户信息
        async GetUserInfo() {
            const res = await getInfo()
            this.user = res.user
        },

        // 获取 来往单位 列表数据
        async GetUnitData() {
            const params = {
                id: this.queryParams.proId,
            }
            const res = await getUnitData(params)
            this.unitList = res.data

            this.GetAgreementInfoById()
        },
        // 获取 工程名称 列表数据
        async GetProData() {
            const params = {
                id: this.queryParams.unitId,
            }
            const res = await getProData(params)
            this.proList = res.data

            this.GetAgreementInfoById()
        },

        // 获取 设备树结构数据
        async GetDeviceTypeTree() {
            const params = {
                level: 4,
            }
            getDeviceTypeTree(params).then((res) => {
                this.deviceTypeTree = res.data
            })
        },
        getParentsById(list, id) {
            for (let i in list) {
                if (list[i].id == id) {
                    //查询到就返回该数组对象的value
                    return [list[i].id]
                }
                if (list[i].children) {
                    let node = this.getParentsById(list[i].children, id)
                    if (node !== undefined) {
                        //查询到把父节把父节点加到数组前面
                        node.unshift(list[i].id)
                        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, '根据工程和单位获取协议id')

                if (res.data.isSlt == 1) {
                    this.$message.error(
                        '当前协议下对应的工程已完成结算，不可重复领料！',
                    )
                    this.isCost = true

                    if (this.leaseApplyDetails.length > 0) {
                        this.leaseApplyDetails = []
                    }
                } else {
                    this.isCost = false
                }
                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

                    // // 1. 判断当前协议对应的工程是否结算

                    // getAgreementInfoByIdApi({
                    //     agreementId: res.data.agreementId,
                    // })
                }
            }
        },

        // 获取 任务详情数据
        async GetTaskDetail(taskId) {
            const res = await getLeaseApplyListAll({ taskId })

            const data = res.rows[0]

            // unitId:null,
            // proId:null,
            // agreementId:null, //协议id
            // agreementCode: null,
            if (data.taskStatus == 100) {
                this.queryParams.taskStatus = 32
                this.queryParams.examineStatusId = '32'
            }
            this.queryParams.unitId = data.unitId
            this.queryParams.costBearingParty = data.costBearingParty
            this.queryParams.proId = data.proId
            this.queryParams.leaseApplyInfo.phone =
                data.leaseApplyInfoList[0].phone
            this.queryParams.leaseApplyInfo.leasePerson =
                data.leaseApplyInfoList[0].leasePerson
            this.queryParams.agreementCode = data.agreementCode
            this.queryParams.agreementId = data.agreementId
            this.queryParams.estimateLeaseTime = data.estimateLeaseTime

            // this.queryParams.leaseType = data.leaseType
            this.$set(this.queryParams, 'leaseType', data.leaseType)
            this.queryParams.leaseApplyInfo.remark =
                data.leaseApplyInfoList[0].remark
            this.leaseApplyInfoList = data.leaseApplyInfoList
            this.leaseApplyDetails = data.leaseApplyDetails.map((item) => {
                return this.handelEchoData(item)
            })
        },
        // 驳回提交 任务详情数据
        async GetTaskDetail2(taskId) {
            const res = await getLeaseApplyAuditListAll({ taskId })

            const data = res.rows[0]

            // unitId:null,
            // proId:null,
            // agreementId:null, //协议id
            // agreementCode: null,
            if (data.taskStatus == 100) {
                this.queryParams.taskStatus = 32
                this.queryParams.examineStatusId = '32'
            }
            this.queryParams.unitId = data.unitId
            this.queryParams.proId = data.proId
            this.queryParams.costBearingParty = data.costBearingParty
            this.queryParams.leaseApplyInfo.phone =
                data.leaseApplyInfoList[0].phone
            this.queryParams.leaseApplyInfo.leasePerson =
                data.leaseApplyInfoList[0].leasePerson
            this.queryParams.agreementCode = data.agreementCode
            this.queryParams.agreementId = data.agreementId
            this.queryParams.estimateLeaseTime = data.estimateLeaseTime
            // this.queryParams.leaseType = data.leaseType
            this.$set(this.queryParams, 'leaseType', data.leaseType)
            this.queryParams.leaseApplyInfo.remark =
                data.leaseApplyInfoList[0].remark
            this.leaseApplyInfoList = data.leaseApplyInfoList
            this.leaseApplyDetails = data.leaseApplyDetails.map((item) => {
                return this.handelEchoData(item)
            })
        },
        //生成回显数据
        handelEchoData(item) {
            const template = JSON.parse(
                JSON.stringify(this.leaseApplyDetailsItem),
            )
            template.createBy = item.createBy
            template.companyId = item.companyId
            template.typeId = item.typeId
            template.unitCn = item.unitName
            template.typeCn = item.typeName
            template.guigeCn = item.typeModelName
            template.remark = item.remark
            template.preNum = item.preNum
            template.deviceNum = item.deviceNum
            template.status = item.status
            template.parenntId = item.parenntId
            template.num = item.num
            return template
        },

        // 表单重置
        reset() {
            if (this.$refs.menu != undefined) {
                this.$refs.menu.setCheckedKeys([])
            }
            ;(this.menuExpand = false),
                (this.menuNodeAll = false),
                (this.deptExpand = true),
                (this.deptNodeAll = false),
                (this.form = {
                    roleId: undefined,
                    roleName: undefined,
                    roleKey: undefined,
                    roleSort: 0,
                    status: '0',
                    menuIds: [],
                    deptIds: [],
                    menuCheckStrictly: true,
                    deptCheckStrictly: true,
                    remark: undefined,
                })
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            // this.queryParams.leaseApplyDetails = selection
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case 'handleDataScope':
                    this.handleDataScope(row)
                    break
                case 'handleAuthUser':
                    this.handleAuthUser(row)
                    break
                default:
                    break
            }
        },

        /** 保存按钮操作 */
        handleAdd() {
            this.$refs.queryForm.validate(async (valid) => {
                if (!valid) {
                    return false
                } else {
                    if (
                        this.leaseApplyDetails.length === 0 &&
                        this.wholeTypeNameList.length === 0
                    ) {
                        this.$message.error('请添加机具类型或成套设备')
                        return
                    }

                    let canSave = true
                    if (this.leaseApplyDetails.length > 0) {
                        this.queryParams.leaseApplyDetails =
                            this.leaseApplyDetails
                        try {
                            this.queryParams.leaseApplyDetails.forEach(
                                (item) => {
                                    if (item.num == 0) {
                                        this.$message.error(
                                            '机具类型库存量为零无法领料',
                                        )
                                        throw new Error()
                                    }
                                    if (item.preNum == '') {
                                        this.$message.error('请填写预领数量')
                                        throw new Error()
                                    }
                                },
                            )
                        } catch (e) {
                            throw e
                        }
                    }

                    if (this.wholeTypeNameList.length > 0) {
                        const wholeTypeList = []
                        this.wholeTypeNameList.forEach((i) => {
                            i.childrenList.forEach((e) => {
                                const items = {
                                    companyId: '101',
                                    guigeCn: e.deviceType,
                                    preNum: e.deviceNum,
                                    typeCn: e.typeName,
                                    typeId: e.deviceTypeId,
                                    wholeTypeName: i.wholeTypeName,
                                }

                                wholeTypeList.push(items)
                            })
                        })

                        this.queryParams.leaseApplyDetails = wholeTypeList
                    }

                    if (!canSave) {
                        return false
                    }
                    this.queryParams.createBy = this.user.userName
                    this.queryParams.companyId = this.user.companyId
                    this.queryParams.userId = this.user.userId
                    let res
                    if (this.queryParams.leaseType == 1) {
                        this.queryParams.taskStatus = 117
                    }
                    if (this.taskId) {
                        this.leaseApplyInfoList.forEach((v) => {
                            v = Object.assign(
                                v,
                                this.queryParams.leaseApplyInfo,
                            )
                            this.$set(
                                v,
                                'leaseApplyDetails',
                                this.queryParams.leaseApplyDetails,
                            )
                        })
                        if (this.$route.query.isBack) {
                            this.queryParams.souceByRefuse = 1
                        }
                        if (this.rejectTaskStatus == 100) {
                            this.queryParams.souceByRefuse = 1
                        }
                        const params = {
                            ...this.queryParams,
                            taskId: this.taskId,
                            leaseApplyInfoList: this.leaseApplyInfoList,
                        }

                        res = await editLeaseApply(params)
                    } else {
                        // console.log(this.queryParams)
                        res = await submitLeaseApply(this.queryParams)
                    }
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: res.msg,
                        })
                        // this.$tab.closeOpenPage({
                        //     path: '/claimAndRefund/receiveByCq/receiveApply',
                        // })
                        this.$emit('goBackPage')
                    }
                }
            })
        },
        /** 修改按钮操作 */
        handleBack(row) {
            this.$tab.closeOpenPage({
                path: '/claimAndRefund/receiveByCq/receiveApply',
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.deviceType.forEach((e, index) => {
                if (e[3] === row.typeId) {
                    this.deviceType.splice(index, 1)
                    this.propsKey++
                }
            })
            this.leaseApplyDetails.splice(row.index, 1)
        },
        /** 导出按钮操作 */
        handleExport() {
            // this.download('system/role/export', {
            //   ...this.queryParams
            // }, `role_${new Date().getTime()}.xlsx`)
        },

        checkNum(row) {
            let maxNum = row.num
            if (row.preNum <= 1) {
                row.preNum = 1
            } else if (row.preNum >= maxNum) {
                row.preNum = maxNum
            }
        },
        /////// 设备类型树  切换
        deviceTypeChange(val) {
            const deviceTypeList =
                this.$refs.deviceTypeCascader.getCheckedNodes()

            // if (val.length > 0) {
            //     for (let i in val) {
            //         console.log(val[i], '----+++')
            //     }
            // }
            let tempList = []
            if (val.length > 0) {
                const items = val.map((e) => {
                    return e[3]
                })
                for (let i in items) {
                    for (let z in deviceTypeList) {
                        if (deviceTypeList[z].data.id === items[i]) {
                            let { num, companyId, id, unitName } =
                                deviceTypeList[z].data
                            tempList.push({
                                createBy: this.user.name,
                                typeId: id,
                                num,
                                companyId,
                                unitCn: unitName,
                                typeCn: deviceTypeList[z].pathLabels[2],
                                guigeCn: deviceTypeList[z].pathLabels[3],
                            })
                            break
                        }
                    }
                }

                const newDataList = [...this.leaseApplyDetails, ...tempList]
                const map = new Map()
                for (let item of newDataList) {
                    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.leaseApplyDetails = newArray_array
            } else {
                this.leaseApplyDetails = []
            }

            // const templateList = deviceTypeList.map((e) => {
            //     let { num, companyId, id, unitName } = e.data
            //     return {
            //         createBy: this.user.name,
            //         num,
            //         companyId,
            //         typeId: id,
            //         unitCn: unitName,
            //         typeCn: e.pathLabels[2],
            //         guigeCn: e.pathLabels[3],
            //     }
            // })
            // this.leaseApplyDetails = [...new Set(templateList)]
            // console.log(templateList, '----')

            // let nodes = null
            // nodes =
            //     this.$refs.deviceTypeCascader.getCheckedNodes().length > 0
            //         ? this.$refs.deviceTypeCascader.getCheckedNodes()
            //         : [this.$refs.deviceTypeCascader.panel.getNodeByValue(val)]
            // if (nodes[0].level != 4) {
            //     return
            // }
            // // console.log(this.leaseApplyDetails)
            // // console.log(nodes[0].data.id)
            // for (let i = 0; i < this.leaseApplyDetails.length; i++) {
            //     if (this.leaseApplyDetails[i].typeId == nodes[0].data.id) {
            //         this.leaseApplyDetails.splice(i, 1)
            //         break
            //     }
            // }
            // this.leaseApplyDetails.push(this.handelTableItemData(nodes[0]))
            // this.deviceType = {}
        },
        //// 将数据处理成 表格中需要的数据
        handelTableItemData(node) {
            const template = JSON.parse(
                JSON.stringify(this.leaseApplyDetailsItem),
            )
            template.createBy = this.user.name
            console.log(node.data)
            template.num = node.data.num
            template.companyId = node.data.companyId
            template.typeId = node.data.id
            template.unitCn = node.data.unitName
            template.typeCn = node.pathLabels[2]
            template.guigeCn = node.pathLabels[3]

            if (this.taskId) {
                const index = this.leaseApplyInfoList.find(
                    (key) => key.companyId == node.data.companyId,
                )
                template.parenntId = index ? index.id : ''
            }

            return template
        },

        // 获取费用承担方
        async getCostBearingFun() {
            const { data: res } = await getCostBearingApi()
            this.costBearingList = res
        },

        // 领用类型修改时清空费用承担方
        leaseTypeChange(val) {
            if (val == 0) {
                this.$set(this.queryParams, 'costBearingParty', '')
            } else {
                this.$delete(this.queryParams, 'costBearingParty')
            }
        },

        /* 获取抱杆下拉数据 */
        async getHoldingPoleSelListData() {
            const { data: res } = await getHoldingPoleSelListApi()
            this.holdingPoleSelList = res
        },
        /* 抱杆成套设备change事件 */
        onChangeWholeTypeName(val) {
            const selLable = this.holdingPoleSelList.find((e) => e.id === val)
            const wholeTypeNameData = {
                id: val,
                wholeTypeName: selLable.wholeTypeName,
                wholeTypeNum: 1,
                childrenList: [],
            }
            queryCompleteSetToolsApi(wholeTypeNameData).then((res) => {
                wholeTypeNameData.childrenList = res.data
                wholeTypeNameData.childrenList.forEach(
                    (e) => (e.initNum = e.deviceNum),
                )
                const isREpeat = this.wholeTypeNameList.find(
                    (e) => e.id === val,
                )
                if (!isREpeat) {
                    this.wholeTypeNameList.push(wholeTypeNameData)
                } else {
                    this.$modal.msgError(
                        '当前抱杆成套设备已添加，不可重复添加！',
                    )
                }

                console.log(this.wholeTypeNameList, '处理后的数据---')
            })

            this.queryParams.wholeTypeName = ''
        },

        /* 删除 */
        onHandelDelete(index) {
            this.wholeTypeNameList.splice(index, 1)
        },

        /* 更改数量 */
        onChangeInput(val, v) {
            this.wholeTypeNameList[v].childrenList.forEach(
                (e) => (e.deviceNum = e.initNum * val),
            )
        },
    },
}
</script>

<style lang="scss">
.popper-select {
    // li[aria-haspopup='true'] {
    //     .el-checkbox {
    //         display: none;
    //     }
    // }

    .el-cascader-panel .el-scrollbar .el-checkbox {
        display: none;
    }

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