import Store from '@/store'
import modal from '@/plugins/modal'

function transformItem(item) {
    if (item.impa) {
        item.materialWarehouseImpa = item.impa
    }
    if (item.impaCode) {
        item.materialWarehouseImpaCode = item.impaCode
    }
    if (item.warehouseName) {
        item.materialWarehouseImpaDescription = item.warehouseName
    }
    if (item.warehouseSpecifications) {
        item.materialWarehouseImpaSpecifications = item.warehouseSpecifications
    }
    if (item.unit) {
        item.materialWarehouseImpaUnit = item.unit
    }
}

export function addApplyPurchaseDetails(item, showMessage = true) {

    transformItem(item)

    //// console.log(item.materialWarehouseImpa)
    //// console.log(Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa])
    if (Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa] == undefined) {
        item.applyPurchaseNum = 1
        Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa] = item
    } else {
        Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa].applyPurchaseNum++
    }
    Store.commit('data/SET_APPLYPURCHASEDETAILS', JSON.parse(JSON.stringify(Store.state.data.applyPurchaseDetails)))
    if (showMessage) {
        modal.msgSuccess('添加成功')
    }
}

export function updateApplyPurchaseDetails(item, showMessage = true) {
    transformItem(item)

    //// console.log(item.materialWarehouseImpa)
    //// console.log(Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa])
    // if (Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa] == undefined) {
    //     item.applyPurchaseNum = 1
    //     Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa] = item
    // } else {
    //     Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa].applyPurchaseNum = parseInt(item.applyPurchaseNum)
    // }
    Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa] = item
    Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa].applyPurchaseNum = parseInt(item.applyPurchaseNum) > 0 ? parseInt(item.applyPurchaseNum) : 1


    Store.commit('data/SET_APPLYPURCHASEDETAILS', JSON.parse(JSON.stringify(Store.state.data.applyPurchaseDetails)))
    if (showMessage) {
        modal.msgSuccess('修改成功')
    }
}

export function clearApplyPurchaseDetails(showMessage = true) {
    Store.commit('data/SET_APPLYPURCHASEDETAILS', {})
    Store.state.data.applyPurchaseDetailsCustomList = []
    if (showMessage) {
        modal.msgSuccess('已清空')
    }
}

export function removeApplyPurchaseDetails(item, showMessage = true) {
    delete Store.state.data.applyPurchaseDetails[item.materialWarehouseImpa]
    Store.commit('data/SET_APPLYPURCHASEDETAILS', JSON.parse(JSON.stringify(Store.state.data.applyPurchaseDetails)))
    if (showMessage) {
        modal.msgSuccess('已删除')
    }
}
