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.EMItem;
import cn.ibizlab.eam.core.eam_core.filter.EMItemSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMItemService;

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


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

    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEIGSJRBService emeigsjrbService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMENService emenService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQSpareDetailService emeqsparedetailService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemCSService emitemcsService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemPLService emitemplService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemPRtnService emitemprtnService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemPUseService emitempuseService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemRInService emitemrinService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemROutService emitemroutService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemSubMapService emitemsubmapService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemTradeService emitemtradeService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMJYJLService emjyjlService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMPODetailService empodetailService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMProductService emproductService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMResItemService emresitemService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMStockService emstockService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWPListCostService emwplistcostService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWPListService emwplistService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMACClassService emacclassService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMCabService emcabService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemTypeService emitemtypeService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMServiceService emserviceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMStorePartService emstorepartService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMStoreService emstoreService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFUnitService pfunitService;

    protected int batchSize = 500;

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

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

    @Override
    @Transactional
    public boolean update(EMItem et) {
        fillParentData(et);
        emobjectService.update(emitemInheritMapping.toEmobject(et));
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("emitemid",et.getEmitemid())))
            return false;
        CachedBeanCopier.copy(get(et.getEmitemid()),et);
        return true;
    }

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

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

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

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

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

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

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

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

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


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

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

	@Override
    public List<EMItem> selectByEmcabid(String emcabid) {
        return baseMapper.selectByEmcabid(emcabid);
    }

    @Override
    public void removeByEmcabid(String emcabid) {
        this.remove(new QueryWrapper<EMItem>().eq("emcabid",emcabid));
    }

	@Override
    public List<EMItem> selectByItemtypeid(String emitemtypeid) {
        return baseMapper.selectByItemtypeid(emitemtypeid);
    }

    @Override
    public void removeByItemtypeid(String emitemtypeid) {
        this.remove(new QueryWrapper<EMItem>().eq("itemtypeid",emitemtypeid));
    }

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

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

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

    @Override
    public void removeByMserviceid(String emserviceid) {
        this.remove(new QueryWrapper<EMItem>().eq("mserviceid",emserviceid));
    }

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

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

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

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

	@Override
    public List<EMItem> selectByUnitid(String pfunitid) {
        return baseMapper.selectByUnitid(pfunitid);
    }

    @Override
    public void removeByUnitid(String pfunitid) {
        this.remove(new QueryWrapper<EMItem>().eq("unitid",pfunitid));
    }


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

    /**
     * 查询集合 类型树物品
     */
    @Override
    public Page<EMItem> searchItemTypeTree(EMItemSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMItem> pages=baseMapper.searchItemTypeTree(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMItem>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMItem et){
        //实体关系[DER1N_EMITEM_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_EMITEM_EMCAB_EMCABID]
        if(!ObjectUtils.isEmpty(et.getEmcabid())){
            cn.ibizlab.eam.core.eam_core.domain.EMCab emcab=et.getEmcab();
            if(ObjectUtils.isEmpty(emcab)){
                cn.ibizlab.eam.core.eam_core.domain.EMCab majorEntity=emcabService.get(et.getEmcabid());
                et.setEmcab(majorEntity);
                emcab=majorEntity;
            }
            et.setEmcabname(emcab.getEmcabname());
        }
        //实体关系[DER1N_EMITEM_EMITEMTYPE_ITEMTYPEID]
        if(!ObjectUtils.isEmpty(et.getItemtypeid())){
            cn.ibizlab.eam.core.eam_core.domain.EMItemType itemtype=et.getItemtype();
            if(ObjectUtils.isEmpty(itemtype)){
                cn.ibizlab.eam.core.eam_core.domain.EMItemType majorEntity=emitemtypeService.get(et.getItemtypeid());
                et.setItemtype(majorEntity);
                itemtype=majorEntity;
            }
            et.setItemmtypeid(itemtype.getItemmtypeid());
            et.setItembtypename(itemtype.getItembtypename());
            et.setItembtypeid(itemtype.getItembtypeid());
            et.setItemtypecode(itemtype.getItemtypecode());
            et.setItemmtypename(itemtype.getItemmtypename());
            et.setItemtypename(itemtype.getItemtypeinfo());
        }
        //实体关系[DER1N_EMITEM_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_EMITEM_EMSERVICE_MSERVICEID]
        if(!ObjectUtils.isEmpty(et.getMserviceid())){
            cn.ibizlab.eam.core.eam_core.domain.EMService mservice=et.getMservice();
            if(ObjectUtils.isEmpty(mservice)){
                cn.ibizlab.eam.core.eam_core.domain.EMService majorEntity=emserviceService.get(et.getMserviceid());
                et.setMservice(majorEntity);
                mservice=majorEntity;
            }
            et.setMservicename(mservice.getEmservicename());
        }
        //实体关系[DER1N_EMITEM_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_EMITEM_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());
            et.setStorecode(store.getStorecode());
        }
        //实体关系[DER1N_EMITEM_PFUNIT_UNITID]
        if(!ObjectUtils.isEmpty(et.getUnitid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFUnit unit=et.getUnit();
            if(ObjectUtils.isEmpty(unit)){
                cn.ibizlab.eam.core.eam_pf.domain.PFUnit majorEntity=pfunitService.get(et.getUnitid());
                et.setUnit(majorEntity);
                unit=majorEntity;
            }
            et.setUnitname(unit.getPfunitname());
        }
    }



    @Autowired
    cn.ibizlab.eam.core.eam_core.mapping.EMItemInheritMapping emitemInheritMapping;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMObjectService emobjectService;

    /**
     * 创建索引主实体数据
     * @param et
     */
    private void createIndexMajorEntityData(EMItem et){
        if(ObjectUtils.isEmpty(et.getEmitemid()))
            et.setEmitemid((String)et.getDefaultKey(true));
        cn.ibizlab.eam.core.eam_core.domain.EMObject emobject =emitemInheritMapping.toEmobject(et);
        emobject.set("emobjecttype","ITEM");
        emobjectService.create(emobject);
    }

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

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

}


