package cn.ibizlab.businesscentral.core.odoo_crm.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_crm.domain.Crm_activity_report;
import cn.ibizlab.businesscentral.core.odoo_crm.filter.Crm_activity_reportSearchContext;
import cn.ibizlab.businesscentral.core.odoo_crm.service.ICrm_activity_reportService;

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_crm.mapper.Crm_activity_reportMapper;
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;

/**
 * 实体[CRM活动分析] 服务对象接口实现
 */
@Slf4j
@Service("Crm_activity_reportServiceImpl")
public class Crm_activity_reportServiceImpl extends EBSServiceImpl<Crm_activity_reportMapper, Crm_activity_report> implements ICrm_activity_reportService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_crm.service.ICrm_leadService crmLeadService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_crm.service.ICrm_stageService crmStageService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_crm.service.ICrm_teamService crmTeamService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mail.service.IMail_activity_typeService mailActivityTypeService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mail.service.IMail_message_subtypeService mailMessageSubtypeService;
    @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_partnerService resPartnerService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

    public String getIrModel(){
        return "crm.activity.report" ;
    }

    private boolean messageinfo = false ;

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

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

    @Override
    @Transactional
    public boolean update(Crm_activity_report et) {
        Crm_activity_report old = new Crm_activity_report() ;
        CachedBeanCopier.copy((AopContext.currentProxy() != null ? (ICrm_activity_reportService)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 ? (ICrm_activity_reportService)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<Crm_activity_report> 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 Crm_activity_report get(Long key) {
        Crm_activity_report et = getById(key);
        if(et==null){
            et=new Crm_activity_report();
            et.setId(key);
        }
        else{
        }
        return et;
    }

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

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

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

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

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


	@Override
    public List<Crm_activity_report> selectByLeadId(Long id) {
        return baseMapper.selectByLeadId(id);
    }
    @Override
    public void resetByLeadId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("lead_id",null).eq("lead_id",id));
    }

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

    @Override
    public void removeByLeadId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("lead_id",id));
    }

	@Override
    public List<Crm_activity_report> selectByStageId(Long id) {
        return baseMapper.selectByStageId(id);
    }
    @Override
    public void resetByStageId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("stage_id",null).eq("stage_id",id));
    }

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

    @Override
    public void removeByStageId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("stage_id",id));
    }

	@Override
    public List<Crm_activity_report> selectByTeamId(Long id) {
        return baseMapper.selectByTeamId(id);
    }
    @Override
    public void resetByTeamId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("team_id",null).eq("team_id",id));
    }

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

    @Override
    public void removeByTeamId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("team_id",id));
    }

	@Override
    public List<Crm_activity_report> selectByMailActivityTypeId(Long id) {
        return baseMapper.selectByMailActivityTypeId(id);
    }
    @Override
    public void resetByMailActivityTypeId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("mail_activity_type_id",null).eq("mail_activity_type_id",id));
    }

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

    @Override
    public void removeByMailActivityTypeId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("mail_activity_type_id",id));
    }

	@Override
    public List<Crm_activity_report> selectBySubtypeId(Long id) {
        return baseMapper.selectBySubtypeId(id);
    }
    @Override
    public void resetBySubtypeId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("subtype_id",null).eq("subtype_id",id));
    }

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

    @Override
    public void removeBySubtypeId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("subtype_id",id));
    }

	@Override
    public List<Crm_activity_report> selectByCompanyId(Long id) {
        return baseMapper.selectByCompanyId(id);
    }
    @Override
    public void resetByCompanyId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("company_id",null).eq("company_id",id));
    }

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

    @Override
    public void removeByCompanyId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("company_id",id));
    }

	@Override
    public List<Crm_activity_report> selectByCountryId(Long id) {
        return baseMapper.selectByCountryId(id);
    }
    @Override
    public void resetByCountryId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("country_id",null).eq("country_id",id));
    }

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

    @Override
    public void removeByCountryId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("country_id",id));
    }

	@Override
    public List<Crm_activity_report> selectByAuthorId(Long id) {
        return baseMapper.selectByAuthorId(id);
    }
    @Override
    public void resetByAuthorId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("author_id",null).eq("author_id",id));
    }

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

    @Override
    public void removeByAuthorId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("author_id",id));
    }

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

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

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

	@Override
    public List<Crm_activity_report> selectByUserId(Long id) {
        return baseMapper.selectByUserId(id);
    }
    @Override
    public void resetByUserId(Long id) {
        this.update(new UpdateWrapper<Crm_activity_report>().set("user_id",null).eq("user_id",id));
    }

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

    @Override
    public void removeByUserId(Long id) {
        this.remove(new QueryWrapper<Crm_activity_report>().eq("user_id",id));
    }


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Crm_activity_report et){
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__CRM_LEAD__LEAD_ID]
        if(!ObjectUtils.isEmpty(et.getLeadId())){
            cn.ibizlab.businesscentral.core.odoo_crm.domain.Crm_lead odooLead=et.getOdooLead();
            if(ObjectUtils.isEmpty(odooLead)){
                cn.ibizlab.businesscentral.core.odoo_crm.domain.Crm_lead majorEntity=crmLeadService.get(et.getLeadId());
                et.setOdooLead(majorEntity);
                odooLead=majorEntity;
            }
            et.setLeadIdText(odooLead.getName());
        }
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__CRM_STAGE__STAGE_ID]
        if(!ObjectUtils.isEmpty(et.getStageId())){
            cn.ibizlab.businesscentral.core.odoo_crm.domain.Crm_stage odooStage=et.getOdooStage();
            if(ObjectUtils.isEmpty(odooStage)){
                cn.ibizlab.businesscentral.core.odoo_crm.domain.Crm_stage majorEntity=crmStageService.get(et.getStageId());
                et.setOdooStage(majorEntity);
                odooStage=majorEntity;
            }
            et.setStageIdText(odooStage.getName());
        }
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__CRM_TEAM__TEAM_ID]
        if(!ObjectUtils.isEmpty(et.getTeamId())){
            cn.ibizlab.businesscentral.core.odoo_crm.domain.Crm_team odooTeam=et.getOdooTeam();
            if(ObjectUtils.isEmpty(odooTeam)){
                cn.ibizlab.businesscentral.core.odoo_crm.domain.Crm_team majorEntity=crmTeamService.get(et.getTeamId());
                et.setOdooTeam(majorEntity);
                odooTeam=majorEntity;
            }
            et.setTeamIdText(odooTeam.getName());
        }
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__MAIL_ACTIVITY_TYPE__MAIL_ACTIVITY_TYPE_ID]
        if(!ObjectUtils.isEmpty(et.getMailActivityTypeId())){
            cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_activity_type odooMailActivityType=et.getOdooMailActivityType();
            if(ObjectUtils.isEmpty(odooMailActivityType)){
                cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_activity_type majorEntity=mailActivityTypeService.get(et.getMailActivityTypeId());
                et.setOdooMailActivityType(majorEntity);
                odooMailActivityType=majorEntity;
            }
            et.setMailActivityTypeIdText(odooMailActivityType.getName());
        }
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__MAIL_MESSAGE_SUBTYPE__SUBTYPE_ID]
        if(!ObjectUtils.isEmpty(et.getSubtypeId())){
            cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_message_subtype odooSubtype=et.getOdooSubtype();
            if(ObjectUtils.isEmpty(odooSubtype)){
                cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_message_subtype majorEntity=mailMessageSubtypeService.get(et.getSubtypeId());
                et.setOdooSubtype(majorEntity);
                odooSubtype=majorEntity;
            }
            et.setSubtypeIdText(odooSubtype.getName());
        }
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__RES_COMPANY__COMPANY_ID]
        if(!ObjectUtils.isEmpty(et.getCompanyId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_company odooCompany=et.getOdooCompany();
            if(ObjectUtils.isEmpty(odooCompany)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_company majorEntity=resCompanyService.get(et.getCompanyId());
                et.setOdooCompany(majorEntity);
                odooCompany=majorEntity;
            }
            et.setCompanyIdText(odooCompany.getName());
        }
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__RES_COUNTRY__COUNTRY_ID]
        if(!ObjectUtils.isEmpty(et.getCountryId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_country odooCountry=et.getOdooCountry();
            if(ObjectUtils.isEmpty(odooCountry)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_country majorEntity=resCountryService.get(et.getCountryId());
                et.setOdooCountry(majorEntity);
                odooCountry=majorEntity;
            }
            et.setCountryIdText(odooCountry.getName());
        }
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__RES_PARTNER__AUTHOR_ID]
        if(!ObjectUtils.isEmpty(et.getAuthorId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner odooAuthor=et.getOdooAuthor();
            if(ObjectUtils.isEmpty(odooAuthor)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner majorEntity=resPartnerService.get(et.getAuthorId());
                et.setOdooAuthor(majorEntity);
                odooAuthor=majorEntity;
            }
            et.setAuthorIdText(odooAuthor.getName());
        }
        //实体关系[DER1N_CRM_ACTIVITY_REPORT__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_CRM_ACTIVITY_REPORT__RES_USERS__USER_ID]
        if(!ObjectUtils.isEmpty(et.getUserId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users odooUser=et.getOdooUser();
            if(ObjectUtils.isEmpty(odooUser)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users majorEntity=resUsersService.get(et.getUserId());
                et.setOdooUser(majorEntity);
                odooUser=majorEntity;
            }
            et.setUserIdText(odooUser.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;
    }




}



