import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import fetchHelper from "../../../utils/fetchHelper"
import { _BOOLEAN_MIXED_GRID_OPTIONS, TreeDataModule } from "ag-grid-enterprise"
import JobPositionDetailRecord from "~/components/partners/JobPositionDetailRecord.vue"

const handleOrderFunc = async (event: any, authToken: any = null, body: any, lines: any[], res_data: any) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)

  let newObjValue = {}
  if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  /*if(body.invoiceRuleId) {
    newObjValue = {...newObjValue, 
      InvoiceRule: {
        id: body.invoiceRuleId
      }
    }
  }
  if(body.freightCostRuleId) {
    newObjValue = {...newObjValue, 
      FreightCostRule: {
        id: body.freightCostRuleId
      }
    }
  }*/
  if(res_data.partner?.id) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: res_data.partner.id,
        tableName: 'C_BPartner'
      },
      Bill_BPartner_ID: {
        id: res_data.partner.id,
        tableName: 'C_BPartner'
      }
    }
  }
  if(res_data.partner_location_ship?.id) {
    newObjValue = {...newObjValue, 
      C_BPartner_Location_ID: {
        id: res_data.partner_location_ship.id,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(res_data.partner_location_bill?.id) {
    newObjValue = {...newObjValue, 
      Bill_Location_ID: {
        id: res_data.partner_location_bill.id,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  /*if(body.cashLineId) {
    newObjValue = {...newObjValue, 
      C_CashLine_ID: {
        id: body.cashLineId,
        tableName: 'C_CashLine'
      }
    }
  }
  if(body.projectId) {
    newObjValue = {...newObjValue, 
      C_Project_ID: {
        id: body.projectId,
        tableName: 'C_Project'
      }
    }
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, 
      C_Campaign_ID: {
        id: body.campaignId,
        tableName: 'C_Campaign'
      }
    }
  }
  if(body.freightCategoryId) {
    newObjValue = {...newObjValue, 
      M_FreightCategory_ID: {
        id: body.freightCategoryId,
        tableName: 'M_FreightCategory'
      }
    }
  }*/
  if(res_data.user_Ship?.id) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: res_data.user_Ship.id,
        tableName: 'AD_User'
      }
    }
  }
  if(res_data.user_Bill?.id) {
    newObjValue = {...newObjValue, 
      Bill_User_ID: {
        id: res_data.user_Bill.id,
        tableName: 'AD_User'
      }
    }
  }
  /*if(body.conversionTypeId) {
    newObjValue = {...newObjValue, 
      C_ConversionType_ID: {
        id: body.conversionTypeId,
        tableName: 'C_ConversionType'
      }
    }
  }*/
  if(lines.length >= 1) {
    newObjValue = {...newObjValue, 
      C_OrderLine: lines.map((item: any) => {
        let newObjEntry = {}
        if(item.productId) {
          newObjEntry = {...newObjEntry, 
            M_Product_ID: {
              id: item.productId
            }
          }
        }
        if(item.uomId) {
          newObjEntry = {...newObjEntry, 
            C_UOM_ID: {
              id: item.uomId
            }
          }
        }
        if(item.taxId) {
          newObjEntry = {...newObjEntry, 
            C_Tax_ID: {
              id: item.taxId
            }
          }
        }
        if(body.warehouseId) {
          newObjEntry = {...newObjEntry, 
            M_Warehouse_ID: {
              id: body.warehouseId
            }
          }
        }
        if(body.currencyId) {
          newObjEntry = {...newObjEntry, 
            C_Currency_ID: {
              id: body.currencyId
            }
          }
        }
        if(res_data.partner.id) {
          newObjEntry = {...newObjEntry, 
            C_BPartner_ID: {
              id: res_data.partner.id
            }
          }
        }
        if(res_data.partner_location_ship?.id) {
          newObjEntry = {...newObjEntry, 
            C_BPartner_Location_ID: {
              id: res_data.partner_location_ship.id
            }
          }
        }
        if(item.attributeSetInstanceId) {
          newObjEntry = {...newObjEntry, 
            M_AttributeSetInstance_ID: {
              id: item.attributeSetInstanceId
            }
          }
        }
        if(item.chargeId) {
          newObjEntry = {...newObjEntry, 
            C_Charge_ID: {
              id: item.chargeId
            }
          }
        }
        if(item.projectId) {
          newObjEntry = {...newObjEntry, 
            C_Project_ID: {
              id: item.projectId
            }
          }
        }
        if(item.campaignId) {
          newObjEntry = {...newObjEntry, 
            C_Campaign_ID: {
              id: item.campaignId
            }
          }
        }

        return {
          line: item.line,
          isActive: item.isActive,
          //dateOrdered: body.dateOrdered,
          //datePromised: body.datePromised,
          qtyOrdered: item?.qtyOrdered || item.qtyEntered,
          qtyReserved: item?.qtyReserved || 0,
          qtyDelivered: item?.qtyDelivered || 0,
          qtyInvoiced: item?.qtyInvoiced || 0,
          qtyLostSales: item?.qtyLostSales || 0,
          qtyEntered: item.qtyEntered,
          priceActual: item.priceActual,
          priceEntered: item.priceEntered,
          priceList: item.priceList,
          priceLimit: item.priceList,
          discount: item.discount,
          lineNetAmt: item.lineNetAmt,
          ...newObjEntry
        }
      })
    }
  }
  if(body.orderSourceId) {
    newObjValue = {...newObjValue, 
      C_OrderSource_ID: {
        id: body.orderSourceId,
        tableName: 'C_OrderSource'
      }
    }
  }
  if(body.deliveryViaRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryViaRule: {
        id: body.deliveryViaRuleId
      }
    }
  }
  if(body.shipperId) {
    newObjValue = {...newObjValue, 
      M_Shipper_ID: {
        id: body.shipperId,
        tableName: 'M_Shipper'
      }
    }
  }

  const payload: any = {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: true,
    isApproved: false,
    isCreditApproved: false,
    isDelivered: false,
    isInvoiced: false,
    isPrinted: false,
    isTransferred: false,
    isSOTrx: true,
    isDiscountPrinted: false,
    isTaxIncluded: false,
    isSelected: false,
    sendEMail: false,
    isSelfService: false,
    isDropShip: false,
    isPayScheduleValid: false,
    isPriviledgedRate: false,
    ...newObjValue,
    C_DocTypeTarget_ID: {
      id: body.docTypeTargetId,
      tableName: 'C_DocTypeTarget'
    },
    DocStatus: {
      id: 'DR'
    },
    M_PriceList_ID: {
      id: body.priceListId,
      tableName: 'M_PriceList'
    },
    M_Warehouse_ID: {
      id: body.warehouseId,
      tableName: 'M_Warehouse'
    },
    PriorityRule: {
      id: '5'
    },
    DeliveryRule: {
      id: 'O'
    },
    /*DeliveryViaRule: {
      id: 'D'
    },*/
    C_PaymentTerm_ID: {
      identifier: 'Immediate',
      tableName: 'C_PaymentTerm'
    },
    PaymentRule: {
      id: 'D'
    },
    SalesRep_ID: {
      id: body.userId,
      tableName: 'AD_User'
    },
    tableName: 'C_Order'
  }
  const res: any = await fetchHelper(event, 'models/c_order', 'POST', token, payload)
  if(res?.id) {
    data['order'] = res

    await fetchHelper(event, `models/c_order/${res.id}`, 'PUT', token, {
      'doc-action': 'CO'
    })
  } else {
    data['order'] = payload
  }

  return data
}

const handleUserFunc = async (event: any, authToken: any = null, resData: any = null, typeUser: string = 'Ship') => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  
  const isBillTo = (typeUser === 'Ship' ? true : false)
  const isShipTo = (typeUser === 'Bill' ? true : false)
  
  if(resData.id && !resData.userId) {
    const res: any = await fetchHelper(event, 'models/ad_user', 'POST', token, {
      AD_Org_ID: {
        id: resData.AD_Org_ID.id,
        tableName: 'AD_Org'
      },
      isActive: true,
      name: `${typeUser}_${resData.Name}`,
      eMail: resData.EMail,
      isFullBPAccess: false,
      isInPayroll: false,
      isSalesLead: false,
      isLocked: false,
      isNoPasswordReset: false,
      isExpired: false,
      isAddMailTextAutomatically: false,
      isNoExpire: false,
      isSupportUser: false,
      isShipTo: isShipTo,
      isBillTo: isBillTo,
      isVendorLead: false,
      phone: resData.Phone,
      C_BPartner_ID: {
        id: resData.id,
        tableName: 'C_BPartner'
      },
      tableName: 'AD_User'
    })
    if(res) {
      data['user_'+typeUser] = res
    }
  } else {
    if(resData.userId) {
      data['user_'+typeUser] = {
        id: resData.userId
      }
    }
  }

  return data
}

const handlePartnerLocationFunc = async (event: any, authToken: any = null, body: any = null, partner: any = null, typeLocation: string = 'ship') => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)

  const isBillTo = (typeLocation === 'ship' ? true : false)
  const isShipTo = (typeLocation === 'bill' ? true : false)
  
  if(partner.id && body.id) {
    const payload: any = {
      AD_Org_ID: {
        id: body.AD_Org_ID.id,
        tableName: 'AD_Org'
      },
      isActive: body.IsActive,
      name: partner.Name,
      phone: body.phone,
      //phone2: partner.phone,
      //fax: partner.fax,
      //ISDN: partner.ISDN,
      isBillTo: isBillTo,
      isShipTo: isShipTo,
      isPayFrom: false,
      isRemitTo: false,
      isPreserveCustomName: false,
      C_BPartner_ID: {
        id: partner.id,
        tableName: 'C_BPartner'
      },
      C_Location_ID: {
        id: body.id,
        tableName: 'C_Location'
      },
      tableName: 'C_BPartner_Location'
    }
    const res: any = await fetchHelper(event, 'models/c_bpartner_location'+(body.partnerLocationId ? '/'+body.partnerLocationId : ''), (body.partnerLocationId ? 'PUT' : 'POST'), token, payload)
    if(res) {
      data['bpartner_'+typeLocation] = res
    } else {
      data['bpartner_'+typeLocation] = payload
    }
  }
  
  return data
}

const handleLocationFunc = async (event: any, authToken: any = null, body: any = null, partner: any = null, type: string = 'ship') => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)

  let newObjValue = {}
  if(body.countryId) {
    newObjValue = {...newObjValue, 
      C_Country_ID: {
        id: body.countryId,
        tableName: 'C_Country'
      }
    }
  }
  if(body.regionId) {
    newObjValue = {...newObjValue, 
      C_Region_ID: {
        id: body.regionId,
        tableName: 'C_Region'
      }
    }
  }
  if(!body.id) {
    newObjValue = {
      ...newObjValue, 
      isValid: body.isValid
    }
  }

  const payload: any = {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    address1: body.address1,
    address2: body.address2,
    address3: body.address3,
    address4: body.address4,
    city: body.city,
    postal: body.postal,
    regionName: body.regionName,
    ...newObjValue,
    tableName: 'C_Location'
  }
  const res: any = await fetchHelper(event, 'models/c_location'+(body.id ? '/'+body.id : ''), (body.id ? 'PUT' : 'POST'), token, payload)
  if(res) {
    data['location_'+type] = res

    const resBody = {
      ...res,
      partnerLocationId: body.partnerLocationId,
      phone: body.phone
    }
    data['partner_location_'+type] = await handlePartnerLocationFunc(event, token, resBody, partner, type)
  } else {
    data['location_'+type] = payload
  }

  return data
}

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  let newObjValue = {}
  if(body.partner.deliveryRuleId) {
    newObjValue = {...newObjValue, DeliveryRule: {
      id: body.partner.deliveryRuleId
    }}
  }
  if(body.partner.deliveryViaRuleId) {
    newObjValue = {...newObjValue, DeliveryViaRule: {
      id: body.partner.deliveryViaRuleId
    }}
  }
  if(body.partner.invoiceScheduleId) {
    newObjValue = {...newObjValue, C_InvoiceSchedule_ID: {
      id: body.partner.invoiceScheduleId,
      tableName: 'C_InvoiceSchedule'
    }}
  }
  if(body.partner.greetingId) {
    newObjValue = {...newObjValue, C_Greeting_ID: {
      id: body.partner.greetingId,
      tableName: 'C_Greeting'
    }}
  }
  if(body.partner.printFormatId) {
    newObjValue = {...newObjValue, Invoice_PrintFormat_ID: {
      id: body.partner.printFormatId,
      tableName: 'AD_Printformat'
    }}
  }
  if(body.partner.salesRepId) {
    newObjValue = {...newObjValue, SalesRep_ID: {
      id: body.partner.salesRepId
    }}
  }
  if(body.partner.invoiceRuleId) {
    newObjValue = {...newObjValue, InvoiceRule: {
      id: body.partner.invoiceRuleId
    }}
  }
  if(body.partner.paymentRuleId) {
    newObjValue = {...newObjValue, PaymentRule: {
      id: body.partner.paymentRuleId
    }}
  }
  if(body.partner.paymentRulePOId) {
    newObjValue = {...newObjValue, PaymentRulePO: {
      id: body.partner.paymentRulePOId
    }}
  }
  if(body.partner.soCreditStatusId) {
    newObjValue = {...newObjValue, SOCreditStatus: {
      id: body.partner.soCreditStatusId
    }}
  }
  if(body.partner.partnerGroupId) {
    newObjValue = {...newObjValue, C_BP_Group_ID: {
      id: body.partner.partnerGroupId,
      tableName: 'C_BP_Group'
    }}
  }
  if(body.partner.priceListId) {
    newObjValue = {...newObjValue, M_PriceList_ID: {
      id: body.partner.priceListId,
      tableName: 'M_PriceList'
    }}
  }
  if(body.partner.poPriceListId) {
    newObjValue = {...newObjValue, PO_PriceList_ID: {
      id: body.partner.poPriceListId,
      tableName: 'M_PriceList'
    }}
  }
  if(body.partner.discountSchemaId) {
    newObjValue = {...newObjValue, M_DiscountSchema_ID: {
      id: body.partner.discountSchemaId,
    }}
  }
  if(body.partner.poDiscountSchemaId) {
    newObjValue = {...newObjValue, PO_DiscountSchema_ID: {
      id: body.partner.poDiscountSchemaId,
    }}
  }
  if(body.partner.paymentTermId) {
    newObjValue = {...newObjValue, C_PaymentTerm_ID: {
      id: body.partner.paymentTermId,
      tableName: 'C_PaymentTerm'
    }}
  }
  if(body.partner.poPaymentTermId) {
    newObjValue = {...newObjValue, PO_PaymentTerm_ID: {
      id: body.partner.poPaymentTermId,
      tableName: 'C_PaymentTerm'
    }}
  }
  if(body.partner.dunningId) {
    newObjValue = {...newObjValue, C_Dunning_ID: {
      id: body.partner.dunningId,
      tableName: 'C_Dunning'
    }}
  }
  if(body.partner.EMail) {
    newObjValue = {...newObjValue, EMail: body.partner.EMail}
  }
  if(new Boolean(body.partner.isFulfillmentCustomer)) {
    newObjValue = {...newObjValue, isFulfillmentCustomer: body.partner.isFulfillmentCustomer}
  }
  if(body.partner.fulfillmentOrderBaseprice) {
    newObjValue = {...newObjValue, fulfillment_order_baseprice: body.partner.fulfillmentOrderBaseprice}
  }
  if(body.partner.fulfillmentOrderPickprice) {
    newObjValue = {...newObjValue, fulfillment_order_pickprice: body.partner.fulfillmentOrderPickprice}
  }
  if(body.partner.fulfillmentOrderQtyPickfree) {
    newObjValue = {...newObjValue, fulfillment_order_qty_pickfree: body.partner.fulfillmentOrderQtyPickfree}
  }
  if(body.partner.fulfillmentOrderBaseprice2) {
    newObjValue = {...newObjValue, fulfillment_order_baseprice_2: body.partner.fulfillmentOrderBaseprice2}
  }
  if(body.partner.fulfillmentOrderBaseprice3) {
    newObjValue = {...newObjValue, fulfillment_order_baseprice_3: body.partner.fulfillmentOrderBaseprice3}
  }
  if(body.partner.fulfillmentOrderReturnBaseprice) {
    newObjValue = {...newObjValue, fulfillment_order_return_baseprice: body.partner.fulfillmentOrderReturnBaseprice}
  }
  if(body.partner.fulfillmentOrderReturnPickprice) {
    newObjValue = {...newObjValue, fulfillment_order_return_pickprice: body.partner.fulfillmentOrderReturnPickprice}
  }

  const payload: any = {
    AD_Org_ID: {
      id: body.partner.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.partner.isActive,
    name: body.partner.name,
    name2: body.partner.name2,
    value: body.partner.value,
    description: body.partner.description,
    salesVolume: body.partner.salesVolume,
    numberEmployees: body.partner.numberEmployees,
    isSummary: body.partner.isSummary,
    isVendor: body.partner.isVendor,
    isCustomer: body.partner.isCustomer,
    isProspect: body.partner.isProspect,
    SO_CreditLimit: body.partner.soCreditLimit,
    SO_CreditUsed: body.partner.soCreditUsed,
    acqusitionCost: body.partner.acqusitionCost,
    potentialLifeTimeValue: body.partner.potentialLifeTimeValue,
    actualLifeTimeValue: body.partner.actualLifeTimeValue,
    shareOfCustomer: body.partner.shareOfCustomer,
    isEmployee: body.partner.isEmployee,
    isSalesRep: body.partner.isSalesRep,
    isOneTime: body.partner.isOneTime,
    isTaxExempt: body.partner.isTaxExempt,
    isDiscountPrinted: body.partner.isDiscountPrinted,
    sendEMail: body.partner.sendEMail,
    totalOpenBalance: body.partner.totalOpenBalance,
    isPOTaxExempt: body.partner.isPOTaxExempt,
    isManufacturer: body.partner.isManufacturer,
    is1099Vendor: body.partner.is1099Vendor,
    FirstSale: body.partner.firstSale,
    POReference: body.partner.poReference,
    referenceNo: body.partner.referenceNo,
    rating: body.partner.rating,
    taxID: body.partner.taxID,
    URL: body.partner.URL,
    NAICS: body.partner.NAICS,
    DUNS: body.partner.DUNS,
    documentCopies: body.partner.documentCopies,
    SO_Description: body.partner.soDescription,
    flatDiscount: body.partner.flatDiscount,
    shelfLifeMinPct: body.partner.shelfLifeMinPct,
    dunningGrace: body.partner.dunningGrace,
    ...newObjValue,
    AD_Language: {
      id: body.partner.languageId,
      tableName: 'AD_Language'
    },
    tableName: 'C_Bpartner'
  }
  const res: any = await fetchHelper(event, 'models/c_bpartner'+(body.partner.id ? '/'+body.partner.id : ''), (body.partner.id ? 'PUT' : 'POST'), token, payload)
  if(res) {
    data['partner'] = res
    data['status'] = 200
    data['message'] = ''

    const locShip = await handleLocationFunc(event, token, body.ship, res, 'ship')
    const locBill = await handleLocationFunc(event, token, body.bill, res, 'bill')
    const userShip = await handleUserFunc(event, token, {...res, userId: body.ship.userId}, 'Ship')
    const userBill = await handleUserFunc(event, token, {...res, userId: body.bill.userId}, 'Bill')
    data = {...data, ...locShip, ...locBill, ...userShip, ...userBill}

    const order = await handleOrderFunc(event, token, body.order, body.lines, data)
    data = {...data, ...order}
    /*try {
      await laravelHelper(event, '/partners/customers/sync-idempiere', 'POST', null)
    } catch(err: any) {}*/
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch(error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})