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.EMEQCheck;
import cn.ibizlab.eam.core.eam_core.filter.EMEQCheckSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMEQCheckService;

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


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

    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMACClassService emacclassService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEquipService emequipService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMObjectService emobjectService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMRFOACService emrfoacService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMRFOCAService emrfocaService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMRFODEService emrfodeService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMRFOMOService emrfomoService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMServiceService emserviceService;
    @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 save(EMEQCheck et) {
        if(!saveOrUpdate(et))
            return false;
        return true;
    }

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

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

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

    @Override
    @Transactional
    public boolean update(EMEQCheck et) {
        fillParentData(et);
        emeqahService.update(emeqcheckInheritMapping.toEmeqah(et));
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("emeqcheckid",et.getEmeqcheckid())))
            return false;
        CachedBeanCopier.copy(get(et.getEmeqcheckid()),et);
        return true;
    }

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

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

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

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

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

    @Override
    public boolean checkKey(EMEQCheck et) {
        return (!ObjectUtils.isEmpty(et.getEmeqcheckid()))&&(!Objects.isNull(this.getById(et.getEmeqcheckid())));
    }
    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result=removeById(key);
        emeqahService.remove(key);
        return result ;
    }

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    @Override
    public void removeByRdeptid(String pfdeptid) {
        this.remove(new QueryWrapper<EMEQCheck>().eq("rdeptid",pfdeptid));
    }

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

    @Override
    public void removeByRempid(String pfempid) {
        this.remove(new QueryWrapper<EMEQCheck>().eq("rempid",pfempid));
    }

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

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


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMEQCheck et){
        //实体关系[DER1N_EMEQCHECK_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_EMEQCHECK_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.setEquipgroup(equip.getEquipgroup());
            et.setEquipname(equip.getEmequipname());
        }
        //实体关系[DER1N_EMEQCHECK_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_EMEQCHECK_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_EMEQCHECK_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_EMEQCHECK_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_EMEQCHECK_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_EMEQCHECK_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_EMEQCHECK_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_EMEQCHECK_PFDEPT_RDEPTID]
        if(!ObjectUtils.isEmpty(et.getRdeptid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFDept rdept=et.getRdept();
            if(ObjectUtils.isEmpty(rdept)){
                cn.ibizlab.eam.core.eam_pf.domain.PFDept majorEntity=pfdeptService.get(et.getRdeptid());
                et.setRdept(majorEntity);
                rdept=majorEntity;
            }
            et.setRdeptname(rdept.getPfdeptname());
        }
        //实体关系[DER1N_EMEQCHECK_PFEMP_REMPID]
        if(!ObjectUtils.isEmpty(et.getRempid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp remp=et.getRemp();
            if(ObjectUtils.isEmpty(remp)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getRempid());
                et.setRemp(majorEntity);
                remp=majorEntity;
            }
            et.setRempname(remp.getPfempname());
        }
        //实体关系[DER1N_EMEQCHECK_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());
        }
    }



    @Autowired
    cn.ibizlab.eam.core.eam_core.mapping.EMEQCheckInheritMapping emeqcheckInheritMapping;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEQAHService emeqahService;

    /**
     * 创建索引主实体数据
     * @param et
     */
    private void createIndexMajorEntityData(EMEQCheck et){
        if(ObjectUtils.isEmpty(et.getEmeqcheckid()))
            et.setEmeqcheckid((String)et.getDefaultKey(true));
        cn.ibizlab.eam.core.eam_core.domain.EMEQAH emeqah =emeqcheckInheritMapping.toEmeqah(et);
        emeqah.set("emeqahtype","CHECK");
        emeqahService.create(emeqah);
    }

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

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

}



