package cn.ibizlab.businesscentral.core.odoo_mro.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.aop.framework.AopContext;
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.beans.factory.annotation.Value;
import cn.ibizlab.businesscentral.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.businesscentral.core.odoo_mro.domain.Mro_order;
import cn.ibizlab.businesscentral.core.odoo_mro.filter.Mro_orderSearchContext;
import cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_orderService;

import cn.ibizlab.businesscentral.util.helper.CachedBeanCopier;
import cn.ibizlab.businesscentral.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.businesscentral.core.util.helper.EBSServiceImpl;
import cn.ibizlab.businesscentral.core.odoo_mro.mapper.Mro_orderMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;

import org.springframework.util.StringUtils;

/**
 * 实体[Maintenance Order] 服务对象接口实现
 */
@Slf4j
@Service("Mro_orderServiceImpl")
public class Mro_orderServiceImpl extends EBSServiceImpl<Mro_orderMapper, Mro_order> implements IMro_orderService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_order_parts_lineService mroOrderPartsLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_asset.service.IAsset_assetService assetAssetService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_requestService mroRequestService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_taskService mroTaskService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_workorderService mroWorkorderService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_companyService resCompanyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

    public String getIrModel(){
        return "mro.order" ;
    }

    private boolean messageinfo = false ;

    public void setMessageInfo(boolean messageinfo){
        this.messageinfo = messageinfo ;
    }

    @Override
    @Transactional
    public boolean create(Mro_order et) {
        boolean mail_create_nosubscribe = et.get("mail_create_nosubscribe") != null;
        boolean mail_create_nolog = et.get("mail_create_nolog") != null;
        boolean mail_notrack = et.get("mail_notrack") != null;
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et)))
            return false;
        CachedBeanCopier.copy((AopContext.currentProxy() != null ? (IMro_orderService)AopContext.currentProxy() : this).get(et.getId()),et);

        if (messageinfo && !mail_create_nosubscribe) {
            cn.ibizlab.businesscentral.util.security.SpringContextHolder.getBean(cn.ibizlab.businesscentral.core.extensions.service.Mail_followersExService.class).add_default_followers(this,et);
        }

        if (messageinfo && !mail_create_nolog) {
            cn.ibizlab.businesscentral.util.security.SpringContextHolder.getBean(cn.ibizlab.businesscentral.core.extensions.service.Mail_messageExService.class).add_default_create_message(this,et);
        }

        if (messageinfo && !mail_notrack) {

        }
        return true;
    }

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

    @Override
    @Transactional
    public boolean update(Mro_order et) {
        Mro_order old = new Mro_order() ;
        CachedBeanCopier.copy((AopContext.currentProxy() != null ? (IMro_orderService)AopContext.currentProxy() : this).get(et.getId()), old);
        boolean mail_notrack = et.get("mail_notrack") != null;
        fillParentData(et);
         if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("id",et.getId())))
            return false;
        CachedBeanCopier.copy((AopContext.currentProxy() != null ? (IMro_orderService)AopContext.currentProxy() : this).get(et.getId()),et);
        if (messageinfo && !mail_notrack) {
            cn.ibizlab.businesscentral.util.security.SpringContextHolder.getBean(cn.ibizlab.businesscentral.core.extensions.service.Mail_tracking_valueExService.class).message_track(this,old,et);
        }
        return true;
    }

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

    @Override
    @Transactional
    public boolean remove(Long key) {
        mroOrderPartsLineService.resetByMaintenanceId(key);
        boolean result=removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<Long> idList) {
        mroOrderPartsLineService.resetByMaintenanceId(idList);
        removeByIds(idList);
    }

    @Override
    @Transactional
    public Mro_order get(Long key) {
        Mro_order et = getById(key);
        if(et==null){
            et=new Mro_order();
            et.setId(key);
        }
        else{
        }
        return et;
    }

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

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

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

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

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


	@Override
    public List<Mro_order> selectByAssetId(Long id) {
        return baseMapper.selectByAssetId(id);
    }
    @Override
    public void resetByAssetId(Long id) {
        this.update(new UpdateWrapper<Mro_order>().set("asset_id",null).eq("asset_id",id));
    }

    @Override
    public void resetByAssetId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Mro_order>().set("asset_id",null).in("asset_id",ids));
    }

    @Override
    public void removeByAssetId(Long id) {
        this.remove(new QueryWrapper<Mro_order>().eq("asset_id",id));
    }

	@Override
    public List<Mro_order> selectByRequestId(Long id) {
        return baseMapper.selectByRequestId(id);
    }
    @Override
    public void resetByRequestId(Long id) {
        this.update(new UpdateWrapper<Mro_order>().set("request_id",null).eq("request_id",id));
    }

    @Override
    public void resetByRequestId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Mro_order>().set("request_id",null).in("request_id",ids));
    }

    @Override
    public void removeByRequestId(Long id) {
        this.remove(new QueryWrapper<Mro_order>().eq("request_id",id));
    }

	@Override
    public List<Mro_order> selectByTaskId(Long id) {
        return baseMapper.selectByTaskId(id);
    }
    @Override
    public void resetByTaskId(Long id) {
        this.update(new UpdateWrapper<Mro_order>().set("task_id",null).eq("task_id",id));
    }

    @Override
    public void resetByTaskId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Mro_order>().set("task_id",null).in("task_id",ids));
    }

    @Override
    public void removeByTaskId(Long id) {
        this.remove(new QueryWrapper<Mro_order>().eq("task_id",id));
    }

	@Override
    public List<Mro_order> selectByWoId(Long id) {
        return baseMapper.selectByWoId(id);
    }
    @Override
    public void removeByWoId(Collection<Long> ids) {
        this.remove(new QueryWrapper<Mro_order>().in("wo_id",ids));
    }

    @Override
    public void removeByWoId(Long id) {
        this.remove(new QueryWrapper<Mro_order>().eq("wo_id",id));
    }

	@Override
    public List<Mro_order> selectByCompanyId(Long id) {
        return baseMapper.selectByCompanyId(id);
    }
    @Override
    public void resetByCompanyId(Long id) {
        this.update(new UpdateWrapper<Mro_order>().set("company_id",null).eq("company_id",id));
    }

    @Override
    public void resetByCompanyId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Mro_order>().set("company_id",null).in("company_id",ids));
    }

    @Override
    public void removeByCompanyId(Long id) {
        this.remove(new QueryWrapper<Mro_order>().eq("company_id",id));
    }

	@Override
    public List<Mro_order> selectByCreateUid(Long id) {
        return baseMapper.selectByCreateUid(id);
    }
    @Override
    public void removeByCreateUid(Long id) {
        this.remove(new QueryWrapper<Mro_order>().eq("create_uid",id));
    }

	@Override
    public List<Mro_order> selectByUserId(Long id) {
        return baseMapper.selectByUserId(id);
    }
    @Override
    public void resetByUserId(Long id) {
        this.update(new UpdateWrapper<Mro_order>().set("user_id",null).eq("user_id",id));
    }

    @Override
    public void resetByUserId(Collection<Long> ids) {
        this.update(new UpdateWrapper<Mro_order>().set("user_id",null).in("user_id",ids));
    }

    @Override
    public void removeByUserId(Long id) {
        this.remove(new QueryWrapper<Mro_order>().eq("user_id",id));
    }

	@Override
    public List<Mro_order> selectByWriteUid(Long id) {
        return baseMapper.selectByWriteUid(id);
    }
    @Override
    public void removeByWriteUid(Long id) {
        this.remove(new QueryWrapper<Mro_order>().eq("write_uid",id));
    }


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Mro_order et){
        //实体关系[DER1N_MRO_ORDER__ASSET_ASSET__ASSET_ID]
        if(!ObjectUtils.isEmpty(et.getAssetId())){
            cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_asset odooAsset=et.getOdooAsset();
            if(ObjectUtils.isEmpty(odooAsset)){
                cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_asset majorEntity=assetAssetService.get(et.getAssetId());
                et.setOdooAsset(majorEntity);
                odooAsset=majorEntity;
            }
            et.setAssetIdText(odooAsset.getName());
        }
        //实体关系[DER1N_MRO_ORDER__MRO_REQUEST__REQUEST_ID]
        if(!ObjectUtils.isEmpty(et.getRequestId())){
            cn.ibizlab.businesscentral.core.odoo_mro.domain.Mro_request odooRequest=et.getOdooRequest();
            if(ObjectUtils.isEmpty(odooRequest)){
                cn.ibizlab.businesscentral.core.odoo_mro.domain.Mro_request majorEntity=mroRequestService.get(et.getRequestId());
                et.setOdooRequest(majorEntity);
                odooRequest=majorEntity;
            }
            et.setRequestIdText(odooRequest.getName());
        }
        //实体关系[DER1N_MRO_ORDER__MRO_TASK__TASK_ID]
        if(!ObjectUtils.isEmpty(et.getTaskId())){
            cn.ibizlab.businesscentral.core.odoo_mro.domain.Mro_task odooTask=et.getOdooTask();
            if(ObjectUtils.isEmpty(odooTask)){
                cn.ibizlab.businesscentral.core.odoo_mro.domain.Mro_task majorEntity=mroTaskService.get(et.getTaskId());
                et.setOdooTask(majorEntity);
                odooTask=majorEntity;
            }
            et.setTaskIdText(odooTask.getName());
        }
        //实体关系[DER1N_MRO_ORDER__MRO_WORKORDER__WO_ID]
        if(!ObjectUtils.isEmpty(et.getWoId())){
            cn.ibizlab.businesscentral.core.odoo_mro.domain.Mro_workorder odooWo=et.getOdooWo();
            if(ObjectUtils.isEmpty(odooWo)){
                cn.ibizlab.businesscentral.core.odoo_mro.domain.Mro_workorder majorEntity=mroWorkorderService.get(et.getWoId());
                et.setOdooWo(majorEntity);
                odooWo=majorEntity;
            }
            et.setWoIdText(odooWo.getName());
        }
        //实体关系[DER1N_MRO_ORDER__RES_COMPANY__COMPANY_ID]
        if(!ObjectUtils.isEmpty(et.getCompanyId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_company odooCompany=et.getOdooCompany();
            if(ObjectUtils.isEmpty(odooCompany)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_company majorEntity=resCompanyService.get(et.getCompanyId());
                et.setOdooCompany(majorEntity);
                odooCompany=majorEntity;
            }
            et.setCompanyIdText(odooCompany.getName());
        }
        //实体关系[DER1N_MRO_ORDER__RES_USERS__CREATE_UID]
        if(!ObjectUtils.isEmpty(et.getCreateUid())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users odooCreate=et.getOdooCreate();
            if(ObjectUtils.isEmpty(odooCreate)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users majorEntity=resUsersService.get(et.getCreateUid());
                et.setOdooCreate(majorEntity);
                odooCreate=majorEntity;
            }
            et.setCreateUidText(odooCreate.getName());
        }
        //实体关系[DER1N_MRO_ORDER__RES_USERS__USER_ID]
        if(!ObjectUtils.isEmpty(et.getUserId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users odooUser=et.getOdooUser();
            if(ObjectUtils.isEmpty(odooUser)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users majorEntity=resUsersService.get(et.getUserId());
                et.setOdooUser(majorEntity);
                odooUser=majorEntity;
            }
            et.setUserIdText(odooUser.getName());
        }
        //实体关系[DER1N_MRO_ORDER__RES_USERS__WRITE_UID]
        if(!ObjectUtils.isEmpty(et.getWriteUid())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users odooWrite=et.getOdooWrite();
            if(ObjectUtils.isEmpty(odooWrite)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_users majorEntity=resUsersService.get(et.getWriteUid());
                et.setOdooWrite(majorEntity);
                odooWrite=majorEntity;
            }
            et.setWriteUidText(odooWrite.getName());
        }
    }




    @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<Mro_order> getMroOrderByIds(List<Long> ids) {
         return this.listByIds(ids);
    }

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



}



