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.EMPODetail;
import cn.ibizlab.eam.core.eam_core.filter.EMPODetailSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMPODetailService;

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


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

    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemRInService emitemrinService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemService emitemService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMPOService empoService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWPListService emwplistService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFUnitService pfunitService;

    protected int batchSize = 500;

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

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

    @Override
    @Transactional
    public boolean update(EMPODetail et) {
        fillParentData(et);
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("empodetailid",et.getEmpodetailid())))
            return false;
        CachedBeanCopier.copy(get(et.getEmpodetailid()),et);
        return true;
    }

    @Override
    public void updateBatch(List<EMPODetail> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(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 EMPODetail get(String key) {
        EMPODetail et = getById(key);
        if(et==null){
            et=new EMPODetail();
            et.setEmpodetailid(key);
        }
        else{
        }
        return et;
    }

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

    @Override
    @Transactional
    public EMPODetail check(EMPODetail et) {
        //自定义代码
        return et;
    }

    @Override
    public boolean checkKey(EMPODetail et) {
        return (!ObjectUtils.isEmpty(et.getEmpodetailid()))&&(!Objects.isNull(this.getById(et.getEmpodetailid())));
    }
    @Override
    @Transactional
    public EMPODetail createRin(EMPODetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public EMPODetail genId(EMPODetail et) {
        //自定义代码
        return et;
    }

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

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

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

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


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

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

	@Override
    public List<EMPODetail> selectByPoid(String empoid) {
        return baseMapper.selectByPoid(empoid);
    }

    @Override
    public void removeByPoid(String empoid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("poid",empoid));
    }

	@Override
    public List<EMPODetail> selectByWplistid(String emwplistid) {
        return baseMapper.selectByWplistid(emwplistid);
    }

    @Override
    public void removeByWplistid(String emwplistid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("wplistid",emwplistid));
    }

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

    @Override
    public void removeByRunitid(String pfunitid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("runitid",pfunitid));
    }

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

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


    /**
     * 查询集合 已关闭
     */
    @Override
    public Page<EMPODetail> searchClosed(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMPODetail> pages=baseMapper.searchClosed(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMPODetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

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

    /**
     * 查询集合 近五年采购
     */
    @Override
    public Page<HashMap> searchLaterYear(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<HashMap> pages=baseMapper.searchLaterYear(context.getPages(),context,context.getSelectCond());
        return new PageImpl<HashMap>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 待记账
     */
    @Override
    public Page<EMPODetail> searchWaitBook(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMPODetail> pages=baseMapper.searchWaitBook(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMPODetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 待验收
     */
    @Override
    public Page<EMPODetail> searchWaitCheck(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMPODetail> pages=baseMapper.searchWaitCheck(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMPODetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMPODetail et){
        //实体关系[DER1N_EMPODETAIL_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.setSunitid(item.getUnitid());
            et.setSunitname(item.getUnitname());
            et.setItemname(item.getEmitemname());
            et.setAvgprice(item.getPrice());
            et.setItembtypeid(item.getItembtypeid());
        }
        //实体关系[DER1N_EMPODETAIL_EMPO_POID]
        if(!ObjectUtils.isEmpty(et.getPoid())){
            cn.ibizlab.eam.core.eam_core.domain.EMPO po=et.getPo();
            if(ObjectUtils.isEmpty(po)){
                cn.ibizlab.eam.core.eam_core.domain.EMPO majorEntity=empoService.get(et.getPoid());
                et.setPo(majorEntity);
                po=majorEntity;
            }
            et.setLabservicename(po.getLabservicename());
            et.setPorempname(po.getRempname());
            et.setPowfstep(po.getWfstep());
            et.setPorempid(po.getRempid());
            et.setLabserviceid(po.getLabserviceid());
            et.setPostate(po.getPostate());
            et.setPoname(po.getEmponame());
        }
        //实体关系[DER1N_EMPODETAIL_EMWPLIST_WPLISTID]
        if(!ObjectUtils.isEmpty(et.getWplistid())){
            cn.ibizlab.eam.core.eam_core.domain.EMWPList wplist=et.getWplist();
            if(ObjectUtils.isEmpty(wplist)){
                cn.ibizlab.eam.core.eam_core.domain.EMWPList majorEntity=emwplistService.get(et.getWplistid());
                et.setWplist(majorEntity);
                wplist=majorEntity;
            }
            et.setUseto(wplist.getUseto());
            et.setObjid(wplist.getObjid());
            et.setEquips(wplist.getEquips());
            et.setAempid(wplist.getAempid());
            et.setEquipid(wplist.getEquipid());
            et.setWplistname(wplist.getEmwplistname());
            et.setTeamid(wplist.getTeamid());
            et.setObjname(wplist.getObjname());
            et.setEquipname(wplist.getEquipname());
            et.setDeptid(wplist.getDeptid());
        }
        //实体关系[DER1N_EMPODETAIL_PFUNIT_RUNITID]
        if(!ObjectUtils.isEmpty(et.getRunitid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFUnit runit=et.getRunit();
            if(ObjectUtils.isEmpty(runit)){
                cn.ibizlab.eam.core.eam_pf.domain.PFUnit majorEntity=pfunitService.get(et.getRunitid());
                et.setRunit(majorEntity);
                runit=majorEntity;
            }
            et.setRunitname(runit.getPfunitname());
        }
        //实体关系[DER1N_EMPODETAIL_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;
    }

    @Override
    public List<EMPODetail> getEmpodetailByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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

}


