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.EMAsset;
import cn.ibizlab.eam.core.eam_core.filter.EMAssetSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMAssetService;

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


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

    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMAssetClearService emassetclearService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMAssetHistService emassethistService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEquipService emequipService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMACClassService emacclassService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMAssetClassService emassetclassService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMEQLocationService emeqlocationService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_core.service.IEMServiceService emserviceService;
    @Autowired
    @Lazy
    private cn.ibizlab.eam.core.eam_pf.service.IPFContractService pfcontractService;
    @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.IPFUnitService pfunitService;

    private int batchSize = 500;

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

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

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

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

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

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

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

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

    @Override
    public void createBatch(List<EMAsset> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(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
    public EMAsset getDraft(EMAsset et) {
        fillParentData(et);
        return et;
    }

    @Override
    public boolean checkKey(EMAsset et) {
        return (!ObjectUtils.isEmpty(et.getEmassetid()))&&(!Objects.isNull(this.getById(et.getEmassetid())));
    }

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

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

	@Override
    public List<EMAsset> selectByAssetclassid(String emassetclassid) {
        return baseMapper.selectByAssetclassid(emassetclassid);
    }

    @Override
    public void removeByAssetclassid(String emassetclassid) {
        this.remove(new QueryWrapper<EMAsset>().eq("assetclassid",emassetclassid));
    }

	@Override
    public List<EMAsset> selectByEqlocationid(String emeqlocationid) {
        return baseMapper.selectByEqlocationid(emeqlocationid);
    }

    @Override
    public void removeByEqlocationid(String emeqlocationid) {
        this.remove(new QueryWrapper<EMAsset>().eq("eqlocationid",emeqlocationid));
    }

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

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

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

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

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

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

	@Override
    public List<EMAsset> selectByContractid(String pfcontractid) {
        return baseMapper.selectByContractid(pfcontractid);
    }

    @Override
    public void removeByContractid(String pfcontractid) {
        this.remove(new QueryWrapper<EMAsset>().eq("contractid",pfcontractid));
    }

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

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

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

    @Override
    public void removeByMgrdeptid(String pfdeptid) {
        this.remove(new QueryWrapper<EMAsset>().eq("mgrdeptid",pfdeptid));
    }

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

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

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

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

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

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


    /**
     * 查询集合 报废资产
     */
    @Override
    public Page<EMAsset> searchAssetBf(EMAssetSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMAsset> pages=baseMapper.searchAssetBf(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMAsset>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMAsset et){
        //实体关系[DER1N_EMASSET_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_EMASSET_EMASSETCLASS_ASSETCLASSID]
        if(!ObjectUtils.isEmpty(et.getAssetclassid())){
            cn.ibizlab.eam.core.eam_core.domain.EMAssetClass assetclass=et.getAssetclass();
            if(ObjectUtils.isEmpty(assetclass)){
                cn.ibizlab.eam.core.eam_core.domain.EMAssetClass majorEntity=emassetclassService.get(et.getAssetclassid());
                et.setAssetclass(majorEntity);
                assetclass=majorEntity;
            }
            et.setAssetclassname(assetclass.getEmassetclassname());
            et.setAssetclasscode(assetclass.getAssetclasscode());
        }
        //实体关系[DER1N_EMASSET_EMEQLOCATION_EQLOCATIONID]
        if(!ObjectUtils.isEmpty(et.getEqlocationid())){
            cn.ibizlab.eam.core.eam_core.domain.EMEQLocation eqlocation=et.getEqlocation();
            if(ObjectUtils.isEmpty(eqlocation)){
                cn.ibizlab.eam.core.eam_core.domain.EMEQLocation majorEntity=emeqlocationService.get(et.getEqlocationid());
                et.setEqlocation(majorEntity);
                eqlocation=majorEntity;
            }
            et.setEqlocationname(eqlocation.getEmeqlocationname());
        }
        //实体关系[DER1N_EMASSET_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_EMASSET_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_EMASSET_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_EMASSET_PFCONTRACT_CONTRACTID]
        if(!ObjectUtils.isEmpty(et.getContractid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFContract contract=et.getContract();
            if(ObjectUtils.isEmpty(contract)){
                cn.ibizlab.eam.core.eam_pf.domain.PFContract majorEntity=pfcontractService.get(et.getContractid());
                et.setContract(majorEntity);
                contract=majorEntity;
            }
            et.setContractname(contract.getPfcontractname());
        }
        //实体关系[DER1N_EMASSET_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.setDeptname(dept.getPfdeptname());
            et.setMgrempname(dept.getMgrempname());
        }
        //实体关系[DER1N_EMASSET_PFDEPT_MGRDEPTID]
        if(!ObjectUtils.isEmpty(et.getMgrdeptid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFDept mgrdept=et.getMgrdept();
            if(ObjectUtils.isEmpty(mgrdept)){
                cn.ibizlab.eam.core.eam_pf.domain.PFDept majorEntity=pfdeptService.get(et.getMgrdeptid());
                et.setMgrdept(majorEntity);
                mgrdept=majorEntity;
            }
            et.setMgrdeptmgr(mgrdept.getMgrempname());
            et.setMgrdeptname(mgrdept.getPfdeptname());
        }
        //实体关系[DER1N_EMASSET_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_EMASSET_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_EMASSET_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<EMAsset> getEmassetByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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

}



