package cn.ibizlab.businesscentral.core.odoo_base.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_base.domain.Res_currency;
import cn.ibizlab.businesscentral.core.odoo_base.filter.Res_currencySearchContext;
import cn.ibizlab.businesscentral.core.odoo_base.service.IRes_currencyService;

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_base.mapper.Res_currencyMapper;
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("Res_currencyServiceImpl")
public class Res_currencyServiceImpl extends EBSServiceImpl<Res_currencyMapper, Res_currency> implements IRes_currencyService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_abstract_paymentService accountAbstractPaymentService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_account_templateService accountAccountTemplateService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_accountService accountAccountService;
    @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_bank_statement_lineService accountBankStatementLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_chart_templateService accountChartTemplateService;
    @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_invoice_taxService accountInvoiceTaxService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_invoiceService accountInvoiceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_journalService accountJournalService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_move_lineService accountMoveLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_moveService accountMoveService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_partial_reconcileService accountPartialReconcileService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_paymentService accountPaymentService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_register_paymentsService accountRegisterPaymentsService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base_import.service.IBase_import_tests_models_complexService baseImportTestsModelsComplexService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base_import.service.IBase_import_tests_models_floatService baseImportTestsModelsFloatService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_hr.service.IHr_expense_sheet_register_payment_wizardService hrExpenseSheetRegisterPaymentWizardService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_hr.service.IHr_expense_sheetService hrExpenseSheetService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_hr.service.IHr_expenseService hrExpenseService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_lunch.service.ILunch_orderService lunchOrderService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_payment.service.IPayment_transactionService paymentTransactionService;
    @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_pricelistService productPricelistService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_supplierinfoService productSupplierinfoService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_purchase.service.IPurchase_bill_unionService purchaseBillUnionService;
    @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_orderService purchaseOrderService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_purchase.service.IPurchase_reportService purchaseReportService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_purchase.service.IPurchase_requisitionService purchaseRequisitionService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_companyService resCompanyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_countryService resCountryService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_currency_rateService resCurrencyRateService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_partner_bankService resPartnerBankService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_sale.service.ISale_order_lineService saleOrderLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

    public String getIrModel(){
        return "res.currency" ;
    }

    private boolean messageinfo = false ;

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

    @Override
    @Transactional
    public boolean create(Res_currency 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_messageExService.class).add_default_create_message(this,et);
        }

        if (messageinfo && !mail_notrack) {

        }
        return true;
    }

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

    @Override
    @Transactional
    public boolean update(Res_currency et) {
        Res_currency old = new Res_currency() ;
        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<Res_currency> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(Long key) {
        accountAbstractPaymentService.resetByCurrencyId(key);
        accountAccountTemplateService.resetByCurrencyId(key);
        accountAccountService.resetByCurrencyId(key);
        accountAnalyticLineService.resetByCurrencyId(key);
        accountBankStatementLineService.resetByCurrencyId(key);
        accountChartTemplateService.resetByCurrencyId(key);
        accountInvoiceLineService.resetByCurrencyId(key);
        accountInvoiceReportService.resetByCurrencyId(key);
        accountInvoiceTaxService.resetByCurrencyId(key);
        accountInvoiceService.resetByCurrencyId(key);
        accountJournalService.resetByCurrencyId(key);
        accountMoveLineService.resetByCompanyCurrencyId(key);
        accountMoveLineService.resetByCurrencyId(key);
        accountMoveService.resetByCurrencyId(key);
        accountPartialReconcileService.resetByCurrencyId(key);
        accountPaymentService.resetByCurrencyId(key);
        accountRegisterPaymentsService.resetByCurrencyId(key);
        baseImportTestsModelsComplexService.resetByCurrencyId(key);
        baseImportTestsModelsFloatService.resetByCurrencyId(key);
        hrExpenseSheetRegisterPaymentWizardService.resetByCurrencyId(key);
        hrExpenseSheetService.resetByCurrencyId(key);
        hrExpenseService.resetByCompanyCurrencyId(key);
        hrExpenseService.resetByCurrencyId(key);
        lunchOrderService.resetByCurrencyId(key);
        paymentTransactionService.resetByCurrencyId(key);
        productPricelistItemService.resetByCurrencyId(key);
        productPricelistService.resetByCurrencyId(key);
        productSupplierinfoService.resetByCurrencyId(key);
        purchaseBillUnionService.resetByCurrencyId(key);
        purchaseOrderLineService.resetByCurrencyId(key);
        purchaseOrderService.resetByCurrencyId(key);
        purchaseReportService.resetByCurrencyId(key);
        resCompanyService.resetByCurrencyId(key);
        resCountryService.resetByCurrencyId(key);
        resCurrencyRateService.resetByCurrencyId(key);
        resPartnerBankService.resetByCurrencyId(key);
        saleOrderLineService.resetByCurrencyId(key);
        boolean result=removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<Long> idList) {
        accountAbstractPaymentService.resetByCurrencyId(idList);
        accountAccountTemplateService.resetByCurrencyId(idList);
        accountAccountService.resetByCurrencyId(idList);
        accountAnalyticLineService.resetByCurrencyId(idList);
        accountBankStatementLineService.resetByCurrencyId(idList);
        accountChartTemplateService.resetByCurrencyId(idList);
        accountInvoiceLineService.resetByCurrencyId(idList);
        accountInvoiceReportService.resetByCurrencyId(idList);
        accountInvoiceTaxService.resetByCurrencyId(idList);
        accountInvoiceService.resetByCurrencyId(idList);
        accountJournalService.resetByCurrencyId(idList);
        accountMoveLineService.resetByCompanyCurrencyId(idList);
        accountMoveLineService.resetByCurrencyId(idList);
        accountMoveService.resetByCurrencyId(idList);
        accountPartialReconcileService.resetByCurrencyId(idList);
        accountPaymentService.resetByCurrencyId(idList);
        accountRegisterPaymentsService.resetByCurrencyId(idList);
        baseImportTestsModelsComplexService.resetByCurrencyId(idList);
        baseImportTestsModelsFloatService.resetByCurrencyId(idList);
        hrExpenseSheetRegisterPaymentWizardService.resetByCurrencyId(idList);
        hrExpenseSheetService.resetByCurrencyId(idList);
        hrExpenseService.resetByCompanyCurrencyId(idList);
        hrExpenseService.resetByCurrencyId(idList);
        lunchOrderService.resetByCurrencyId(idList);
        paymentTransactionService.resetByCurrencyId(idList);
        productPricelistItemService.resetByCurrencyId(idList);
        productPricelistService.resetByCurrencyId(idList);
        productSupplierinfoService.resetByCurrencyId(idList);
        purchaseBillUnionService.resetByCurrencyId(idList);
        purchaseOrderLineService.resetByCurrencyId(idList);
        purchaseOrderService.resetByCurrencyId(idList);
        purchaseReportService.resetByCurrencyId(idList);
        resCompanyService.resetByCurrencyId(idList);
        resCountryService.resetByCurrencyId(idList);
        resCurrencyRateService.resetByCurrencyId(idList);
        resPartnerBankService.resetByCurrencyId(idList);
        saleOrderLineService.resetByCurrencyId(idList);
        removeByIds(idList);
    }

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

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

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

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

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

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



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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Res_currency et){
        //实体关系[DER1N_RES_CURRENCY__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_RES_CURRENCY__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<Res_currency> getResCurrencyByIds(List<Long> ids) {
         return this.listByIds(ids);
    }

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



}



