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.aop.framework.AopContext;
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_payment;
import cn.ibizlab.businesscentral.core.odoo_account.filter.Account_paymentSearchContext;
import cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_paymentService;

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_paymentMapper;
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_paymentServiceImpl")
public class Account_paymentServiceImpl extends EBSServiceImpl<Account_paymentMapper, Account_payment> implements IAccount_paymentService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_move_lineService accountMoveLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_payment.service.IPayment_transactionService paymentTransactionService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_accountService accountAccountService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_journalService accountJournalService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_payment_methodService accountPaymentMethodService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_payment.service.IPayment_tokenService paymentTokenService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_currencyService resCurrencyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_partner_bankService resPartnerBankService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_partnerService resPartnerService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

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

    private boolean messageinfo = false ;

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

    @Override
    @Transactional
    public boolean create(Account_payment 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((AopContext.currentProxy() != null ? (IAccount_paymentService)AopContext.currentProxy() : this).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<Account_payment> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean update(Account_payment et) {
        Account_payment old = new Account_payment() ;
        CachedBeanCopier.copy((AopContext.currentProxy() != null ? (IAccount_paymentService)AopContext.currentProxy() : this).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((AopContext.currentProxy() != null ? (IAccount_paymentService)AopContext.currentProxy() : this).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_payment> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

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

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

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

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

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

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

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

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


	@Override
    public List<Account_payment> selectByWriteoffAccountId(Long id) {
        return baseMapper.selectByWriteoffAccountId(id);
    }
    @Override
    public void resetByWriteoffAccountId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("writeoff_account_id",null).eq("writeoff_account_id",id));
    }

    @Override
    public void resetByWriteoffAccountId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("writeoff_account_id",null).in("writeoff_account_id",ids));
    }

    @Override
    public void removeByWriteoffAccountId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("writeoff_account_id",id));
    }

	@Override
    public List<Account_payment> selectByDestinationJournalId(Long id) {
        return baseMapper.selectByDestinationJournalId(id);
    }
    @Override
    public void resetByDestinationJournalId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("destination_journal_id",null).eq("destination_journal_id",id));
    }

    @Override
    public void resetByDestinationJournalId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("destination_journal_id",null).in("destination_journal_id",ids));
    }

    @Override
    public void removeByDestinationJournalId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("destination_journal_id",id));
    }

	@Override
    public List<Account_payment> selectByJournalId(Long id) {
        return baseMapper.selectByJournalId(id);
    }
    @Override
    public void resetByJournalId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("journal_id",null).eq("journal_id",id));
    }

    @Override
    public void resetByJournalId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("journal_id",null).in("journal_id",ids));
    }

    @Override
    public void removeByJournalId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("journal_id",id));
    }

	@Override
    public List<Account_payment> selectByPaymentMethodId(Long id) {
        return baseMapper.selectByPaymentMethodId(id);
    }
    @Override
    public void resetByPaymentMethodId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("payment_method_id",null).eq("payment_method_id",id));
    }

    @Override
    public void resetByPaymentMethodId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("payment_method_id",null).in("payment_method_id",ids));
    }

    @Override
    public void removeByPaymentMethodId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("payment_method_id",id));
    }

	@Override
    public List<Account_payment> selectByPaymentTokenId(Long id) {
        return baseMapper.selectByPaymentTokenId(id);
    }
    @Override
    public void resetByPaymentTokenId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("payment_token_id",null).eq("payment_token_id",id));
    }

    @Override
    public void resetByPaymentTokenId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("payment_token_id",null).in("payment_token_id",ids));
    }

    @Override
    public void removeByPaymentTokenId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("payment_token_id",id));
    }

	@Override
    public List<Account_payment> selectByPaymentTransactionId(Long id) {
        return baseMapper.selectByPaymentTransactionId(id);
    }
    @Override
    public void resetByPaymentTransactionId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("payment_transaction_id",null).eq("payment_transaction_id",id));
    }

    @Override
    public void resetByPaymentTransactionId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("payment_transaction_id",null).in("payment_transaction_id",ids));
    }

    @Override
    public void removeByPaymentTransactionId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("payment_transaction_id",id));
    }

	@Override
    public List<Account_payment> selectByCurrencyId(Long id) {
        return baseMapper.selectByCurrencyId(id);
    }
    @Override
    public void resetByCurrencyId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("currency_id",null).eq("currency_id",id));
    }

    @Override
    public void resetByCurrencyId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("currency_id",null).in("currency_id",ids));
    }

    @Override
    public void removeByCurrencyId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("currency_id",id));
    }

	@Override
    public List<Account_payment> selectByPartnerBankAccountId(Long id) {
        return baseMapper.selectByPartnerBankAccountId(id);
    }
    @Override
    public void resetByPartnerBankAccountId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("partner_bank_account_id",null).eq("partner_bank_account_id",id));
    }

    @Override
    public void resetByPartnerBankAccountId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("partner_bank_account_id",null).in("partner_bank_account_id",ids));
    }

    @Override
    public void removeByPartnerBankAccountId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("partner_bank_account_id",id));
    }

	@Override
    public List<Account_payment> selectByPartnerId(Long id) {
        return baseMapper.selectByPartnerId(id);
    }
    @Override
    public void resetByPartnerId(Long id) {
        this.update(new UpdateWrapper<Account_payment>().set("partner_id",null).eq("partner_id",id));
    }

    @Override
    public void resetByPartnerId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Account_payment>().set("partner_id",null).in("partner_id",ids));
    }

    @Override
    public void removeByPartnerId(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("partner_id",id));
    }

	@Override
    public List<Account_payment> selectByCreateUid(Long id) {
        return baseMapper.selectByCreateUid(id);
    }
    @Override
    public void removeByCreateUid(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("create_uid",id));
    }

	@Override
    public List<Account_payment> selectByWriteUid(Long id) {
        return baseMapper.selectByWriteUid(id);
    }
    @Override
    public void removeByWriteUid(Long id) {
        this.remove(new QueryWrapper<Account_payment>().eq("write_uid",id));
    }


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Account_payment et){
        //实体关系[DER1N_ACCOUNT_PAYMENT__ACCOUNT_ACCOUNT__WRITEOFF_ACCOUNT_ID]
        if(!ObjectUtils.isEmpty(et.getWriteoffAccountId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account odooWriteoffAccount=et.getOdooWriteoffAccount();
            if(ObjectUtils.isEmpty(odooWriteoffAccount)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_account majorEntity=accountAccountService.get(et.getWriteoffAccountId());
                et.setOdooWriteoffAccount(majorEntity);
                odooWriteoffAccount=majorEntity;
            }
            et.setWriteoffAccountIdText(odooWriteoffAccount.getName());
        }
        //实体关系[DER1N_ACCOUNT_PAYMENT__ACCOUNT_JOURNAL__DESTINATION_JOURNAL_ID]
        if(!ObjectUtils.isEmpty(et.getDestinationJournalId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_journal odooDestinationJournal=et.getOdooDestinationJournal();
            if(ObjectUtils.isEmpty(odooDestinationJournal)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_journal majorEntity=accountJournalService.get(et.getDestinationJournalId());
                et.setOdooDestinationJournal(majorEntity);
                odooDestinationJournal=majorEntity;
            }
            et.setDestinationJournalIdText(odooDestinationJournal.getName());
        }
        //实体关系[DER1N_ACCOUNT_PAYMENT__ACCOUNT_JOURNAL__JOURNAL_ID]
        if(!ObjectUtils.isEmpty(et.getJournalId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_journal odooJournal=et.getOdooJournal();
            if(ObjectUtils.isEmpty(odooJournal)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_journal majorEntity=accountJournalService.get(et.getJournalId());
                et.setOdooJournal(majorEntity);
                odooJournal=majorEntity;
            }
            et.setJournalIdText(odooJournal.getName());
            et.setCompanyId(odooJournal.getCompanyId());
        }
        //实体关系[DER1N_ACCOUNT_PAYMENT__ACCOUNT_PAYMENT_METHOD__PAYMENT_METHOD_ID]
        if(!ObjectUtils.isEmpty(et.getPaymentMethodId())){
            cn.ibizlab.businesscentral.core.odoo_account.domain.Account_payment_method odooPaymentMethod=et.getOdooPaymentMethod();
            if(ObjectUtils.isEmpty(odooPaymentMethod)){
                cn.ibizlab.businesscentral.core.odoo_account.domain.Account_payment_method majorEntity=accountPaymentMethodService.get(et.getPaymentMethodId());
                et.setOdooPaymentMethod(majorEntity);
                odooPaymentMethod=majorEntity;
            }
            et.setPaymentMethodCode(odooPaymentMethod.getCode());
            et.setPaymentMethodIdText(odooPaymentMethod.getName());
        }
        //实体关系[DER1N_ACCOUNT_PAYMENT__PAYMENT_TOKEN__PAYMENT_TOKEN_ID]
        if(!ObjectUtils.isEmpty(et.getPaymentTokenId())){
            cn.ibizlab.businesscentral.core.odoo_payment.domain.Payment_token odooPaymentToken=et.getOdooPaymentToken();
            if(ObjectUtils.isEmpty(odooPaymentToken)){
                cn.ibizlab.businesscentral.core.odoo_payment.domain.Payment_token majorEntity=paymentTokenService.get(et.getPaymentTokenId());
                et.setOdooPaymentToken(majorEntity);
                odooPaymentToken=majorEntity;
            }
            et.setPaymentTokenIdText(odooPaymentToken.getName());
        }
        //实体关系[DER1N_ACCOUNT_PAYMENT__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_PAYMENT__RES_PARTNER__PARTNER_ID]
        if(!ObjectUtils.isEmpty(et.getPartnerId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner odooPartner=et.getOdooPartner();
            if(ObjectUtils.isEmpty(odooPartner)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner majorEntity=resPartnerService.get(et.getPartnerId());
                et.setOdooPartner(majorEntity);
                odooPartner=majorEntity;
            }
            et.setPartnerIdText(odooPartner.getName());
        }
        //实体关系[DER1N_ACCOUNT_PAYMENT__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_PAYMENT__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_payment> getAccountPaymentByIds(List<Long> ids) {
         return this.listByIds(ids);
    }

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



}



