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.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_lead;
import cn.ibizlab.businesscentral.core.odoo_crm.filter.Crm_leadSearchContext;
import cn.ibizlab.businesscentral.core.odoo_crm.service.ICrm_leadService;

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_leadMapper;
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("Crm_leadServiceImpl")
public class Crm_leadServiceImpl extends EBSServiceImpl<Crm_leadMapper, Crm_lead> implements ICrm_leadService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_calendar.service.ICalendar_eventService calendarEventService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_crm.service.ICrm_activity_reportService crmActivityReportService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_sale.service.ISale_orderService saleOrderService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_crm.service.ICrm_lost_reasonService crmLostReasonService;
    @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_base.service.IRes_companyService resCompanyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_country_stateService resCountryStateService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_countryService resCountryService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_partner_titleService resPartnerTitleService;
    @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;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_utm.service.IUtm_campaignService utmCampaignService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_utm.service.IUtm_mediumService utmMediumService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_utm.service.IUtm_sourceService utmSourceService;

    protected int batchSize = 500;

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

    private boolean messageinfo = false ;

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

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

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

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

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

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

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

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


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

    @Override
    public void removeByLostReason(Long id) {
        this.remove(new QueryWrapper<Crm_lead>().eq("lost_reason",id));
    }

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

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

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

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

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

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

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

    @Override
    public void removeByStateId(Long id) {
        this.remove(new QueryWrapper<Crm_lead>().eq("state_id",id));
    }

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

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

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

    @Override
    public void removeByTitle(Long id) {
        this.remove(new QueryWrapper<Crm_lead>().eq("title",id));
    }

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

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

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

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

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

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

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

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

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

    @Override
    public void removeByCampaignId(Long id) {
        this.remove(new QueryWrapper<Crm_lead>().eq("campaign_id",id));
    }

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

    @Override
    public void removeByMediumId(Long id) {
        this.remove(new QueryWrapper<Crm_lead>().eq("medium_id",id));
    }

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

    @Override
    public void removeBySourceId(Long id) {
        this.remove(new QueryWrapper<Crm_lead>().eq("source_id",id));
    }


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Crm_lead et){
        //实体关系[DER1N_CRM_LEAD__CRM_LOST_REASON__LOST_REASON]
        if(!ObjectUtils.isEmpty(et.getLostReason())){
            cn.ibizlab.businesscentral.core.odoo_crm.domain.Crm_lost_reason odooLost=et.getOdooLost();
            if(ObjectUtils.isEmpty(odooLost)){
                cn.ibizlab.businesscentral.core.odoo_crm.domain.Crm_lost_reason majorEntity=crmLostReasonService.get(et.getLostReason());
                et.setOdooLost(majorEntity);
                odooLost=majorEntity;
            }
            et.setLostReasonText(odooLost.getName());
        }
        //实体关系[DER1N_CRM_LEAD__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_LEAD__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_LEAD__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.setCompanyCurrency(odooCompany.getCurrencyId());
            et.setCompanyIdText(odooCompany.getName());
        }
        //实体关系[DER1N_CRM_LEAD__RES_COUNTRY_STATE__STATE_ID]
        if(!ObjectUtils.isEmpty(et.getStateId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_country_state odooState=et.getOdooState();
            if(ObjectUtils.isEmpty(odooState)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_country_state majorEntity=resCountryStateService.get(et.getStateId());
                et.setOdooState(majorEntity);
                odooState=majorEntity;
            }
            et.setStateIdText(odooState.getName());
        }
        //实体关系[DER1N_CRM_LEAD__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_LEAD__RES_PARTNER_TITLE__TITLE]
        if(!ObjectUtils.isEmpty(et.getTitle())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner_title odooTitle=et.getOdooTitle();
            if(ObjectUtils.isEmpty(odooTitle)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner_title majorEntity=resPartnerTitleService.get(et.getTitle());
                et.setOdooTitle(majorEntity);
                odooTitle=majorEntity;
            }
            et.setTitleText(odooTitle.getName());
        }
        //实体关系[DER1N_CRM_LEAD__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.setPartnerAddressName(odooPartner.getName());
            et.setPartnerAddressMobile(odooPartner.getMobile());
            et.setPartnerAddressPhone(odooPartner.getPhone());
            et.setPartnerIsBlacklisted(odooPartner.getIsBlacklisted());
            et.setPartnerAddressEmail(odooPartner.getEmail());
        }
        //实体关系[DER1N_CRM_LEAD__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_CRM_LEAD__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());
            et.setUserEmail(odooUser.getEmail());
            et.setUserLogin(odooUser.getLogin());
        }
        //实体关系[DER1N_CRM_LEAD__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());
        }
        //实体关系[DER1N_CRM_LEAD__UTM_CAMPAIGN__CAMPAIGN_ID]
        if(!ObjectUtils.isEmpty(et.getCampaignId())){
            cn.ibizlab.businesscentral.core.odoo_utm.domain.Utm_campaign odooCampaign=et.getOdooCampaign();
            if(ObjectUtils.isEmpty(odooCampaign)){
                cn.ibizlab.businesscentral.core.odoo_utm.domain.Utm_campaign majorEntity=utmCampaignService.get(et.getCampaignId());
                et.setOdooCampaign(majorEntity);
                odooCampaign=majorEntity;
            }
            et.setCampaignIdText(odooCampaign.getName());
        }
        //实体关系[DER1N_CRM_LEAD__UTM_MEDIUM__MEDIUM_ID]
        if(!ObjectUtils.isEmpty(et.getMediumId())){
            cn.ibizlab.businesscentral.core.odoo_utm.domain.Utm_medium odooMedium=et.getOdooMedium();
            if(ObjectUtils.isEmpty(odooMedium)){
                cn.ibizlab.businesscentral.core.odoo_utm.domain.Utm_medium majorEntity=utmMediumService.get(et.getMediumId());
                et.setOdooMedium(majorEntity);
                odooMedium=majorEntity;
            }
            et.setMediumIdText(odooMedium.getName());
        }
        //实体关系[DER1N_CRM_LEAD__UTM_SOURCE__SOURCE_ID]
        if(!ObjectUtils.isEmpty(et.getSourceId())){
            cn.ibizlab.businesscentral.core.odoo_utm.domain.Utm_source odooSource=et.getOdooSource();
            if(ObjectUtils.isEmpty(odooSource)){
                cn.ibizlab.businesscentral.core.odoo_utm.domain.Utm_source majorEntity=utmSourceService.get(et.getSourceId());
                et.setOdooSource(majorEntity);
                odooSource=majorEntity;
            }
            et.setSourceIdText(odooSource.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<Crm_lead> getCrmLeadByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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



}



