package cn.ibizlab.businesscentral.core.odoo_account.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_account.domain.Account_chart_template;
import cn.ibizlab.businesscentral.core.odoo_account.filter.Account_chart_templateSearchContext;
import cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_chart_templateService;

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_account.mapper.Account_chart_templateMapper;
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("Account_chart_templateServiceImpl")
public class Account_chart_templateServiceImpl extends EBSServiceImpl<Account_chart_templateMapper, Account_chart_template> implements IAccount_chart_templateService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_account_templateService accountAccountTemplateService;

    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_chart_templateService accountChartTemplateService = this;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_fiscal_position_templateService accountFiscalPositionTemplateService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_reconcile_model_templateService accountReconcileModelTemplateService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_tax_templateService accountTaxTemplateService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_companyService resCompanyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_config_settingsService resConfigSettingsService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_currencyService resCurrencyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

    public String getIrModel(){
        return "account.chart.template" ;
    }

    private boolean messageinfo = false ;

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

    @Override
    @Transactional
    public boolean create(Account_chart_template 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<Account_chart_template> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean update(Account_chart_template et) {
        Account_chart_template old = new Account_chart_template() ;
        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<Account_chart_template> 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 Account_chart_template get(Long key) {
        Account_chart_template et = getById(key);
        if(et==null){
            et=new Account_chart_template();
            et.setId(key);
        }
        else{
        }
        return et;
    }





    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Account_chart_template et){
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__EXPENSE_CURRENCY_EXCHANGE_ACCOUNT_ID]
        if(!ObjectUtils.isEmpty(et.getExpenseCurrencyExchangeAccountId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooExpenseCurrencyExchangeAccount=et.getOdooExpenseCurrencyExchangeAccount();
            if(ObjectUtils.isEmpty(odooExpenseCurrencyExchangeAccount)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getExpenseCurrencyExchangeAccountId());
                et.setOdooExpenseCurrencyExchangeAccount(majorEntity);
                odooExpenseCurrencyExchangeAccount=majorEntity;
            }
            et.setExpenseCurrencyExchangeAccountIdText(odooExpenseCurrencyExchangeAccount.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__INCOME_CURRENCY_EXCHANGE_ACCOUNT_ID]
        if(!ObjectUtils.isEmpty(et.getIncomeCurrencyExchangeAccountId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooIncomeCurrencyExchangeAccount=et.getOdooIncomeCurrencyExchangeAccount();
            if(ObjectUtils.isEmpty(odooIncomeCurrencyExchangeAccount)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getIncomeCurrencyExchangeAccountId());
                et.setOdooIncomeCurrencyExchangeAccount(majorEntity);
                odooIncomeCurrencyExchangeAccount=majorEntity;
            }
            et.setIncomeCurrencyExchangeAccountIdText(odooIncomeCurrencyExchangeAccount.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_ACCOUNT_EXPENSE_CATEG_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyAccountExpenseCategId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyAccountExpenseCateg=et.getOdooPropertyAccountExpenseCateg();
            if(ObjectUtils.isEmpty(odooPropertyAccountExpenseCateg)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyAccountExpenseCategId());
                et.setOdooPropertyAccountExpenseCateg(majorEntity);
                odooPropertyAccountExpenseCateg=majorEntity;
            }
            et.setPropertyAccountExpenseCategIdText(odooPropertyAccountExpenseCateg.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_ACCOUNT_EXPENSE_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyAccountExpenseId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyAccountExpense=et.getOdooPropertyAccountExpense();
            if(ObjectUtils.isEmpty(odooPropertyAccountExpense)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyAccountExpenseId());
                et.setOdooPropertyAccountExpense(majorEntity);
                odooPropertyAccountExpense=majorEntity;
            }
            et.setPropertyAccountExpenseIdText(odooPropertyAccountExpense.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_ACCOUNT_INCOME_CATEG_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyAccountIncomeCategId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyAccountIncomeCateg=et.getOdooPropertyAccountIncomeCateg();
            if(ObjectUtils.isEmpty(odooPropertyAccountIncomeCateg)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyAccountIncomeCategId());
                et.setOdooPropertyAccountIncomeCateg(majorEntity);
                odooPropertyAccountIncomeCateg=majorEntity;
            }
            et.setPropertyAccountIncomeCategIdText(odooPropertyAccountIncomeCateg.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_ACCOUNT_INCOME_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyAccountIncomeId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyAccountIncome=et.getOdooPropertyAccountIncome();
            if(ObjectUtils.isEmpty(odooPropertyAccountIncome)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyAccountIncomeId());
                et.setOdooPropertyAccountIncome(majorEntity);
                odooPropertyAccountIncome=majorEntity;
            }
            et.setPropertyAccountIncomeIdText(odooPropertyAccountIncome.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_ACCOUNT_PAYABLE_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyAccountPayableId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyAccountPayable=et.getOdooPropertyAccountPayable();
            if(ObjectUtils.isEmpty(odooPropertyAccountPayable)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyAccountPayableId());
                et.setOdooPropertyAccountPayable(majorEntity);
                odooPropertyAccountPayable=majorEntity;
            }
            et.setPropertyAccountPayableIdText(odooPropertyAccountPayable.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_ACCOUNT_RECEIVABLE_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyAccountReceivableId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyAccountReceivable=et.getOdooPropertyAccountReceivable();
            if(ObjectUtils.isEmpty(odooPropertyAccountReceivable)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyAccountReceivableId());
                et.setOdooPropertyAccountReceivable(majorEntity);
                odooPropertyAccountReceivable=majorEntity;
            }
            et.setPropertyAccountReceivableIdText(odooPropertyAccountReceivable.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_STOCK_ACCOUNT_INPUT_CATEG_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyStockAccountInputCategId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyStockAccountInputCateg=et.getOdooPropertyStockAccountInputCateg();
            if(ObjectUtils.isEmpty(odooPropertyStockAccountInputCateg)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyStockAccountInputCategId());
                et.setOdooPropertyStockAccountInputCateg(majorEntity);
                odooPropertyStockAccountInputCateg=majorEntity;
            }
            et.setPropertyStockAccountInputCategIdText(odooPropertyStockAccountInputCateg.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_STOCK_ACCOUNT_OUTPUT_CATEG_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyStockAccountOutputCategId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyStockAccountOutputCateg=et.getOdooPropertyStockAccountOutputCateg();
            if(ObjectUtils.isEmpty(odooPropertyStockAccountOutputCateg)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyStockAccountOutputCategId());
                et.setOdooPropertyStockAccountOutputCateg(majorEntity);
                odooPropertyStockAccountOutputCateg=majorEntity;
            }
            et.setPropertyStockAccountOutputCategIdText(odooPropertyStockAccountOutputCateg.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_ACCOUNT_TEMPLATE__PROPERTY_STOCK_VALUATION_ACCOUNT_ID]
        if(!ObjectUtils.isEmpty(et.getPropertyStockValuationAccountId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template odooPropertyStockValuationAccount=et.getOdooPropertyStockValuationAccount();
            if(ObjectUtils.isEmpty(odooPropertyStockValuationAccount)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account_template majorEntity=accountAccountTemplateService.get(et.getPropertyStockValuationAccountId());
                et.setOdooPropertyStockValuationAccount(majorEntity);
                odooPropertyStockValuationAccount=majorEntity;
            }
            et.setPropertyStockValuationAccountIdText(odooPropertyStockValuationAccount.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__ACCOUNT_CHART_TEMPLATE__PARENT_ID]
        if(!ObjectUtils.isEmpty(et.getParentId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_chart_template odooParent=et.getOdooParent();
            if(ObjectUtils.isEmpty(odooParent)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_chart_template majorEntity=accountChartTemplateService.get(et.getParentId());
                et.setOdooParent(majorEntity);
                odooParent=majorEntity;
            }
            et.setParentIdText(odooParent.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__RES_CURRENCY__CURRENCY_ID]
        if(!ObjectUtils.isEmpty(et.getCurrencyId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_currency odooCurrency=et.getOdooCurrency();
            if(ObjectUtils.isEmpty(odooCurrency)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_currency majorEntity=resCurrencyService.get(et.getCurrencyId());
                et.setOdooCurrency(majorEntity);
                odooCurrency=majorEntity;
            }
            et.setCurrencyIdText(odooCurrency.getName());
        }
        //实体关系[DER1N_ACCOUNT_CHART_TEMPLATE__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_ACCOUNT_CHART_TEMPLATE__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<Account_chart_template> getAccountChartTemplateByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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



}



