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.EMItemPUse;
import cn.ibizlab.eam.core.eam_core.filter.EMItemPUseSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMItemPUseService;

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


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

    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEIBatteryService emeibatteryService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEICamService emeicamService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEICellService emeicellService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEITIResService emeitiresService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEIToolService emeitoolService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemPRtnService emitemprtnService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMJYJLService emjyjlService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMPurchangeHisService empurchangehisService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMRiggingHService emrigginghService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMRiggingService emriggingService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEquipService emequipService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemService emitemService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMObjectService emobjectService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMPurPlanService empurplanService;
    @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_core.service.IEMWOService emwoService;
    @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(EMItemPUse et) {
        fillParentData(et);
        emitemtradeService.update(emitempuseInheritMapping.toEmitemtrade(et));
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("emitempuseid",et.getEmitempuseid())))
            return false;
        CachedBeanCopier.copy(get(et.getEmitempuseid()),et);
        return true;
    }

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

    @Override
    public boolean checkKey(EMItemPUse et) {
        return (!ObjectUtils.isEmpty(et.getEmitempuseid()))&&(!Objects.isNull(this.getById(et.getEmitempuseid())));
    }
    @Override
    public EMItemPUse getDraft(EMItemPUse et) {
        fillParentData(et);
        return et;
    }

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

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

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

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

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

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

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

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

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


	@Override
    public List<EMItemPUse> selectByEquipid(String emequipid) {
        return baseMapper.selectByEquipid(emequipid);
    }

    @Override
    public void removeByEquipid(String emequipid) {
        this.remove(new QueryWrapper<EMItemPUse>().eq("equipid",emequipid));
    }

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

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

	@Override
    public List<EMItemPUse> selectByObjid(String emobjectid) {
        return baseMapper.selectByObjid(emobjectid);
    }

    @Override
    public void removeByObjid(String emobjectid) {
        this.remove(new QueryWrapper<EMItemPUse>().eq("objid",emobjectid));
    }

	@Override
    public List<EMItemPUse> selectByPurplanid(String empurplanid) {
        return baseMapper.selectByPurplanid(empurplanid);
    }

    @Override
    public void removeByPurplanid(String empurplanid) {
        this.remove(new QueryWrapper<EMItemPUse>().eq("purplanid",empurplanid));
    }

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

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

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

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

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

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

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

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

	@Override
    public List<EMItemPUse> selectByWoid(String emwoid) {
        return baseMapper.selectByWoid(emwoid);
    }

    @Override
    public void removeByWoid(String emwoid) {
        this.remove(new QueryWrapper<EMItemPUse>().eq("woid",emwoid));
    }

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

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

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

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

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

    @Override
    public void removeByApprempid(String pfempid) {
        this.remove(new QueryWrapper<EMItemPUse>().eq("apprempid",pfempid));
    }

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

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

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

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

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

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


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMItemPUse et){
        //实体关系[DER1N_EMITEMPUSE_EMEQUIP_EQUIPID]
        if(!ObjectUtils.isEmpty(et.getEquipid())){
            cn.ibizlab.eam.core.eam_core.domain.EMEquip equip=et.getEquip();
            if(ObjectUtils.isEmpty(equip)){
                cn.ibizlab.eam.core.eam_core.domain.EMEquip majorEntity=emequipService.get(et.getEquipid());
                et.setEquip(majorEntity);
                equip=majorEntity;
            }
            et.setEquipname(equip.getEmequipname());
        }
        //实体关系[DER1N_EMITEMPUSE_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.setLife(item.getLife());
            et.setUnitname(item.getUnitname());
            et.setUnitid(item.getUnitid());
            et.setItembtypeid(item.getItembtypeid());
            et.setItemgroup(item.getItemgroup());
            et.setAvgprice(item.getPrice());
            et.setItemname(item.getEmitemname());
        }
        //实体关系[DER1N_EMITEMPUSE_EMOBJECT_OBJID]
        if(!ObjectUtils.isEmpty(et.getObjid())){
            cn.ibizlab.eam.core.eam_core.domain.EMObject obj=et.getObj();
            if(ObjectUtils.isEmpty(obj)){
                cn.ibizlab.eam.core.eam_core.domain.EMObject majorEntity=emobjectService.get(et.getObjid());
                et.setObj(majorEntity);
                obj=majorEntity;
            }
            et.setObjname(obj.getEmobjectname());
        }
        //实体关系[DER1N_EMITEMPUSE_EMPURPLAN_PURPLANID]
        if(!ObjectUtils.isEmpty(et.getPurplanid())){
            cn.ibizlab.eam.core.eam_core.domain.EMPurPlan purplan=et.getPurplan();
            if(ObjectUtils.isEmpty(purplan)){
                cn.ibizlab.eam.core.eam_core.domain.EMPurPlan majorEntity=empurplanService.get(et.getPurplanid());
                et.setPurplan(majorEntity);
                purplan=majorEntity;
            }
            et.setPurplanname(purplan.getEmpurplanname());
        }
        //实体关系[DER1N_EMITEMPUSE_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_EMITEMPUSE_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_EMITEMPUSE_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_EMITEMPUSE_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_EMITEMPUSE_EMWO_WOID]
        if(!ObjectUtils.isEmpty(et.getWoid())){
            cn.ibizlab.eam.core.eam_core.domain.EMWO wo=et.getWo();
            if(ObjectUtils.isEmpty(wo)){
                cn.ibizlab.eam.core.eam_core.domain.EMWO majorEntity=emwoService.get(et.getWoid());
                et.setWo(majorEntity);
                wo=majorEntity;
            }
            et.setWoname(wo.getEmwoname());
        }
        //实体关系[DER1N_EMITEMPUSE_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_EMITEMPUSE_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_EMITEMPUSE_PFEMP_APPREMPID]
        if(!ObjectUtils.isEmpty(et.getApprempid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp appremp=et.getAppremp();
            if(ObjectUtils.isEmpty(appremp)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getApprempid());
                et.setAppremp(majorEntity);
                appremp=majorEntity;
            }
            et.setApprempname(appremp.getPfempname());
        }
        //实体关系[DER1N_EMITEMPUSE_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_EMITEMPUSE_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_EMITEMPUSE_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());
        }
    }



    @Autowired
    cn.ibizlab.eam.core.eam_core.mapping.EMItemPUseInheritMapping emitempuseInheritMapping;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMItemTradeService emitemtradeService;

    /**
     * 创建索引主实体数据
     * @param et
     */
    private void createIndexMajorEntityData(EMItemPUse et){
        if(ObjectUtils.isEmpty(et.getEmitempuseid()))
            et.setEmitempuseid((String)et.getDefaultKey(true));
        cn.ibizlab.eam.core.eam_core.domain.EMItemTrade emitemtrade =emitempuseInheritMapping.toEmitemtrade(et);
        emitemtrade.set("emitemtradetype","PUSE");
        emitemtradeService.create(emitemtrade);
    }

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

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

}



