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.EMWO;
import cn.ibizlab.eam.core.eam_core.filter.EMWOSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMWOService;

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


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

    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMDPRCTService emdprctService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMENConsumService emenconsumService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQAHService emeqahService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQCheckService emeqcheckService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQDebugService emeqdebugService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQKeepService emeqkeepService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQKPRCDService emeqkprcdService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQMaintanceService emeqmaintanceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQMonitorService emeqmonitorService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQMPMTRService emeqmpmtrService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQSetupService emeqsetupService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEQWLService emeqwlService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemPUseService emitempuseService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMOutputRctService emoutputrctService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWO_DPService emwoDpService;

    protected cn.ibizlab.eam.core.eam_core.service.IEMWOService emwoService = this;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWO_ENService emwoEnService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWO_INNERService emwoInnerService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWO_OSCService emwoOscService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWO_PTService emwoPtService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMACClassService emacclassService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEquipService emequipService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMObjectService emobjectService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMRFOACService emrfoacService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMRFOCAService emrfocaService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMRFODEService emrfodeService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMRFOMOService emrfomoService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMServiceService emserviceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWOORIService emwooriService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFTeamService pfteamService;

    protected int batchSize = 500;

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

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

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

    @Override
    public void updateBatch(List<EMWO> 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 EMWO get(String key) {
        EMWO et = getById(key);
        if(et==null){
            et=new EMWO();
            et.setEmwoid(key);
        }
        else{
        }
        return et;
    }

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

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

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

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

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


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

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

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

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

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

    @Override
    public void removeByDpid(String emobjectid) {
        this.remove(new QueryWrapper<EMWO>().eq("dpid",emobjectid));
    }

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

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

	@Override
    public List<EMWO> selectByRfoacid(String emrfoacid) {
        return baseMapper.selectByRfoacid(emrfoacid);
    }

    @Override
    public void removeByRfoacid(String emrfoacid) {
        this.remove(new QueryWrapper<EMWO>().eq("rfoacid",emrfoacid));
    }

	@Override
    public List<EMWO> selectByRfocaid(String emrfocaid) {
        return baseMapper.selectByRfocaid(emrfocaid);
    }

    @Override
    public void removeByRfocaid(String emrfocaid) {
        this.remove(new QueryWrapper<EMWO>().eq("rfocaid",emrfocaid));
    }

	@Override
    public List<EMWO> selectByRfodeid(String emrfodeid) {
        return baseMapper.selectByRfodeid(emrfodeid);
    }

    @Override
    public void removeByRfodeid(String emrfodeid) {
        this.remove(new QueryWrapper<EMWO>().eq("rfodeid",emrfodeid));
    }

	@Override
    public List<EMWO> selectByRfomoid(String emrfomoid) {
        return baseMapper.selectByRfomoid(emrfomoid);
    }

    @Override
    public void removeByRfomoid(String emrfomoid) {
        this.remove(new QueryWrapper<EMWO>().eq("rfomoid",emrfomoid));
    }

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

    @Override
    public void removeByRserviceid(String emserviceid) {
        this.remove(new QueryWrapper<EMWO>().eq("rserviceid",emserviceid));
    }

	@Override
    public List<EMWO> selectByWooriid(String emwooriid) {
        return baseMapper.selectByWooriid(emwooriid);
    }

    @Override
    public void removeByWooriid(String emwooriid) {
        this.remove(new QueryWrapper<EMWO>().eq("wooriid",emwooriid));
    }

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

    @Override
    public void removeByWopid(String emwoid) {
        this.remove(new QueryWrapper<EMWO>().eq("wopid",emwoid));
    }

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

    @Override
    public void removeByRteamid(String pfteamid) {
        this.remove(new QueryWrapper<EMWO>().eq("rteamid",pfteamid));
    }


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

    /**
     * 查询集合 设备年度工单数量
     */
    @Override
    public Page<HashMap> searchEQYearWO(EMWOSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<HashMap> pages=baseMapper.searchEQYearWO(context.getPages(),context,context.getSelectCond());
        return new PageImpl<HashMap>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

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

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

    /**
     * 查询集合 工单种类数量
     */
    @Override
    public Page<HashMap> searchWoTypeNum(EMWOSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<HashMap> pages=baseMapper.searchWoTypeNum(context.getPages(),context,context.getSelectCond());
        return new PageImpl<HashMap>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 年度计划生成工单数量
     */
    @Override
    public Page<HashMap> searchYearWONumByPlan(EMWOSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<HashMap> pages=baseMapper.searchYearWONumByPlan(context.getPages(),context,context.getSelectCond());
        return new PageImpl<HashMap>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMWO et){
        //实体关系[DER1N_EMWO_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_EMWO_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.setEquipcode(equip.getEquipcode());
            et.setEquipname(equip.getEquipinfo());
            et.setStype(equip.getStype());
            et.setSname(equip.getSname());
        }
        //实体关系[DER1N_EMWO_EMOBJECT_DPID]
        if(!ObjectUtils.isEmpty(et.getDpid())){
            cn.ibizlab.eam.core.eam_core.domain.EMObject dp=et.getDp();
            if(ObjectUtils.isEmpty(dp)){
                cn.ibizlab.eam.core.eam_core.domain.EMObject majorEntity=emobjectService.get(et.getDpid());
                et.setDp(majorEntity);
                dp=majorEntity;
            }
            et.setDptype(dp.getEmobjecttype());
            et.setDpname(dp.getEmobjectname());
        }
        //实体关系[DER1N_EMWO_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_EMWO_EMRFOAC_RFOACID]
        if(!ObjectUtils.isEmpty(et.getRfoacid())){
            cn.ibizlab.eam.core.eam_core.domain.EMRFOAC rfoac=et.getRfoac();
            if(ObjectUtils.isEmpty(rfoac)){
                cn.ibizlab.eam.core.eam_core.domain.EMRFOAC majorEntity=emrfoacService.get(et.getRfoacid());
                et.setRfoac(majorEntity);
                rfoac=majorEntity;
            }
            et.setRfoacname(rfoac.getEmrfoacname());
        }
        //实体关系[DER1N_EMWO_EMRFOCA_RFOCAID]
        if(!ObjectUtils.isEmpty(et.getRfocaid())){
            cn.ibizlab.eam.core.eam_core.domain.EMRFOCA rfoca=et.getRfoca();
            if(ObjectUtils.isEmpty(rfoca)){
                cn.ibizlab.eam.core.eam_core.domain.EMRFOCA majorEntity=emrfocaService.get(et.getRfocaid());
                et.setRfoca(majorEntity);
                rfoca=majorEntity;
            }
            et.setRfocaname(rfoca.getEmrfocaname());
        }
        //实体关系[DER1N_EMWO_EMRFODE_RFODEID]
        if(!ObjectUtils.isEmpty(et.getRfodeid())){
            cn.ibizlab.eam.core.eam_core.domain.EMRFODE rfode=et.getRfode();
            if(ObjectUtils.isEmpty(rfode)){
                cn.ibizlab.eam.core.eam_core.domain.EMRFODE majorEntity=emrfodeService.get(et.getRfodeid());
                et.setRfode(majorEntity);
                rfode=majorEntity;
            }
            et.setRfodename(rfode.getEmrfodename());
        }
        //实体关系[DER1N_EMWO_EMRFOMO_RFOMOID]
        if(!ObjectUtils.isEmpty(et.getRfomoid())){
            cn.ibizlab.eam.core.eam_core.domain.EMRFOMO rfomo=et.getRfomo();
            if(ObjectUtils.isEmpty(rfomo)){
                cn.ibizlab.eam.core.eam_core.domain.EMRFOMO majorEntity=emrfomoService.get(et.getRfomoid());
                et.setRfomo(majorEntity);
                rfomo=majorEntity;
            }
            et.setRfomoname(rfomo.getEmrfomoname());
        }
        //实体关系[DER1N_EMWO_EMSERVICE_RSERVICEID]
        if(!ObjectUtils.isEmpty(et.getRserviceid())){
            cn.ibizlab.eam.core.eam_core.domain.EMService rservice=et.getRservice();
            if(ObjectUtils.isEmpty(rservice)){
                cn.ibizlab.eam.core.eam_core.domain.EMService majorEntity=emserviceService.get(et.getRserviceid());
                et.setRservice(majorEntity);
                rservice=majorEntity;
            }
            et.setRservicename(rservice.getEmservicename());
        }
        //实体关系[DER1N_EMWO_EMWOORI_WOORIID]
        if(!ObjectUtils.isEmpty(et.getWooriid())){
            cn.ibizlab.eam.core.eam_core.domain.EMWOORI woori=et.getWoori();
            if(ObjectUtils.isEmpty(woori)){
                cn.ibizlab.eam.core.eam_core.domain.EMWOORI majorEntity=emwooriService.get(et.getWooriid());
                et.setWoori(majorEntity);
                woori=majorEntity;
            }
            et.setWooriname(woori.getEmwooriname());
            et.setWooritype(woori.getEmwooritype());
        }
        //实体关系[DER1N_EMWO_EMWO_WOPID]
        if(!ObjectUtils.isEmpty(et.getWopid())){
            cn.ibizlab.eam.core.eam_core.domain.EMWO wop=et.getWop();
            if(ObjectUtils.isEmpty(wop)){
                cn.ibizlab.eam.core.eam_core.domain.EMWO majorEntity=emwoService.get(et.getWopid());
                et.setWop(majorEntity);
                wop=majorEntity;
            }
            et.setWopname(wop.getEmwoname());
        }
        //实体关系[DER1N_EMWO_PFTEAM_RTEAMID]
        if(!ObjectUtils.isEmpty(et.getRteamid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFTeam rteam=et.getRteam();
            if(ObjectUtils.isEmpty(rteam)){
                cn.ibizlab.eam.core.eam_pf.domain.PFTeam majorEntity=pfteamService.get(et.getRteamid());
                et.setRteam(majorEntity);
                rteam=majorEntity;
            }
            et.setRteamname(rteam.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<EMWO> getEmwoByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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

}


