<template>
    <!-- 新增工机具 -->
    <div class="app-container">
        <el-form :model="maForm" ref="maForm" :rules="rules" size="small" :inline="true" label-width="120px">
                <el-form-item label="结算单位"  prop="unitId">
                    <el-select
                        v-model="repairParams.unitId"
                        placeholder="请选择往来单位"
                        clearable
                        filterable
                        @change="unitChange"
                    >
                        <el-option
                            v-for="item in unitList"
                            :key="item.unitId"
                            :label="item.unitName"
                            :value="item.unitId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="结算工程" prop="projectId">
                    <el-select
                        v-model="repairParams.projectId"
                        placeholder="请选择工程名称"
                        clearable
                        filterable
                        @change="proChange"
                    >
                        <el-option
                            v-for="item in projectList"
                            :key="item.projectId"
                            :label="item.projectName"
                            :value="item.projectId"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="协议号" prop="agreementCode">
                    <el-input maxlength="50" v-model="repairParams.agreementCode" disabled style="width: 240px"></el-input>
                </el-form-item>

            <!-- <el-form-item label="规格型号" prop="equipmentId">
                <el-cascader
                    :key="propsKey"
                    v-model="deviceType"
                    :show-all-levels="false"
                    :options="equipmentTypeList"
                    :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>
             <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleSave">保存</el-button>
             <el-button type="success" plain icon="el-icon-download" size="mini" @click="downloadModel">模板下载</el-button>
             <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="uploadModel">模板上传</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="equipmentList" >>
            <el-table-column align="center" label="序号" type="index" width="55" />
            <el-table-column
                align="center"
                label="机具名称"
                prop="machineTypeName"
                show-overflow-tooltip
            ></el-table-column>
            <el-table-column align="center" label="规格型号" prop="specificationType" show-overflow-tooltip />
            <el-table-column align="center" label="计量单位" prop="unitName" />
            <el-table-column align="center" label="维修配件名称" prop="partName" width="180">
                <template slot-scope="scope">
                    <el-input
                    maxlength="100"
                    v-model="scope.row.partName"
                    placeholder="请输入"
                    clearable
                    style="width: 100%"
                    />
                </template>
            </el-table-column>
            <el-table-column label="维修配件型号" align="center" prop="partModelName" width="180">
                <template slot-scope="scope">
                    <el-input
                    maxlength="100"
                    v-model="scope.row.partModelName"
                    placeholder="请输入"
                    clearable
                    style="width: 100%"
                    />
                </template>
            </el-table-column>
            <el-table-column label="使用数量" align="center" prop="partNum">
                <template slot-scope="scope">
                    <el-input-number
                        type="number"
                        :min="1"
                        :precision="0"
                        v-model.number="scope.row.partNum"
                        @change="calculateTotalPrice(scope.row)"
                        style="width: 100%"
                    ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="配件单价" align="center" prop="partPrice" >
                <template slot-scope="scope">
                    <el-input
                    type="number"
                    maxlength="100"
                    v-model.number="scope.row.partPrice"
                    placeholder="请输入"
                    @input="calculateTotalPrice(scope.row)"
                    style="width: 100%"
                    />
                </template>
            </el-table-column>
            <el-table-column label="配件总价" align="center" prop="partAllCosts">
                <template slot-scope="scope">
                    <el-input
                    :value="scope.row.partAllCosts || '0.00'"
                    placeholder="自动计算"
                    readonly
                    style="width: 100%"
                    />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        style="color: red"
                        @click="handleDelete(scope.row)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <el-dialog
        title="模板上传"
        :visible.sync="dialogUpload"
        width="400px"
        append-to-body
    >
        <template >
            <el-upload
                class="upload-demo"
                drag
                :action="actionUrl"
                :headers="headers"
                :on-success="handleUploadSuccess"
                :accept="'.xlsx'"
                :before-upload="beforeUpload"
                :auto-upload="true"
                :show-file-list="false"
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip" style="color: red;">只能上传.xls或.xlsx文件</div>
            </el-upload>
        </template>
    </el-dialog>
    </div>
</template>

<script>
import { getUnitList,  getAgreementInfoById, } from '@/api/claimAndRefund/receive'
import { getProjectListByUnitIds,addRepairInputInfoApi } from '@/api/cost/cost'
import { getUserByRoleList } from '@/api/system/user'
import { equipmentTypeTree, } from '@/api/store/tools'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import HoldingpoleDialog from '@/components/HoldingpoleDialog/index.vue'

import {} from '@/api/store/newBuy'


export default {
    name: 'RepairCostList',
    dicts: ['sys_normal_disable'],
    components: { Treeselect, HoldingpoleDialog },
    data() {
        return {
            actionUrlPic: process.env.VUE_APP_BASE_API + '/system/sys/file/upload',
            actionUrl: process.env.VUE_APP_BASE_API + '/material/purchaseCheckInfo/importRepairData',
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('token'),
            },
            aform: {
                checkUrl: '',
                checkUrlName: '',
                fileListNew: [],
            },
            taskId: '',
            // isEdit: false,
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            //制造厂家（供应商管理）
            supplierList: [],
            //机具类型
            equipmentTypeList: [],
            // 用户数据
            userList: [],
            // 角色表格数据
            equipmentList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 是否显示弹出层（数据权限）
            openDataScope: false,
            menuExpand: false,
            menuNodeAll: false,
            deptExpand: true,
            deptNodeAll: false,
            showDialog: false,
            holdingpoleData: {},
            // 日期范围
            dateRange: [],
            // 数据范围选项
            dataScopeOptions: [
                {
                    value: '1',
                    label: '全部数据权限',
                },
                {
                    value: '2',
                    label: '自定数据权限',
                },
                {
                    value: '3',
                    label: '本部门数据权限',
                },
                {
                    value: '4',
                    label: '本部门及以下数据权限',
                },
                {
                    value: '5',
                    label: '仅本人数据权限',
                },
            ],
            // 菜单列表
            menuOptions: [],
            // 部门列表
            deptOptions: [],
            // 查询参数
            queryParams: {
                equipmentId: undefined,
                productionTime: '',
                supplierId: '',
            },
            maForm: {
                purchaseTime: '',
                arrivalTime: '',
                purchaser: '',
                remark: '',
                purchaseNumber: '',
            },
            // 表单参数
            form: {},
            defaultProps: {
                children: 'children',
                label: 'label',
            },
            // 表单校验
            rules: {
                purchaseNumber: [
                    {
                        required: false,
                        message: '请输入线下采购单编号',
                        trigger: 'blur',
                    },
                ],
                purchaseTime: [
                    {
                        required: true,
                        message: '采购日期不能为空',
                        trigger: 'blur',
                    },
                ],
                arrivalTime: [
                    {
                        required: false,
                        message: '到货日期不能为空',
                        trigger: 'blur',
                    },
                ],
                // purchaser: [
                //   { required: true, message: "采购员不能为空", trigger: "blur" }
                // ]
            },
            deviceTypeTreeProps: {
                children: 'children',
                label: 'typeName',
                // multiple: false,
                value: 'typeId',
                multiple: true,
            },
            deviceType: [],
            propsKey: 1000,
            currentIndex: 0,
            dialogUpload: false,
            // 往来单位数据
            unitList: [],
            // 工程数据
            projectList: [],
            repairParams: {
                unitId: '',
                projectId: '',
                agreementCode: '',
            }
        }
    },
    computed: {
        pickerOptions() {
            return {
                disabledDate(time) {
                    const currentDate = new Date()
                    currentDate.setHours(0, 0, 0, 0)
                    return time.getTime() < currentDate.getTime()
                },
            }
        },
    },
    created() {

        this.getUnitList()
        this.GetProData()

        this.getUserList()
        this.equipmentType()
    },
    methods: {
        //获取结算单位下的结算工程
        unitChange(val){
            console.log("yyyyyyyyyyyyyyyyy",val)
            this.repairParams.projectId = null;
            this.GetProData()
        }, 
        //获取结算工程下的结算单位
        proChange(val){
            this.GetAgreementInfoById()

        }, 

        getUnitList() {
            getUnitList().then((response) => {
                this.unitList = response.data
            })
        },
        async GetProData() {
            const params = {
                unitId: this.repairParams.unitId,
            }
            const res = await getProjectListByUnitIds(params)
            this.projectList = res.data;
        },

        async GetAgreementInfoById() {
            console.log("zzzzzzzzzzz",this.repairParams.unitId,this.repairParams.projectId)
            if (this.repairParams.unitId && this.repairParams.projectId) {
                const params = {
                unitId: this.repairParams.unitId,
                projectId: this.repairParams.projectId,
                }
                const res = await getAgreementInfoById(params)
                if(res.data.agreementCode == null || res.data.agreementCode == '' || res.data.agreementCode == undefined){
                    this.$message({
                        message: '暂无协议',
                        type: 'error',
                    })
                }else{
                    this.repairParams.agreementId = res.data.agreementId
                    this.repairParams.agreementCode = res.data.agreementCode
                }
                } 
        },




        /** 查询用户列表--采购员 */
        getUserList() {
            getUserByRoleList({ roleIds: [152] }).then((response) => {
                this.userList = response.data
            })
        },
        /** 机具类型 */
        equipmentType() {
            equipmentTypeTree().then((response) => {
                this.equipmentTypeList = response.data
                this.equipmentTypeList.forEach((item, index) => {
                    if (item.children && item.children.length > 0) {
                        item.children.forEach((item2, index2) => {
                            if (item2.children && item2.children.length > 0) {
                                item2.children.forEach((item3) => {
                                    if (item3.children && item3.children.length > 0) {
                                        item3.children.forEach((item4) => {
                                            item4.machineTypeName = item3.typeName
                                            item4.specificationType = item4.typeName
                                            this.$set(item4, 'partNum', 1)
                                        })
                                    }
                                })
                            }
                        })
                    }
                })

                let selectList = []
                this.equipmentList.forEach((e) => {
                    selectList.push(this.getParentsById(this.equipmentTypeList, e.typeId))
                })
                this.deviceType = selectList
            })
        },

        //添加机具类型
        select(row) {
            console.log(row)
            if (row.level == 4) {
                for (let i = 0; i < this.equipmentList.length; i++) {
                    if (this.equipmentList[i].typeId == row.typeId) {
                        this.equipmentList.splice(i, 1)
                        break
                    }
                }

                // 如果有厂家则代入
                if (this.queryParams.supplierId) {
                    this.$set(row, 'supplierId', this.queryParams.supplierId)
                } else {
                    this.$set(row, 'supplierId', '')
                }
                this.$set(row, 'createTime', null)
                this.$set(row, 'productionTime', '')
                // this.$set(row, 'supplierId', '')
                this.$set(row, 'purchasePrice', 0)
                this.$set(row, 'purchaseNum', 1)
                this.equipmentList.unshift(row)
            }
        },


        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
                    }
                }
            }
        },

        /** 查询右侧列表 */
        getList() {
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 取消按钮（数据权限）
        cancelDataScope() {
            this.openDataScope = false
            this.reset()
        },
        // 表单重置
        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')
        },

        /** 新增按钮操作 */
        handleSave() {
            if(this.repairParams.agreementId == null || this.repairParams.agreementId == '' || this.repairParams.agreementId == undefined){
                this.$message({
                    message: '请选择协议号',
                    type: 'error',
                })
                return 
            }
            if (this.equipmentList.length > 0) {

                this.equipmentList.forEach((item) => {
                    if(!item.partName || !item.partModelName){
                        this.$message({
                            message: '请填写配件名称和配件型号',
                            type: 'error',
                        })
                        
                    }
                })



                const params = this.equipmentList.map((item) => {
                    return {
                        agreementId: this.repairParams.agreementId,
                        typeId: item.typeId,
                        partNum: item.partNum,
                        partPrice: item.partPrice,
                        partName: item.partName,
                        partModelName: item.partModelName,
                        partAllCosts: item.partAllCosts,
                    }
                })
                
                this.$modal
                    .confirm('是否确认保存当前页面')
                    .then(function () {})
                    .then(() => {

                        this.loading = true
                        addRepairInputInfoApi(params).then((response) => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess('保存成功')
                                // 保存成功后清除页面数据
                                this.clearPageData();
                            }
                            this.loading = false
                        })
                    })
                    .catch(() => {})


            } else {
                this.$modal.msgError('请先添加维修信息')
            }
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            // console.log(row.id)
            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(() => {})
        },

        clearPageData() {
            // 清除设备列表
            this.equipmentList = [];
            // 重置协议号
            this.repairParams.agreementId = '';
            // 重置规格型号选择
            this.deviceType = [];
            this.repairParams.unitId = '';
            this.repairParams.projectId = '';
            this.repairParams.agreementCode = '';
        },



        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))
                            // 初始化配件相关字段
                            obj.partNum = obj.partNum || 1
                            obj.partPrice = obj.partPrice || 0
                            obj.partName = obj.partName || ''
                            obj.partModelName = obj.partModelName || ''
                            obj.partAllCosts = 0
                            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) {
                            // 确保数量至少为1
                            if (!j.partNum || j.partNum < 1) {
                                j.partNum = 1
                            }
                            // 确保有配件相关字段
                            j.partPrice = j.partPrice || 0
                            j.partName = j.partName || ''
                            j.partModelName = j.partModelName || ''
                            j.partAllCosts = (j.partNum * (j.partPrice || 0)).toFixed(2)
                            newArray_array.push(j)
                        }
                    })
                })
                this.equipmentList = newArray_array
            } else {
                this.equipmentList = []
            }
        },

        /** 模板下载 */
        downloadModel() {
            const params = {params:JSON.stringify(this.repairParams)}
            this.download(
                'material/purchaseCheckInfo/downLoadRepairModel',
                {...params,},
                `维修导入模板下载_${new Date().getTime()}.xlsx`,
            )

        },
        uploadModel() {
           this.dialogUpload = true 
        },
        beforeUpload(file) {
            const fileType = file.name.split('.').pop().toLowerCase();
            if (fileType!== 'xls' && fileType!== 'xlsx') {
                this.$message.error('只能上传 Excel 文件（.xls 或 .xlsx）');
                return false;
            }
            return true;
        },
        handleUploadSuccess(response, file, fileList) {
              if (response.code == 200) {
                this.$message.success('文件上传成功');
                 this.dialogUpload = false; // 上传成功后关闭弹窗
                 response.data.forEach((item) => {
                    const partNum = item.partNum && item.partNum >= 1 ? item.partNum : 1
                    const partPrice = item.partPrice || 0
                   // 创建新项数据
                    const newItem = {
                        machineTypeName: item.typeName,
                        specificationType: item.modelName,
                        typeId: item.typeId,
                        unitName: item.unitName,
                        partName: item.partName,
                        partModelName: item.partModelName,
                        partPrice: partPrice,
                        partNum: partNum,
                        partAllCosts: (partNum * partPrice).toFixed(2),
                    }
                    
                    // // 获取该项的层级路径
                    // const path = this.getParentsById(this.equipmentTypeList, item.typeId);
                    
                    // // 检查是否已存在相同typeId的项
                    let exists = false;
                    // let typeIdExistsInDeviceType = false;
                    
                    // // 检查设备列表中是否存在相同typeId
                    // for (let i = 0; i < this.equipmentList.length; i++) {
                    //     if (this.equipmentList[i].typeId == item.typeId) {
                    //         // 替换已存在的项
                    //         this.equipmentList[i] = newItem;
                    //         exists = true;
                    //         break;
                    //     }
                    // }
                    
                    // // 检查deviceType中是否已包含该typeId
                    // if (path && path.length > 0) {
                    //     const targetTypeId = path[path.length - 1]; // 最底层typeId
                    //     for (let i = 0; i < this.deviceType.length; i++) {
                    //         if (this.deviceType[i][this.deviceType[i].length - 1] === targetTypeId) {
                    //             typeIdExistsInDeviceType = true;
                    //             break;
                    //         }
                    //     }
                    // }
                    
                    // 如果不存在，则添加新项
                    // if (!exists) {
                        this.equipmentList.push(newItem);
                        // 获取新增项的层级路径并添加到deviceType
                        // if (path && !typeIdExistsInDeviceType) {
                            // this.deviceType.push(path);
                        // }
                    // } else if (path && !typeIdExistsInDeviceType) {
                    //     // 如果是替换已有项，但deviceType中没有对应的typeId，则添加
                    //     this.deviceType.push(path);
                    // }
                    
                    // 强制更新propsKey以触发级联选择器重新渲染
                    // this.propsKey++;
                 })

            } else {
                this.$message.error(response.msg);
            }
        },
        // 计算配件总价
        calculateTotalPrice(row) {
            // 确保数量至少为1
            if (!row.partNum || row.partNum < 1) {
                this.$set(row, 'partNum', 1)
            }
            // 确保单价为数字
            const price = parseFloat(row.partPrice) || 0
            const num = parseFloat(row.partNum) || 1
            // 计算总价，使用 $set 确保响应式更新
            const total = (price * num).toFixed(2)
            this.$set(row, 'partAllCosts', total)
        },
    },
    
}
</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>
