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.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_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((AopContext.currentProxy() != null ? (IAsset_assetService)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<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((AopContext.currentProxy() != null ? (IAsset_assetService)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 ? (IAsset_assetService)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<Asset_asset> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(Long key) {
        mroOrderService.resetByAssetId(key);
        if(!ObjectUtils.isEmpty(mroPmMeterService.selectByAssetId(key)))
            throw new BadRequestAlertException("删除数据失败，当前数据存在关系实体[Mro_pm_meter]数据，无法删除!","","");
        mroRequestService.resetByAssetId(key);
        boolean result=removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<Long> idList) {
        mroOrderService.resetByAssetId(idList);
        if(!ObjectUtils.isEmpty(mroPmMeterService.selectByAssetId(idList)))
            throw new BadRequestAlertException("删除数据失败，当前数据存在关系实体[Mro_pm_meter]数据，无法删除!","","");
        mroRequestService.resetByAssetId(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;
    }

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

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

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

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

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


	@Override
    public List<Asset_asset> selectByAccountingStateId(Long id) {
        return baseMapper.selectByAccountingStateId(id);
    }
    @Override
    public void resetByAccountingStateId(Long id) {
        this.update(new UpdateWrapper<Asset_asset>().set("accounting_state_id",null).eq("accounting_state_id",id));
    }

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

    @Override
    public void removeByAccountingStateId(Long id) {
        this.remove(new QueryWrapper<Asset_asset>().eq("accounting_state_id",id));
    }

	@Override
    public List<Asset_asset> selectByFinanceStateId(Long id) {
        return baseMapper.selectByFinanceStateId(id);
    }
    @Override
    public void resetByFinanceStateId(Long id) {
        this.update(new UpdateWrapper<Asset_asset>().set("finance_state_id",null).eq("finance_state_id",id));
    }

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

    @Override
    public void removeByFinanceStateId(Long id) {
        this.remove(new QueryWrapper<Asset_asset>().eq("finance_state_id",id));
    }

	@Override
    public List<Asset_asset> selectByMaintenanceStateId(Long id) {
        return baseMapper.selectByMaintenanceStateId(id);
    }
    @Override
    public void resetByMaintenanceStateId(Long id) {
        this.update(new UpdateWrapper<Asset_asset>().set("maintenance_state_id",null).eq("maintenance_state_id",id));
    }

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

    @Override
    public void removeByMaintenanceStateId(Long id) {
        this.remove(new QueryWrapper<Asset_asset>().eq("maintenance_state_id",id));
    }

	@Override
    public List<Asset_asset> selectByManufactureStateId(Long id) {
        return baseMapper.selectByManufactureStateId(id);
    }
    @Override
    public void resetByManufactureStateId(Long id) {
        this.update(new UpdateWrapper<Asset_asset>().set("manufacture_state_id",null).eq("manufacture_state_id",id));
    }

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

    @Override
    public void removeByManufactureStateId(Long id) {
        this.remove(new QueryWrapper<Asset_asset>().eq("manufacture_state_id",id));
    }

	@Override
    public List<Asset_asset> selectByWarehouseStateId(Long id) {
        return baseMapper.selectByWarehouseStateId(id);
    }
    @Override
    public void resetByWarehouseStateId(Long id) {
        this.update(new UpdateWrapper<Asset_asset>().set("warehouse_state_id",null).eq("warehouse_state_id",id));
    }

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

    @Override
    public void removeByWarehouseStateId(Long id) {
        this.remove(new QueryWrapper<Asset_asset>().eq("warehouse_state_id",id));
    }

	@Override
    public List<Asset_asset> selectByManufacturerId(Long id) {
        return baseMapper.selectByManufacturerId(id);
    }
    @Override
    public void resetByManufacturerId(Long id) {
        this.update(new UpdateWrapper<Asset_asset>().set("manufacturer_id",null).eq("manufacturer_id",id));
    }

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

    @Override
    public void removeByManufacturerId(Long id) {
        this.remove(new QueryWrapper<Asset_asset>().eq("manufacturer_id",id));
    }

	@Override
    public List<Asset_asset> selectByVendorId(Long id) {
        return baseMapper.selectByVendorId(id);
    }
    @Override
    public void resetByVendorId(Long id) {
        this.update(new UpdateWrapper<Asset_asset>().set("vendor_id",null).eq("vendor_id",id));
    }

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

    @Override
    public void removeByVendorId(Long id) {
        this.remove(new QueryWrapper<Asset_asset>().eq("vendor_id",id));
    }

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

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

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

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

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


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @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<Long> 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;
    }



}



