package cn.ibizlab.core.sample.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 cn.ibizlab.util.security.SpringContextHolder;
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.util.StringUtils;
import org.springframework.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.core.sample.domain.IBIZOrderDetail;
import cn.ibizlab.core.sample.filter.IBIZOrderDetailSearchContext;
import cn.ibizlab.core.sample.service.IBIZOrderDetailService;
import cn.ibizlab.core.sample.mapper.IBIZOrderDetailMapper;
import cn.ibizlab.util.helper.CachedBeanCopier;
import cn.ibizlab.util.security.AuthenticationUser;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import cn.ibizlab.core.sample.domain.IBIZOrder;
import cn.ibizlab.core.sample.service.IBIZOrderService;
import cn.ibizlab.core.sample.domain.IBIZUNIProduct;
import cn.ibizlab.core.sample.service.IBIZUNIProductService;


/**
 * 实体[订单明细] 服务对象接口实现
 */
@Slf4j
@Service("IBIZOrderDetailService")
public class IBIZOrderDetailServiceBase extends ServiceImpl<IBIZOrderDetailMapper,IBIZOrderDetail> implements IBIZOrderDetailService {

    @Autowired
    @Lazy
    protected IBIZOrderService ibizOrderService;
   
    @Autowired
    @Lazy
    protected IBIZUNIProductService ibizuniProductService;
   

    protected int batchSize = 500;

    public IBIZOrderDetail get(IBIZOrderDetail et) {
        IBIZOrderDetail rt = this.baseMapper.selectEntity(et);
        Assert.notNull(rt,"数据不存在,订单明细:"+et.getIbizOrderDetailId());
        BeanUtils.copyProperties(rt, et);
        return et;
    }
    
    public List<IBIZOrderDetail> getByEntities(List<IBIZOrderDetail> entities) {
        return this.baseMapper.selectEntities(entities);
    }

    public void fillParentData(IBIZOrderDetail et) {
        if(!ObjectUtils.isEmpty(et.getIbizOrderId())) {
            IBIZOrder ibizOrder = et.getIbizorder();
            if(!ObjectUtils.isEmpty(ibizOrder)) {
                et.setOrderUid(ibizOrder.getOrderUid());   
                et.setIbizOrderName(ibizOrder.getIbizOrderName());   
            }
        }    
        if(!ObjectUtils.isEmpty(et.getIbizuniProductId())) {
            IBIZUNIProduct ibizuniProduct = et.getIbizuniproduct();
            if(!ObjectUtils.isEmpty(ibizuniProduct)) {
                et.setUnitPrice(ibizuniProduct.getUnitPrice());   
                et.setUnit(ibizuniProduct.getUnit());   
                et.setIbizuniProductName(ibizuniProduct.getIbizuniProductName());   
            }
        }    
    }

    public IBIZOrderDetail getDraft(IBIZOrderDetail et) {
        fillParentData(et);
        return et;
    }

    public Integer checkKey(IBIZOrderDetail et) {
        fillParentData(et);
        return ( (!ObjectUtils.isEmpty(et.getIbizOrderDetailId())) && this.count(Wrappers.<IBIZOrderDetail>query().eq("ibizorderdetailid", et.getIbizOrderDetailId()))>0 )?1:0;
    }

    @Override
    @Transactional
    public boolean create(IBIZOrderDetail et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et))) 
            return false;
        get(et);
        updateParentData(et);    
        return true;
    }
    @Transactional
    public boolean createBatch(List<IBIZOrderDetail> list) {
        list.forEach(et->fillParentData(et));
        this.saveBatch(list, batchSize);
        updateParentDataBatch(list);    
        return true;
    }

    @Transactional
    public boolean update(IBIZOrderDetail et) {
        fillParentData(et);
        UpdateWrapper qw=et.getUpdateWrapper(true);
        qw.eq("ibizorderdetailid", et.getIbizOrderDetailId());
        if(!update(et, qw)) {
            return false;
        }
        get(et);
        updateParentData(et);    
        return true;
    }

    @Transactional
    public boolean updateBatch(List<IBIZOrderDetail> list) {
        list.forEach(et->fillParentData(et));
        updateBatchById(list, batchSize);
        updateParentDataBatch(list);    
        return true;
    }

    @Transactional
    public boolean save(IBIZOrderDetail et) {
        if(checkKey(et)>0)
            return getSelf().update(et);
        else
            return getSelf().create(et);
    }

    @Transactional
    public boolean saveBatch(List<IBIZOrderDetail> list) {
        List<IBIZOrderDetail> rt=this.getByEntities(list);
        Set<Serializable> keys=new HashSet<>();
        rt.forEach(et->{
            Serializable key = et.getIbizOrderDetailId();
            if(!ObjectUtils.isEmpty(key))
                keys.add(key);
        });
        List<IBIZOrderDetail> _create=new ArrayList<>();
        List<IBIZOrderDetail> _update=new ArrayList<>();
        list.forEach(et-> {
            Serializable key = et.getIbizOrderDetailId();
            if(keys.contains(key))
                _update.add(et);
            else
                _create.add(et);
        });
        List rtList=new ArrayList<>();
        if(_update.size()>0 && (!getSelf().updateBatch(_update)))
            return false;
        if(_create.size()>0 && (!getSelf().createBatch(_create)))
            return false;
        return true;
    }

    @Transactional
    public boolean remove(IBIZOrderDetail et) {
        String key = et.getIbizOrderDetailId();
        get(et); 

        if(!remove(new QueryWrapper<IBIZOrderDetail>()
                .eq("ibizorderdetailid", et.getIbizOrderDetailId())
            )) {
            return false;
        }
        updateParentData(et);    
        return true ;
    }

    @Transactional
    public boolean removeByEntities(List<IBIZOrderDetail> entities) {
        for (IBIZOrderDetail et : entities) {
            if(!getSelf().remove(et))
                return false;
        }
        return true;
    }

    @Transactional
    public IBIZOrderDetail createTemp(IBIZOrderDetail dto) {
        return dto;
    }

    @Transactional
    public IBIZOrderDetail createTempMajor(IBIZOrderDetail dto) {
        return dto;
    }

    @Transactional
    public IBIZOrderDetail updateTemp(IBIZOrderDetail dto) {
        return dto;
    }

    @Transactional
    public IBIZOrderDetail updateTempMajor(IBIZOrderDetail dto) {
        return dto;
    }

    @Transactional
    public List<String> removeTemp(List<String> keys) {
        return keys;
    }

    @Transactional
    public List<String> removeTempMajor(List<String> keys) {
        return keys;
    }

    @Transactional
    public IBIZOrderDetail getTemp(String key) {
        return null;
    }

    @Transactional
    public IBIZOrderDetail getTempMajor(String key) {
        return null;
    }

    @Transactional
    public IBIZOrderDetail getDraftTemp(IBIZOrderDetail dto) {
        return null;
    }

    @Transactional
    public IBIZOrderDetail getDraftTempMajor(IBIZOrderDetail dto) {
        return null;
    }

    @Transactional
    public IBIZOrderDetail countMoney(IBIZOrderDetail dto) {
        return dto;
    }

    @Transactional
    public IBIZOrderDetail getUnitAndPrice(String key) {
        return null;
    }

    public Page<IBIZOrderDetail> searchCsmxdy(IBIZOrderDetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrderDetail> pages=baseMapper.searchCsmxdy(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrderDetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrderDetail> listCsmxdy(IBIZOrderDetailSearchContext context) {
        return baseMapper.listCsmxdy(context,context.getSelectCond());
    }

    public Page<IBIZOrderDetail> searchDefault(IBIZOrderDetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrderDetail> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrderDetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrderDetail> listDefault(IBIZOrderDetailSearchContext context) {
        return baseMapper.listDefault(context,context.getSelectCond());
    }

    public Page<IBIZOrderDetail> searchLogic0007(IBIZOrderDetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrderDetail> pages=baseMapper.searchLogic0007(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrderDetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrderDetail> listLogic0007(IBIZOrderDetailSearchContext context) {
        return baseMapper.listLogic0007(context,context.getSelectCond());
    }

    public Page<IBIZOrderDetail> searchX(IBIZOrderDetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrderDetail> pages=baseMapper.searchX(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrderDetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrderDetail> listX(IBIZOrderDetailSearchContext context) {
        return baseMapper.listX(context,context.getSelectCond());
    }

    public List<IBIZOrderDetail> selectByIbizOrderId(String ibizOrderId) {
        return baseMapper.selectByIbizOrderId(ibizOrderId);
    }

    public boolean removeByIbizOrderId(String ibizOrderId) {
        return this.remove(new QueryWrapper<IBIZOrderDetail>().eq("ibizorderid",ibizOrderId));
    }

    public boolean resetByIbizOrderId(String ibizOrderId) {
        return this.update(new UpdateWrapper<IBIZOrderDetail>().set("ibizorderid",null).eq("ibizorderid",ibizOrderId));
    }

    public boolean saveByIbizorder(IBIZOrder ibizOrder,List<IBIZOrderDetail> list) {
        if(list==null)
            return true;
        Set<String> delIds=new HashSet<String>();
        List<IBIZOrderDetail> _update=new ArrayList<IBIZOrderDetail>();
        List<IBIZOrderDetail> _create=new ArrayList<IBIZOrderDetail>();
        for(IBIZOrderDetail before:selectByIbizOrderId(ibizOrder.getIbizOrderId())){
            delIds.add(before.getIbizOrderDetailId());
        }
        for(IBIZOrderDetail sub:list) {
            sub.setIbizOrderId(ibizOrder.getIbizOrderId());
            sub.setIbizorder(ibizOrder);
            if(ObjectUtils.isEmpty(sub.getIbizOrderDetailId()))
                sub.setIbizOrderDetailId((String)sub.getDefaultKey(true));
            if(delIds.contains(sub.getIbizOrderDetailId())) {
                delIds.remove(sub.getIbizOrderDetailId());
                _update.add(sub);
            }
            else
                _create.add(sub);
        }
        if(_update.size()>0 && (!getSelf().updateBatch(_update)))
            return false;
        if(_create.size()>0 && (!getSelf().createBatch(_create)))
            return false;
        if(delIds.size()>0 && (!getSelf().removeBatch(delIds)))
            return false;
        return true;
    }

    public List<IBIZOrderDetail> selectByIbizuniProductId(String ibizuniProductId) {
        return baseMapper.selectByIbizuniProductId(ibizuniProductId);
    }

    public boolean removeByIbizuniProductId(String ibizuniProductId) {
        return this.remove(new QueryWrapper<IBIZOrderDetail>().eq("ibizuniproductid",ibizuniProductId));
    }

    public boolean resetByIbizuniProductId(String ibizuniProductId) {
        return this.update(new UpdateWrapper<IBIZOrderDetail>().set("ibizuniproductid",null).eq("ibizuniproductid",ibizuniProductId));
    }

    public boolean saveByIbizuniproduct(IBIZUNIProduct ibizuniProduct,List<IBIZOrderDetail> list) {
        if(list==null)
            return true;
        Set<String> delIds=new HashSet<String>();
        List<IBIZOrderDetail> _update=new ArrayList<IBIZOrderDetail>();
        List<IBIZOrderDetail> _create=new ArrayList<IBIZOrderDetail>();
        for(IBIZOrderDetail before:selectByIbizuniProductId(ibizuniProduct.getIbizuniProductId())){
            delIds.add(before.getIbizOrderDetailId());
        }
        for(IBIZOrderDetail sub:list) {
            sub.setIbizuniProductId(ibizuniProduct.getIbizuniProductId());
            sub.setIbizuniproduct(ibizuniProduct);
            if(ObjectUtils.isEmpty(sub.getIbizOrderDetailId()))
                sub.setIbizOrderDetailId((String)sub.getDefaultKey(true));
            if(delIds.contains(sub.getIbizOrderDetailId())) {
                delIds.remove(sub.getIbizOrderDetailId());
                _update.add(sub);
            }
            else
                _create.add(sub);
        }
        if(_update.size()>0 && (!getSelf().updateBatch(_update)))
            return false;
        if(_create.size()>0 && (!getSelf().createBatch(_create)))
            return false;
        if(delIds.size()>0 && (!getSelf().removeBatch(delIds)))
            return false;
        return true;
    }



    /**
    * 更新父数据（实体关系属性映射）
    * @param et
    */
    private void updateParentData(IBIZOrderDetail et){
    }

    private void updateParentDataBatch(List <IBIZOrderDetail> entities){
    }

    @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;
    }

}