package cn.ibizlab.eam.core.eam_core.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.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.eam.core.eam_core.domain.EMPlanTempl;
import cn.ibizlab.eam.core.eam_core.filter.EMPlanTemplSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMPlanTemplService;

import cn.ibizlab.eam.util.helper.CachedBeanCopier;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.eam.core.eam_core.mapper.EMPlanTemplMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[计划模板] 服务对象接口实现
 */
@Slf4j
@Service("EMPlanTemplServiceImpl")
public class EMPlanTemplServiceImpl extends ServiceImpl<EMPlanTemplMapper, EMPlanTempl> implements IEMPlanTemplService {

    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMPlanTDetailService emplantdetailService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMPlanService emplanService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMACClassService emacclassService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMServiceService emserviceService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_pf.service.IPFDeptService pfdeptService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_pf.service.IPFEmpService pfempService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_pf.service.IPFTeamService pfteamService;

    private int batchSize = 500;

    @Override
    @Transactional
    public EMPlanTempl get(String key) {
        EMPlanTempl et = getById(key);
        if(et==null){
            et=new EMPlanTempl();
            et.setEmplantemplid(key);
        }
        else{
        }
        return et;
    }

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

    @Override
    @Transactional
    public boolean create(EMPlanTempl et) {
        fillParentData(et);
        createIndexMajorEntityData(et);
        if(!this.retBool(this.baseMapper.insert(et)))
            return false;
        CachedBeanCopier.copy(get(et.getEmplantemplid()),et);
        return true;
    }

    @Override
    public void createBatch(List<EMPlanTempl> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result=removeById(key);
        emresrefobjService.remove(key);
        return result ;
    }

    @Override
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    public boolean checkKey(EMPlanTempl et) {
        return (!ObjectUtils.isEmpty(et.getEmplantemplid()))&&(!Objects.isNull(this.getById(et.getEmplantemplid())));
    }
    @Override
    @Transactional
    public boolean update(EMPlanTempl et) {
        fillParentData(et);
        emresrefobjService.update(emplantemplInheritMapping.toEmresrefobj(et));
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("emplantemplid",et.getEmplantemplid())))
            return false;
        CachedBeanCopier.copy(get(et.getEmplantemplid()),et);
        return true;
    }

    @Override
    public void updateBatch(List<EMPlanTempl> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean save(EMPlanTempl et) {
        if(!saveOrUpdate(et))
            return false;
        return true;
    }

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

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

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


	@Override
    public List<EMPlanTempl> selectByAcclassid(String emacclassid) {
        return baseMapper.selectByAcclassid(emacclassid);
    }

    @Override
    public void removeByAcclassid(String emacclassid) {
        this.remove(new QueryWrapper<EMPlanTempl>().eq("acclassid",emacclassid));
    }

	@Override
    public List<EMPlanTempl> selectByRserviceid(String emserviceid) {
        return baseMapper.selectByRserviceid(emserviceid);
    }

    @Override
    public void removeByRserviceid(String emserviceid) {
        this.remove(new QueryWrapper<EMPlanTempl>().eq("rserviceid",emserviceid));
    }

	@Override
    public List<EMPlanTempl> selectByRdeptid(String pfdeptid) {
        return baseMapper.selectByRdeptid(pfdeptid);
    }

    @Override
    public void removeByRdeptid(String pfdeptid) {
        this.remove(new QueryWrapper<EMPlanTempl>().eq("rdeptid",pfdeptid));
    }

	@Override
    public List<EMPlanTempl> selectByMpersonid(String pfempid) {
        return baseMapper.selectByMpersonid(pfempid);
    }

    @Override
    public void removeByMpersonid(String pfempid) {
        this.remove(new QueryWrapper<EMPlanTempl>().eq("mpersonid",pfempid));
    }

	@Override
    public List<EMPlanTempl> selectByRecvpersonid(String pfempid) {
        return baseMapper.selectByRecvpersonid(pfempid);
    }

    @Override
    public void removeByRecvpersonid(String pfempid) {
        this.remove(new QueryWrapper<EMPlanTempl>().eq("recvpersonid",pfempid));
    }

	@Override
    public List<EMPlanTempl> selectByRempid(String pfempid) {
        return baseMapper.selectByRempid(pfempid);
    }

    @Override
    public void removeByRempid(String pfempid) {
        this.remove(new QueryWrapper<EMPlanTempl>().eq("rempid",pfempid));
    }

	@Override
    public List<EMPlanTempl> selectByRteamid(String pfteamid) {
        return baseMapper.selectByRteamid(pfteamid);
    }

    @Override
    public void removeByRteamid(String pfteamid) {
        this.remove(new QueryWrapper<EMPlanTempl>().eq("rteamid",pfteamid));
    }


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMPlanTempl et){
        //实体关系[DER1N_EMPLANTEMPL_EMACCLASS_ACCLASSID]
        if(!ObjectUtils.isEmpty(et.getAcclassid())){
            cn.ibizlab.eam.core.eam_core.domain.EMACClass acclass=et.getAcclass();
            if(ObjectUtils.isEmpty(acclass)){
                cn.ibizlab.eam.core.eam_core.domain.EMACClass majorEntity=emacclassService.get(et.getAcclassid());
                et.setAcclass(majorEntity);
                acclass=majorEntity;
            }
            et.setAcclassname(acclass.getEmacclassname());
        }
        //实体关系[DER1N_EMPLANTEMPL_EMSERVICE_RSERVICEID]
        if(!ObjectUtils.isEmpty(et.getRserviceid())){
            cn.ibizlab.eam.core.eam_core.domain.EMService rservice=et.getRservice();
            if(ObjectUtils.isEmpty(rservice)){
                cn.ibizlab.eam.core.eam_core.domain.EMService majorEntity=emserviceService.get(et.getRserviceid());
                et.setRservice(majorEntity);
                rservice=majorEntity;
            }
            et.setRservicename(rservice.getEmservicename());
        }
        //实体关系[DER1N_EMPLANTEMPL_PFDEPT_RDEPTID]
        if(!ObjectUtils.isEmpty(et.getRdeptid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFDept rdept=et.getRdept();
            if(ObjectUtils.isEmpty(rdept)){
                cn.ibizlab.eam.core.eam_pf.domain.PFDept majorEntity=pfdeptService.get(et.getRdeptid());
                et.setRdept(majorEntity);
                rdept=majorEntity;
            }
            et.setRdeptname(rdept.getPfdeptname());
        }
        //实体关系[DER1N_EMPLANTEMPL_PFEMP_MPERSONID]
        if(!ObjectUtils.isEmpty(et.getMpersonid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp mperson=et.getMperson();
            if(ObjectUtils.isEmpty(mperson)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getMpersonid());
                et.setMperson(majorEntity);
                mperson=majorEntity;
            }
            et.setMpersonname(mperson.getPfempname());
        }
        //实体关系[DER1N_EMPLANTEMPL_PFEMP_RECVPERSONID]
        if(!ObjectUtils.isEmpty(et.getRecvpersonid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp recvperson=et.getRecvperson();
            if(ObjectUtils.isEmpty(recvperson)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getRecvpersonid());
                et.setRecvperson(majorEntity);
                recvperson=majorEntity;
            }
            et.setRecvpersonname(recvperson.getPfempname());
        }
        //实体关系[DER1N_EMPLANTEMPL_PFEMP_REMPID]
        if(!ObjectUtils.isEmpty(et.getRempid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp remp=et.getRemp();
            if(ObjectUtils.isEmpty(remp)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getRempid());
                et.setRemp(majorEntity);
                remp=majorEntity;
            }
            et.setRempname(remp.getPfempname());
        }
        //实体关系[DER1N_EMPLANTEMPL_PFTEAM_RTEAMID]
        if(!ObjectUtils.isEmpty(et.getRteamid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFTeam rteam=et.getRteam();
            if(ObjectUtils.isEmpty(rteam)){
                cn.ibizlab.eam.core.eam_pf.domain.PFTeam majorEntity=pfteamService.get(et.getRteamid());
                et.setRteam(majorEntity);
                rteam=majorEntity;
            }
            et.setRteamname(rteam.getPfteamname());
        }
    }



    @Autowired
    cn.ibizlab.eam.core.eam_core.mapping.EMPlanTemplInheritMapping emplantemplInheritMapping;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMResRefObjService emresrefobjService;

    /**
     * 创建索引主实体数据
     * @param et
     */
    private void createIndexMajorEntityData(EMPlanTempl et){
        if(ObjectUtils.isEmpty(et.getEmplantemplid()))
            et.setEmplantemplid((String)et.getDefaultKey(true));
        cn.ibizlab.eam.core.eam_core.domain.EMResRefObj emresrefobj =emplantemplInheritMapping.toEmresrefobj(et);
        emresrefobj.set("emresrefobjtype","PLANTEMPL");
        emresrefobjService.create(emresrefobj);
    }

    @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<EMPlanTempl> getEmplantemplByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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

}



