package cn.ibizlab.businesscentral.core.odoo_asset.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.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_asset.domain.Asset_asset;
import cn.ibizlab.businesscentral.core.odoo_asset.filter.Asset_assetSearchContext;
import cn.ibizlab.businesscentral.core.odoo_asset.service.IAsset_assetService;

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_asset.mapper.Asset_assetMapper;
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;

/**
 * 实体[Asset] 服务对象接口实现
 */
@Slf4j
@Service("Asset_assetServiceImpl")
public class Asset_assetServiceImpl extends EBSServiceImpl<Asset_assetMapper, Asset_asset> implements IAsset_assetService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_orderService mroOrderService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_pm_meterService mroPmMeterService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_mro.service.IMro_requestService mroRequestService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_asset.service.IAsset_stateService assetStateService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_partnerService resPartnerService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.odoo_base.service.IRes_usersService resUsersService;

    protected int batchSize = 500;

    public String getIrModel(){
        return "asset.asset" ;
    }

    private boolean messageinfo = false ;

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

    @Override
    @Transactional
    public boolean create(Asset_asset 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(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_tracking_valueExService.class).add_default_create_message(this,et);
        }

        if (messageinfo && !mail_notrack) {

        }

        return true;
    }

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

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

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

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

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





    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Asset_asset et){
        //实体关系[DER1N_ASSET_ASSET__ASSET_STATE__ACCOUNTING_STATE_ID]
        if(!ObjectUtils.isEmpty(et.getAccountingStateId())){
            cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state odooAccountingState=et.getOdooAccountingState();
            if(ObjectUtils.isEmpty(odooAccountingState)){
                cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state majorEntity=assetStateService.get(et.getAccountingStateId());
                et.setOdooAccountingState(majorEntity);
                odooAccountingState=majorEntity;
            }
            et.setAccountingStateIdText(odooAccountingState.getName());
        }
        //实体关系[DER1N_ASSET_ASSET__ASSET_STATE__FINANCE_STATE_ID]
        if(!ObjectUtils.isEmpty(et.getFinanceStateId())){
            cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state odooFinanceState=et.getOdooFinanceState();
            if(ObjectUtils.isEmpty(odooFinanceState)){
                cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state majorEntity=assetStateService.get(et.getFinanceStateId());
                et.setOdooFinanceState(majorEntity);
                odooFinanceState=majorEntity;
            }
            et.setFinanceStateIdText(odooFinanceState.getName());
        }
        //实体关系[DER1N_ASSET_ASSET__ASSET_STATE__MAINTENANCE_STATE_ID]
        if(!ObjectUtils.isEmpty(et.getMaintenanceStateId())){
            cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state odooMaintenanceState=et.getOdooMaintenanceState();
            if(ObjectUtils.isEmpty(odooMaintenanceState)){
                cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state majorEntity=assetStateService.get(et.getMaintenanceStateId());
                et.setOdooMaintenanceState(majorEntity);
                odooMaintenanceState=majorEntity;
            }
            et.setMaintenanceStateColor(odooMaintenanceState.getStateColor());
            et.setMaintenanceStateIdText(odooMaintenanceState.getName());
        }
        //实体关系[DER1N_ASSET_ASSET__ASSET_STATE__MANUFACTURE_STATE_ID]
        if(!ObjectUtils.isEmpty(et.getManufactureStateId())){
            cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state odooManufactureState=et.getOdooManufactureState();
            if(ObjectUtils.isEmpty(odooManufactureState)){
                cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state majorEntity=assetStateService.get(et.getManufactureStateId());
                et.setOdooManufactureState(majorEntity);
                odooManufactureState=majorEntity;
            }
            et.setManufactureStateIdText(odooManufactureState.getName());
        }
        //实体关系[DER1N_ASSET_ASSET__ASSET_STATE__WAREHOUSE_STATE_ID]
        if(!ObjectUtils.isEmpty(et.getWarehouseStateId())){
            cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state odooWarehouseState=et.getOdooWarehouseState();
            if(ObjectUtils.isEmpty(odooWarehouseState)){
                cn.ibizlab.businesscentral.core.odoo_asset.domain.Asset_state majorEntity=assetStateService.get(et.getWarehouseStateId());
                et.setOdooWarehouseState(majorEntity);
                odooWarehouseState=majorEntity;
            }
            et.setWarehouseStateIdText(odooWarehouseState.getName());
        }
        //实体关系[DER1N_ASSET_ASSET__RES_PARTNER__MANUFACTURER_ID]
        if(!ObjectUtils.isEmpty(et.getManufacturerId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner odooManufacturer=et.getOdooManufacturer();
            if(ObjectUtils.isEmpty(odooManufacturer)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner majorEntity=resPartnerService.get(et.getManufacturerId());
                et.setOdooManufacturer(majorEntity);
                odooManufacturer=majorEntity;
            }
            et.setManufacturerIdText(odooManufacturer.getName());
        }
        //实体关系[DER1N_ASSET_ASSET__RES_PARTNER__VENDOR_ID]
        if(!ObjectUtils.isEmpty(et.getVendorId())){
            cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner odooVendor=et.getOdooVendor();
            if(ObjectUtils.isEmpty(odooVendor)){
                cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner majorEntity=resPartnerService.get(et.getVendorId());
                et.setOdooVendor(majorEntity);
                odooVendor=majorEntity;
            }
            et.setVendorIdText(odooVendor.getName());
        }
        //实体关系[DER1N_ASSET_ASSET__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_ASSET_ASSET__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_ASSET_ASSET__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<Asset_asset> getAssetAssetByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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



}



