package cn.ibizlab.businesscentral.core.odoo_product.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.businesscentral.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.businesscentral.core.odoo_product.domain.Product_product;
import cn.ibizlab.businesscentral.core.odoo_product.filter.Product_productSearchContext;
import cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_productService;

import cn.ibizlab.businesscentral.util.helper.CachedBeanCopier;
import cn.ibizlab.businesscentral.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.businesscentral.core.util.helper.EBSServiceImpl;
import cn.ibizlab.businesscentral.core.odoo_product.mapper.Product_productMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;

import org.springframework.util.StringUtils;

/**
 * 实体[产品] 服务对象接口实现
 */
@Slf4j
@Service("Product_productServiceImpl")
public class Product_productServiceImpl extends EBSServiceImpl<Product_productMapper, Product_product> implements IProduct_productService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_analytic_lineService accountAnalyticLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_invoice_lineService accountInvoiceLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_invoice_reportService accountInvoiceReportService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_move_lineService accountMoveLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_event.service.IEvent_event_ticketService eventEventTicketService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_hr.service.IHr_expenseService hrExpenseService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_order_parts_lineService mroOrderPartsLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_task_parts_lineService mroTaskPartsLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_bom_lineService mrpBomLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_bomService mrpBomService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_productionService mrpProductionService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_product_produce_lineService mrpProductProduceLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_product_produceService mrpProductProduceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_unbuildService mrpUnbuildService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_workorderService mrpWorkorderService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_packagingService productPackagingService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_pricelist_itemService productPricelistItemService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_price_historyService productPriceHistoryService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_replenishService productReplenishService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_supplierinfoService productSupplierinfoService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_purchase.service.IPurchase_order_lineService purchaseOrderLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_purchase.service.IPurchase_reportService purchaseReportService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_purchase.service.IPurchase_requisition_lineService purchaseRequisitionLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_repair.service.IRepair_feeService repairFeeService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_repair.service.IRepair_lineService repairLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_repair.service.IRepair_orderService repairOrderService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_config_settingsService resConfigSettingsService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_sale.service.ISale_advance_payment_invService saleAdvancePaymentInvService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_sale.service.ISale_order_lineService saleOrderLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_sale.service.ISale_order_optionService saleOrderOptionService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_sale.service.ISale_order_template_lineService saleOrderTemplateLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_sale.service.ISale_order_template_optionService saleOrderTemplateOptionService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_sale.service.ISale_reportService saleReportService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_change_product_qtyService stockChangeProductQtyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_fixed_putaway_stratService stockFixedPutawayStratService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_inventory_lineService stockInventoryLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_inventoryService stockInventoryService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_move_lineService stockMoveLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_moveService stockMoveService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_production_lotService stockProductionLotService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_quantService stockQuantService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_return_picking_lineService stockReturnPickingLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_rules_reportService stockRulesReportService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_scrapService stockScrapService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_track_lineService stockTrackLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_warehouse_orderpointService stockWarehouseOrderpointService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_warn_insufficient_qty_repairService stockWarnInsufficientQtyRepairService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_warn_insufficient_qty_scrapService stockWarnInsufficientQtyScrapService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_warn_insufficient_qty_unbuildService stockWarnInsufficientQtyUnbuildService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_warn_insufficient_qtyService stockWarnInsufficientQtyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_templateService productTemplateService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

    public String getIrModel(){
        return "product.product" ;
    }

    private boolean messageinfo = false ;

    public void setMessageInfo(boolean messageinfo){
        this.messageinfo = messageinfo ;
    }

    @Override
    @Transactional
    public boolean create(Product_product et) {
        boolean mail_create_nosubscribe = et.get("mail_create_nosubscribe") != null;
        boolean mail_create_nolog = et.get("mail_create_nolog") != null;
        boolean mail_notrack = et.get("mail_notrack") != null;
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et)))
            return false;
        CachedBeanCopier.copy(get(et.getId()),et);

        if (messageinfo && !mail_create_nosubscribe) {
            cn.ibizlab.businesscentral.util.security.SpringContextHolder.getBean(cn.ibizlab.businesscentral.core.extensions.service.Mail_followersExService.class).add_default_followers(this,et);
        }

        if (messageinfo && !mail_create_nolog) {
            cn.ibizlab.businesscentral.util.security.SpringContextHolder.getBean(cn.ibizlab.businesscentral.core.extensions.service.Mail_tracking_valueExService.class).add_default_create_message(this,et);
        }

        if (messageinfo && !mail_notrack) {

        }

        return true;
    }

    @Override
    @Transactional
    public void createBatch(List<Product_product> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean update(Product_product et) {
        Product_product old = new Product_product() ;
        CachedBeanCopier.copy(get(et.getId()), old);
        boolean mail_notrack = et.get("mail_notrack") != null;
        fillParentData(et);
         if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("id",et.getId())))
            return false;
        CachedBeanCopier.copy(get(et.getId()),et);
        if (messageinfo && !mail_notrack) {
            cn.ibizlab.businesscentral.util.security.SpringContextHolder.getBean(cn.ibizlab.businesscentral.core.extensions.service.Mail_tracking_valueExService.class).message_track(this,old,et);
        }
        return true;
    }

    @Override
    @Transactional
    public void updateBatch(List<Product_product> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(Long key) {
        boolean result=removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<Long> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public Product_product get(Long key) {
        Product_product et = getById(key);
        if(et==null){
            et=new Product_product();
            et.setId(key);
        }
        else{
        }
        return et;
    }

    @Override
    public Product_product getDraft(Product_product et) {
        fillParentData(et);
        return et;
    }

    @Override
    public boolean checkKey(Product_product et) {
        return (!ObjectUtils.isEmpty(et.getId()))&&(!Objects.isNull(this.getById(et.getId())));
    }
    @Override
    @Transactional
    public boolean save(Product_product et) {
        if(!saveOrUpdate(et))
            return false;
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(Product_product et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? this.update(et) : this.create(et);
        }
    }

    @Override
    @Transactional
    public boolean saveBatch(Collection<Product_product> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
        return true;
    }

    @Override
    @Transactional
    public void saveBatch(List<Product_product> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
    }


	@Override
    public List<Product_product> selectByProductTmplId(Long id) {
        return baseMapper.selectByProductTmplId(id);
    }

    @Override
    public void removeByProductTmplId(Long id) {
        this.remove(new QueryWrapper<Product_product>().eq("product_tmpl_id",id));
    }

	@Override
    public List<Product_product> selectByCreateUid(Long id) {
        return baseMapper.selectByCreateUid(id);
    }

    @Override
    public void removeByCreateUid(Long id) {
        this.remove(new QueryWrapper<Product_product>().eq("create_uid",id));
    }

	@Override
    public List<Product_product> selectByWriteUid(Long id) {
        return baseMapper.selectByWriteUid(id);
    }

    @Override
    public void removeByWriteUid(Long id) {
        this.remove(new QueryWrapper<Product_product>().eq("write_uid",id));
    }


    /**
     * 查询集合 数据集
     */
    @Override
    public Page<Product_product> searchDefault(Product_productSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Product_product> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Product_product>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Product_product et){
        //实体关系[DER1N_PRODUCT_PRODUCT__PRODUCT_TEMPLATE__PRODUCT_TMPL_ID]
        if(!ObjectUtils.isEmpty(et.getProductTmplId())){
            cn.ibizlab.businesscentral.core.odoo_product.domain.Product_template odooProductTmpl=et.getOdooProductTmpl();
            if(ObjectUtils.isEmpty(odooProductTmpl)){
                cn.ibizlab.businesscentral.core.odoo_product.domain.Product_template majorEntity=productTemplateService.get(et.getProductTmplId());
                et.setOdooProductTmpl(majorEntity);
                odooProductTmpl=majorEntity;
            }
            et.setCurrencyId(odooProductTmpl.getCurrencyId());
            et.setTracking(odooProductTmpl.getTracking());
            et.setDescriptionPicking(odooProductTmpl.getDescriptionPicking());
            et.setPropertyStockAccountOutput(odooProductTmpl.getPropertyStockAccountOutput());
            et.setSaleOk(odooProductTmpl.getSaleOk());
            et.setWebsiteDescription(odooProductTmpl.getWebsiteDescription());
            et.setWebsiteMetaOgImg(odooProductTmpl.getWebsiteMetaOgImg());
            et.setCompanyId(odooProductTmpl.getCompanyId());
            et.setToWeight(odooProductTmpl.getToWeight());
            et.setDescription(odooProductTmpl.getDescription());
            et.setDescriptionPickingin(odooProductTmpl.getDescriptionPickingin());
            et.setListPrice(odooProductTmpl.getListPrice());
            et.setHideExpensePolicy(odooProductTmpl.getHideExpensePolicy());
            et.setDescriptionSale(odooProductTmpl.getDescriptionSale());
            et.setCostMethod(odooProductTmpl.getCostMethod());
            et.setSequence(odooProductTmpl.getSequence());
            et.setSaleLineWarnMsg(odooProductTmpl.getSaleLineWarnMsg());
            et.setWarehouseId(odooProductTmpl.getWarehouseId());
            et.setRental(odooProductTmpl.getRental());
            et.setPropertyAccountCreditorPriceDifference(odooProductTmpl.getPropertyAccountCreditorPriceDifference());
            et.setWeightUomName(odooProductTmpl.getWeightUomName());
            et.setCostCurrencyId(odooProductTmpl.getCostCurrencyId());
            et.setPropertyStockAccountInput(odooProductTmpl.getPropertyStockAccountInput());
            et.setName(odooProductTmpl.getName());
            et.setProduceDelay(odooProductTmpl.getProduceDelay());
            et.setIsSeoOptimized(odooProductTmpl.getIsSeoOptimized());
            et.setWebsiteUrl(odooProductTmpl.getWebsiteUrl());
            et.setRatingLastFeedback(odooProductTmpl.getRatingLastFeedback());
            et.setWebsiteSizeY(odooProductTmpl.getWebsiteSizeY());
            et.setEventOk(odooProductTmpl.getEventOk());
            et.setInventoryAvailability(odooProductTmpl.getInventoryAvailability());
            et.setPurchaseOk(odooProductTmpl.getPurchaseOk());
            et.setRatingLastValue(odooProductTmpl.getRatingLastValue());
            et.setWebsiteMetaTitle(odooProductTmpl.getWebsiteMetaTitle());
            et.setRatingLastImage(odooProductTmpl.getRatingLastImage());
            et.setDescriptionPurchase(odooProductTmpl.getDescriptionPurchase());
            et.setWebsiteId(odooProductTmpl.getWebsiteId());
            et.setCanBeExpensed(odooProductTmpl.getCanBeExpensed());
            et.setSaleLineWarn(odooProductTmpl.getSaleLineWarn());
            et.setWebsiteSizeX(odooProductTmpl.getWebsiteSizeX());
            et.setServiceToPurchase(odooProductTmpl.getServiceToPurchase());
            et.setWebsiteSequence(odooProductTmpl.getWebsiteSequence());
            et.setPropertyStockInventory(odooProductTmpl.getPropertyStockInventory());
            et.setLocationId(odooProductTmpl.getLocationId());
            et.setPropertyValuation(odooProductTmpl.getPropertyValuation());
            et.setIsPublished(odooProductTmpl.getIsPublished());
            et.setExpensePolicy(odooProductTmpl.getExpensePolicy());
            et.setWeightUomId(odooProductTmpl.getWeightUomId());
            et.setColor(odooProductTmpl.getColor());
            et.setPropertyStockProduction(odooProductTmpl.getPropertyStockProduction());
            et.setWebsitePublished(odooProductTmpl.getWebsitePublished());
            et.setWebsiteMetaKeywords(odooProductTmpl.getWebsiteMetaKeywords());
            et.setDescriptionPickingout(odooProductTmpl.getDescriptionPickingout());
            et.setPricelistId(odooProductTmpl.getPricelistId());
            et.setRatingCount(odooProductTmpl.getRatingCount());
            et.setWebsiteMetaDescription(odooProductTmpl.getWebsiteMetaDescription());
            et.setValuation(odooProductTmpl.getValuation());
            et.setInvoicePolicy(odooProductTmpl.getInvoicePolicy());
            et.setPurchaseLineWarnMsg(odooProductTmpl.getPurchaseLineWarnMsg());
            et.setPropertyAccountIncomeId(odooProductTmpl.getPropertyAccountIncomeId());
            et.setPropertyCostMethod(odooProductTmpl.getPropertyCostMethod());
            et.setCategId(odooProductTmpl.getCategId());
            et.setUomId(odooProductTmpl.getUomId());
            et.setProductVariantId(odooProductTmpl.getProductVariantId());
            et.setType(odooProductTmpl.getType());
            et.setPurchaseMethod(odooProductTmpl.getPurchaseMethod());
            et.setServiceType(odooProductTmpl.getServiceType());
            et.setUomName(odooProductTmpl.getUomName());
            et.setAvailableThreshold(odooProductTmpl.getAvailableThreshold());
            et.setPurchaseLineWarn(odooProductTmpl.getPurchaseLineWarn());
            et.setProductVariantCount(odooProductTmpl.getProductVariantCount());
            et.setPosCategId(odooProductTmpl.getPosCategId());
            et.setCustomMessage(odooProductTmpl.getCustomMessage());
            et.setPropertyAccountExpenseId(odooProductTmpl.getPropertyAccountExpenseId());
            et.setSaleDelay(odooProductTmpl.getSaleDelay());
            et.setUomPoId(odooProductTmpl.getUomPoId());
            et.setAvailableInPos(odooProductTmpl.getAvailableInPos());
        }
        //实体关系[DER1N_PRODUCT_PRODUCT__RES_USERS__CREATE_UID]
        if(!ObjectUtils.isEmpty(et.getCreateUid())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users odooCreate=et.getOdooCreate();
            if(ObjectUtils.isEmpty(odooCreate)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users majorEntity=resUsersService.get(et.getCreateUid());
                et.setOdooCreate(majorEntity);
                odooCreate=majorEntity;
            }
            et.setCreateUidText(odooCreate.getName());
        }
        //实体关系[DER1N_PRODUCT_PRODUCT__RES_USERS__WRITE_UID]
        if(!ObjectUtils.isEmpty(et.getWriteUid())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users odooWrite=et.getOdooWrite();
            if(ObjectUtils.isEmpty(odooWrite)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users majorEntity=resUsersService.get(et.getWriteUid());
                et.setOdooWrite(majorEntity);
                odooWrite=majorEntity;
            }
            et.setWriteUidText(odooWrite.getName());
        }
    }




    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<Product_product> getProductProductByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<Product_product> getProductProductByEntities(List<Product_product> entities) {
        List ids =new ArrayList();
        for(Product_product entity : entities){
            Serializable id=entity.getId();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0)
           return this.listByIds(ids);
        else
           return entities;
    }



}



