package cn.ibizlab.businesscentral.core.odoo_mrp.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_mrp.domain.Mrp_workorder;
import cn.ibizlab.businesscentral.core.odoo_mrp.filter.Mrp_workorderSearchContext;
import cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_workorderService;

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_mrp.mapper.Mrp_workorderMapper;
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;

/**
 * 实体[工单] 服务对象接口实现
 */
@Slf4j
@Service("Mrp_workorderServiceImpl")
public class Mrp_workorderServiceImpl extends EBSServiceImpl<Mrp_workorderMapper, Mrp_workorder> implements IMrp_workorderService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_workcenter_productivityService mrpWorkcenterProductivityService;

    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_workorderService mrpWorkorderService = this;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_move_lineService stockMoveLineService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_moveService stockMoveService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_production_lotService stockProductionLotService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_stock.service.IStock_scrapService stockScrapService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_productionService mrpProductionService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_routing_workcenterService mrpRoutingWorkcenterService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mrp.service.IMrp_workcenterService mrpWorkcenterService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_productService productProductService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

    public String getIrModel(){
        return "mrp.workorder" ;
    }

    private boolean messageinfo = false ;

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

    @Override
    @Transactional
    public boolean create(Mrp_workorder 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 ? (IMrp_workorderService)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<Mrp_workorder> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean update(Mrp_workorder et) {
        Mrp_workorder old = new Mrp_workorder() ;
        CachedBeanCopier.copy((AopContext.currentProxy() != null ? (IMrp_workorderService)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 ? (IMrp_workorderService)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<Mrp_workorder> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(Long key) {
        mrpWorkcenterProductivityService.resetByWorkorderId(key);
        mrpWorkorderService.resetByNextWorkOrderId(key);
        stockMoveLineService.resetByWorkorderId(key);
        stockMoveService.resetByWorkorderId(key);
        stockProductionLotService.resetByUseNextOnWorkOrderId(key);
        stockScrapService.resetByWorkorderId(key);
        boolean result=removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<Long> idList) {
        mrpWorkcenterProductivityService.resetByWorkorderId(idList);
        mrpWorkorderService.resetByNextWorkOrderId(idList);
        stockMoveLineService.resetByWorkorderId(idList);
        stockMoveService.resetByWorkorderId(idList);
        stockProductionLotService.resetByUseNextOnWorkOrderId(idList);
        stockScrapService.resetByWorkorderId(idList);
        removeByIds(idList);
    }

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

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

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

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

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

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


	@Override
    public List<Mrp_workorder> selectByProductionId(Long id) {
        return baseMapper.selectByProductionId(id);
    }
    @Override
    public void removeByProductionId(Collection<Long> ids) {
        this.remove(new QueryWrapper<Mrp_workorder>().in("production_id",ids));
    }

    @Override
    public void removeByProductionId(Long id) {
        this.remove(new QueryWrapper<Mrp_workorder>().eq("production_id",id));
    }

	@Override
    public List<Mrp_workorder> selectByOperationId(Long id) {
        return baseMapper.selectByOperationId(id);
    }
    @Override
    public void resetByOperationId(Long id) {
        this.update(new UpdateWrapper<Mrp_workorder>().set("operation_id",null).eq("operation_id",id));
    }

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

    @Override
    public void removeByOperationId(Long id) {
        this.remove(new QueryWrapper<Mrp_workorder>().eq("operation_id",id));
    }

	@Override
    public List<Mrp_workorder> selectByWorkcenterId(Long id) {
        return baseMapper.selectByWorkcenterId(id);
    }
    @Override
    public void resetByWorkcenterId(Long id) {
        this.update(new UpdateWrapper<Mrp_workorder>().set("workcenter_id",null).eq("workcenter_id",id));
    }

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

    @Override
    public void removeByWorkcenterId(Long id) {
        this.remove(new QueryWrapper<Mrp_workorder>().eq("workcenter_id",id));
    }

	@Override
    public List<Mrp_workorder> selectByNextWorkOrderId(Long id) {
        return baseMapper.selectByNextWorkOrderId(id);
    }
    @Override
    public void resetByNextWorkOrderId(Long id) {
        this.update(new UpdateWrapper<Mrp_workorder>().set("next_work_order_id",null).eq("next_work_order_id",id));
    }

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

    @Override
    public void removeByNextWorkOrderId(Long id) {
        this.remove(new QueryWrapper<Mrp_workorder>().eq("next_work_order_id",id));
    }

	@Override
    public List<Mrp_workorder> selectByProductId(Long id) {
        return baseMapper.selectByProductId(id);
    }
    @Override
    public void resetByProductId(Long id) {
        this.update(new UpdateWrapper<Mrp_workorder>().set("product_id",null).eq("product_id",id));
    }

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

    @Override
    public void removeByProductId(Long id) {
        this.remove(new QueryWrapper<Mrp_workorder>().eq("product_id",id));
    }

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

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

	@Override
    public List<Mrp_workorder> selectByFinalLotId(Long id) {
        return baseMapper.selectByFinalLotId(id);
    }
    @Override
    public void resetByFinalLotId(Long id) {
        this.update(new UpdateWrapper<Mrp_workorder>().set("final_lot_id",null).eq("final_lot_id",id));
    }

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

    @Override
    public void removeByFinalLotId(Long id) {
        this.remove(new QueryWrapper<Mrp_workorder>().eq("final_lot_id",id));
    }


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Mrp_workorder et){
        //实体关系[DER1N_MRP_WORKORDER__MRP_PRODUCTION__PRODUCTION_ID]
        if(!ObjectUtils.isEmpty(et.getProductionId())){
            cn.ibizlab.businesscentral.core.odoo_mrp.domain.Mrp_production odooProduction=et.getOdooProduction();
            if(ObjectUtils.isEmpty(odooProduction)){
                cn.ibizlab.businesscentral.core.odoo_mrp.domain.Mrp_production majorEntity=mrpProductionService.get(et.getProductionId());
                et.setOdooProduction(majorEntity);
                odooProduction=majorEntity;
            }
            et.setProductionDate(odooProduction.getDatePlannedStart());
            et.setQtyProduction(odooProduction.getProductQty());
            et.setProductUomId(odooProduction.getProductUomId());
            et.setProductionAvailability(odooProduction.getAvailability());
            et.setProductionState(odooProduction.getState());
            et.setProductionIdText(odooProduction.getName());
        }
        //实体关系[DER1N_MRP_WORKORDER__MRP_ROUTING_WORKCENTER__OPERATION_ID]
        if(!ObjectUtils.isEmpty(et.getOperationId())){
            cn.ibizlab.businesscentral.core.odoo_mrp.domain.Mrp_routing_workcenter odooOperation=et.getOdooOperation();
            if(ObjectUtils.isEmpty(odooOperation)){
                cn.ibizlab.businesscentral.core.odoo_mrp.domain.Mrp_routing_workcenter majorEntity=mrpRoutingWorkcenterService.get(et.getOperationId());
                et.setOdooOperation(majorEntity);
                odooOperation=majorEntity;
            }
            et.setWorksheet(odooOperation.getWorksheet());
            et.setOperationIdText(odooOperation.getName());
        }
        //实体关系[DER1N_MRP_WORKORDER__MRP_WORKCENTER__WORKCENTER_ID]
        if(!ObjectUtils.isEmpty(et.getWorkcenterId())){
            cn.ibizlab.businesscentral.core.odoo_mrp.domain.Mrp_workcenter odooWorkcenter=et.getOdooWorkcenter();
            if(ObjectUtils.isEmpty(odooWorkcenter)){
                cn.ibizlab.businesscentral.core.odoo_mrp.domain.Mrp_workcenter majorEntity=mrpWorkcenterService.get(et.getWorkcenterId());
                et.setOdooWorkcenter(majorEntity);
                odooWorkcenter=majorEntity;
            }
            et.setWorkcenterIdText(odooWorkcenter.getName());
            et.setWorkingState(odooWorkcenter.getWorkingState());
        }
        //实体关系[DER1N_MRP_WORKORDER__MRP_WORKORDER__NEXT_WORK_ORDER_ID]
        if(!ObjectUtils.isEmpty(et.getNextWorkOrderId())){
            cn.ibizlab.businesscentral.core.odoo_mrp.domain.Mrp_workorder odooNextWorkOrder=et.getOdooNextWorkOrder();
            if(ObjectUtils.isEmpty(odooNextWorkOrder)){
                cn.ibizlab.businesscentral.core.odoo_mrp.domain.Mrp_workorder majorEntity=mrpWorkorderService.get(et.getNextWorkOrderId());
                et.setOdooNextWorkOrder(majorEntity);
                odooNextWorkOrder=majorEntity;
            }
            et.setNextWorkOrderIdText(odooNextWorkOrder.getName());
        }
        //实体关系[DER1N_MRP_WORKORDER__PRODUCT_PRODUCT__PRODUCT_ID]
        if(!ObjectUtils.isEmpty(et.getProductId())){
            cn.ibizlab.businesscentral.core.odoo_product.domain.Product_product odooProduct=et.getOdooProduct();
            if(ObjectUtils.isEmpty(odooProduct)){
                cn.ibizlab.businesscentral.core.odoo_product.domain.Product_product majorEntity=productProductService.get(et.getProductId());
                et.setOdooProduct(majorEntity);
                odooProduct=majorEntity;
            }
            et.setProductIdText(odooProduct.getName());
            et.setProductTracking(odooProduct.getTracking());
        }
        //实体关系[DER1N_MRP_WORKORDER__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_MRP_WORKORDER__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());
        }
        //实体关系[DER1N_MRP_WORKORDER__STOCK_PRODUCTION_LOT__FINAL_LOT_ID]
        if(!ObjectUtils.isEmpty(et.getFinalLotId())){
            cn.ibizlab.businesscentral.core.odoo_stock.domain.Stock_production_lot odooFinalLot=et.getOdooFinalLot();
            if(ObjectUtils.isEmpty(odooFinalLot)){
                cn.ibizlab.businesscentral.core.odoo_stock.domain.Stock_production_lot majorEntity=stockProductionLotService.get(et.getFinalLotId());
                et.setOdooFinalLot(majorEntity);
                odooFinalLot=majorEntity;
            }
            et.setFinalLotIdText(odooFinalLot.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<Mrp_workorder> getMrpWorkorderByIds(List<Long> ids) {
         return this.listByIds(ids);
    }

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



}



