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
    private cn.ibizlab.eam.core.eam_core.service.IEMEIGSJRBService emeigsjrbService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMENService emenService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEQSpareDetailService emeqsparedetailService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemCSService emitemcsService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemPLService emitemplService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemPRtnService emitemprtnService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemPUseService emitempuseService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemRInService emitemrinService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemROutService emitemroutService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemSubMapService emitemsubmapService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemTradeService emitemtradeService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMJYJLService emjyjlService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMPODetailService empodetailService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMProductService emproductService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMResItemService emresitemService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMStockService emstockService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMWPListCostService emwplistcostService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMWPListService emwplistService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMACClassService emacclassService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMCabService emcabService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemTypeService emitemtypeService;
    @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.IPFEmpService pfempService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_pf.service.IPFUnitService pfunitService;

    private int batchSize = 500;

    @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 EMItem get(String key) {
        EMItem et = getById(key);
        if(et==null){
            et=new EMItem();
            et.setEmitemid(key);
        }
        else{
        }
        return et;
    }

    @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 void saveBatch(List<EMItem> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
    }

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

    @Override
    @Transactional
    public boolean update(EMItem et) {
        fillParentData(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 create(EMItem et) {
        fillParentData(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
    public boolean checkKey(EMItem et) {
        return (!ObjectUtils.isEmpty(et.getEmitemid()))&&(!Objects.isNull(this.getById(et.getEmitemid())));
    }


	@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> selectByEmpid(String pfempid) {
        return baseMapper.selectByEmpid(pfempid);
    }

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

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

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

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

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

	@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.getEmitemtypename());
        }
        //实体关系[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_PFEMP_EMPID]
        if(!ObjectUtils.isEmpty(et.getEmpid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp emp=et.getEmp();
            if(ObjectUtils.isEmpty(emp)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getEmpid());
                et.setEmp(majorEntity);
                emp=majorEntity;
            }
            et.setEmpname(emp.getPfempname());
        }
        //实体关系[DER1N_EMITEM_PFEMP_LASTAEMPID]
        if(!ObjectUtils.isEmpty(et.getLastaempid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp lastaemp=et.getLastaemp();
            if(ObjectUtils.isEmpty(lastaemp)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getLastaempid());
                et.setLastaemp(majorEntity);
                lastaemp=majorEntity;
            }
            et.setLastaempname(lastaemp.getPfempname());
        }
        //实体关系[DER1N_EMITEM_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_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());
        }
    }

    @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;
    }

}


