package cn.ibizlab.businesscentral.core.odoo_mail.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_mail.domain.Mail_activity;
import cn.ibizlab.businesscentral.core.odoo_mail.filter.Mail_activitySearchContext;
import cn.ibizlab.businesscentral.core.odoo_mail.service.IMail_activityService;

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_mail.mapper.Mail_activityMapper;
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("Mail_activityServiceImpl")
public class Mail_activityServiceImpl extends EBSServiceImpl<Mail_activityMapper, Mail_activity> implements IMail_activityService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_calendar.service.ICalendar_eventService calendarEventService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mail.service.IMail_activity_typeService mailActivityTypeService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_note.service.INote_noteService noteNoteService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

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

    private boolean messageinfo = false ;

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

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

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

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

    @Override
    @Transactional
    public Mail_activity action_done(Mail_activity et) {
        //自定义代码
        return et;
    }

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

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

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

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


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

    @Override
    public void removeByCalendarEventId(Long id) {
        this.remove(new QueryWrapper<Mail_activity>().eq("calendar_event_id",id));
    }

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

    @Override
    public void removeByActivityTypeId(Long id) {
        this.remove(new QueryWrapper<Mail_activity>().eq("activity_type_id",id));
    }

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

    @Override
    public void removeByPreviousActivityTypeId(Long id) {
        this.remove(new QueryWrapper<Mail_activity>().eq("previous_activity_type_id",id));
    }

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

    @Override
    public void removeByRecommendedActivityTypeId(Long id) {
        this.remove(new QueryWrapper<Mail_activity>().eq("recommended_activity_type_id",id));
    }

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

    @Override
    public void removeByNoteId(Long id) {
        this.remove(new QueryWrapper<Mail_activity>().eq("note_id",id));
    }

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

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

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

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

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

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


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Mail_activity et){
        //实体关系[DER1N_MAIL_ACTIVITY__CALENDAR_EVENT__CALENDAR_EVENT_ID]
        if(!ObjectUtils.isEmpty(et.getCalendarEventId())){
            cn.ibizlab.businesscentral.core.odoo_calendar.domain.Calendar_event odooCalendarEvent=et.getOdooCalendarEvent();
            if(ObjectUtils.isEmpty(odooCalendarEvent)){
                cn.ibizlab.businesscentral.core.odoo_calendar.domain.Calendar_event majorEntity=calendarEventService.get(et.getCalendarEventId());
                et.setOdooCalendarEvent(majorEntity);
                odooCalendarEvent=majorEntity;
            }
            et.setCalendarEventIdText(odooCalendarEvent.getName());
        }
        //实体关系[DER1N_MAIL_ACTIVITY__MAIL_ACTIVITY_TYPE__ACTIVITY_TYPE_ID]
        if(!ObjectUtils.isEmpty(et.getActivityTypeId())){
            cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_activity_type odooActivityType=et.getOdooActivityType();
            if(ObjectUtils.isEmpty(odooActivityType)){
                cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_activity_type majorEntity=mailActivityTypeService.get(et.getActivityTypeId());
                et.setOdooActivityType(majorEntity);
                odooActivityType=majorEntity;
            }
            et.setActivityCategory(odooActivityType.getCategory());
            et.setActivityTypeIdText(odooActivityType.getName());
            et.setIcon(odooActivityType.getIcon());
            et.setActivityDecoration(odooActivityType.getDecorationType());
            et.setForceNext(odooActivityType.getForceNext());
        }
        //实体关系[DER1N_MAIL_ACTIVITY__MAIL_ACTIVITY_TYPE__PREVIOUS_ACTIVITY_TYPE_ID]
        if(!ObjectUtils.isEmpty(et.getPreviousActivityTypeId())){
            cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_activity_type odooPreviousActivityType=et.getOdooPreviousActivityType();
            if(ObjectUtils.isEmpty(odooPreviousActivityType)){
                cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_activity_type majorEntity=mailActivityTypeService.get(et.getPreviousActivityTypeId());
                et.setOdooPreviousActivityType(majorEntity);
                odooPreviousActivityType=majorEntity;
            }
            et.setPreviousActivityTypeIdText(odooPreviousActivityType.getName());
        }
        //实体关系[DER1N_MAIL_ACTIVITY__MAIL_ACTIVITY_TYPE__RECOMMENDED_ACTIVITY_TYPE_ID]
        if(!ObjectUtils.isEmpty(et.getRecommendedActivityTypeId())){
            cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_activity_type odooRecommendedActivityType=et.getOdooRecommendedActivityType();
            if(ObjectUtils.isEmpty(odooRecommendedActivityType)){
                cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_activity_type majorEntity=mailActivityTypeService.get(et.getRecommendedActivityTypeId());
                et.setOdooRecommendedActivityType(majorEntity);
                odooRecommendedActivityType=majorEntity;
            }
            et.setRecommendedActivityTypeIdText(odooRecommendedActivityType.getName());
        }
        //实体关系[DER1N_MAIL_ACTIVITY__NOTE_NOTE__NOTE_ID]
        if(!ObjectUtils.isEmpty(et.getNoteId())){
            cn.ibizlab.businesscentral.core.odoo_note.domain.Note_note odooNote=et.getOdooNote();
            if(ObjectUtils.isEmpty(odooNote)){
                cn.ibizlab.businesscentral.core.odoo_note.domain.Note_note majorEntity=noteNoteService.get(et.getNoteId());
                et.setOdooNote(majorEntity);
                odooNote=majorEntity;
            }
            et.setNoteIdText(odooNote.getName());
        }
        //实体关系[DER1N_MAIL_ACTIVITY__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_MAIL_ACTIVITY__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());
        }
        //实体关系[DER1N_MAIL_ACTIVITY__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<Mail_activity> getMailActivityByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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



}



