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.EMItemTrade;
import cn.ibizlab.eam.core.eam_core.filter.EMItemTradeSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMItemTradeService;

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


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.eam.core.eam_core.mapper.EMItemTradeMapper;
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("EMItemTradeServiceImpl")
public class EMItemTradeServiceImpl extends ServiceImpl<EMItemTradeMapper, EMItemTrade> implements IEMItemTradeService {


    private cn.ibizlab.eam.core.eam_core.service.IEMItemTradeService emitemtradeService = this;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemService emitemService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMServiceService emserviceService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMStorePartService emstorepartService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMStoreService emstoreService;
    @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 boolean update(EMItemTrade et) {
        fillParentData(et);
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("emitemtradeid",et.getEmitemtradeid())))
            return false;
        CachedBeanCopier.copy(get(et.getEmitemtradeid()),et);
        return true;
    }

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

    @Override
    public boolean checkKey(EMItemTrade et) {
        return (!ObjectUtils.isEmpty(et.getEmitemtradeid()))&&(!Objects.isNull(this.getById(et.getEmitemtradeid())));
    }
    @Override
    @Transactional
    public boolean create(EMItemTrade et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et)))
            return false;
        CachedBeanCopier.copy(get(et.getEmitemtradeid()),et);
        return true;
    }

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

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

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

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

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

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

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

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

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


	@Override
    public List<EMItemTrade> selectByRid(String emitemtradeid) {
        return baseMapper.selectByRid(emitemtradeid);
    }

    @Override
    public void removeByRid(String emitemtradeid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("rid",emitemtradeid));
    }

	@Override
    public List<EMItemTrade> selectByItemid(String emitemid) {
        return baseMapper.selectByItemid(emitemid);
    }

    @Override
    public void removeByItemid(String emitemid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("itemid",emitemid));
    }

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

    @Override
    public void removeByLabserviceid(String emserviceid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("labserviceid",emserviceid));
    }

	@Override
    public List<EMItemTrade> selectByStorepartid(String emstorepartid) {
        return baseMapper.selectByStorepartid(emstorepartid);
    }

    @Override
    public void removeByStorepartid(String emstorepartid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("storepartid",emstorepartid));
    }

	@Override
    public List<EMItemTrade> selectByStoreid(String emstoreid) {
        return baseMapper.selectByStoreid(emstoreid);
    }

    @Override
    public void removeByStoreid(String emstoreid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("storeid",emstoreid));
    }

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

    @Override
    public void removeByDeptid(String pfdeptid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("deptid",pfdeptid));
    }

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

    @Override
    public void removeByAempid(String pfempid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("aempid",pfempid));
    }

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

    @Override
    public void removeBySempid(String pfempid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("sempid",pfempid));
    }

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

    @Override
    public void removeByTeamid(String pfteamid) {
        this.remove(new QueryWrapper<EMItemTrade>().eq("teamid",pfteamid));
    }


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

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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMItemTrade et){
        //实体关系[DER1N_EMITEMTRADE_EMITEMTRADE_RID]
        if(!ObjectUtils.isEmpty(et.getRid())){
            cn.ibizlab.eam.core.eam_core.domain.EMItemTrade r=et.getR();
            if(ObjectUtils.isEmpty(r)){
                cn.ibizlab.eam.core.eam_core.domain.EMItemTrade majorEntity=emitemtradeService.get(et.getRid());
                et.setR(majorEntity);
                r=majorEntity;
            }
            et.setRname(r.getEmitemtradename());
        }
        //实体关系[DER1N_EMITEMTRADE_EMITEM_ITEMID]
        if(!ObjectUtils.isEmpty(et.getItemid())){
            cn.ibizlab.eam.core.eam_core.domain.EMItem item=et.getItem();
            if(ObjectUtils.isEmpty(item)){
                cn.ibizlab.eam.core.eam_core.domain.EMItem majorEntity=emitemService.get(et.getItemid());
                et.setItem(majorEntity);
                item=majorEntity;
            }
            et.setItemmtypeid(item.getItemmtypeid());
            et.setItembtypename(item.getItembtypename());
            et.setShfprice(item.getShfprice());
            et.setItembtypeid(item.getItembtypeid());
            et.setStockamount(item.getAmount());
            et.setItemcode(item.getItemcode());
            et.setItemname(item.getEmitemname());
            et.setItemmtypename(item.getItemmtypename());
            et.setItemtypeid(item.getItemtypeid());
        }
        //实体关系[DER1N_EMITEMTRADE_EMSERVICE_LABSERVICEID]
        if(!ObjectUtils.isEmpty(et.getLabserviceid())){
            cn.ibizlab.eam.core.eam_core.domain.EMService labservice=et.getLabservice();
            if(ObjectUtils.isEmpty(labservice)){
                cn.ibizlab.eam.core.eam_core.domain.EMService majorEntity=emserviceService.get(et.getLabserviceid());
                et.setLabservice(majorEntity);
                labservice=majorEntity;
            }
            et.setLabservicename(labservice.getEmservicename());
        }
        //实体关系[DER1N_EMITEMTRADE_EMSTOREPART_STOREPARTID]
        if(!ObjectUtils.isEmpty(et.getStorepartid())){
            cn.ibizlab.eam.core.eam_core.domain.EMStorePart storepart=et.getStorepart();
            if(ObjectUtils.isEmpty(storepart)){
                cn.ibizlab.eam.core.eam_core.domain.EMStorePart majorEntity=emstorepartService.get(et.getStorepartid());
                et.setStorepart(majorEntity);
                storepart=majorEntity;
            }
            et.setStorepartname(storepart.getEmstorepartname());
        }
        //实体关系[DER1N_EMITEMTRADE_EMSTORE_STOREID]
        if(!ObjectUtils.isEmpty(et.getStoreid())){
            cn.ibizlab.eam.core.eam_core.domain.EMStore store=et.getStore();
            if(ObjectUtils.isEmpty(store)){
                cn.ibizlab.eam.core.eam_core.domain.EMStore majorEntity=emstoreService.get(et.getStoreid());
                et.setStore(majorEntity);
                store=majorEntity;
            }
            et.setStorename(store.getEmstorename());
        }
        //实体关系[DER1N_EMITEMTRADE_PFDEPT_DEPTID]
        if(!ObjectUtils.isEmpty(et.getDeptid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFDept dept=et.getDept();
            if(ObjectUtils.isEmpty(dept)){
                cn.ibizlab.eam.core.eam_pf.domain.PFDept majorEntity=pfdeptService.get(et.getDeptid());
                et.setDept(majorEntity);
                dept=majorEntity;
            }
            et.setSdept(dept.getSdept());
            et.setDeptname(dept.getPfdeptname());
        }
        //实体关系[DER1N_EMITEMTRADE_PFEMP_AEMPID]
        if(!ObjectUtils.isEmpty(et.getAempid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp aemp=et.getAemp();
            if(ObjectUtils.isEmpty(aemp)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getAempid());
                et.setAemp(majorEntity);
                aemp=majorEntity;
            }
            et.setAempname(aemp.getPfempname());
        }
        //实体关系[DER1N_EMITEMTRADE_PFEMP_SEMPID]
        if(!ObjectUtils.isEmpty(et.getSempid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp semp=et.getSemp();
            if(ObjectUtils.isEmpty(semp)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getSempid());
                et.setSemp(majorEntity);
                semp=majorEntity;
            }
            et.setSempname(semp.getPfempname());
        }
        //实体关系[DER1N_EMITEMTRADE_PFTEAM_TEAMID]
        if(!ObjectUtils.isEmpty(et.getTeamid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFTeam team=et.getTeam();
            if(ObjectUtils.isEmpty(team)){
                cn.ibizlab.eam.core.eam_pf.domain.PFTeam majorEntity=pfteamService.get(et.getTeamid());
                et.setTeam(majorEntity);
                team=majorEntity;
            }
            et.setTeamname(team.getPfteamname());
        }
    }




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

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

}



