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 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.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.IIBIZOrderDetailService;

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


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.core.sample.mapper.IBIZOrderDetailMapper;
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("IBIZOrderDetailServiceImpl")
public class IBIZOrderDetailServiceImpl extends ServiceImpl<IBIZOrderDetailMapper, IBIZOrderDetail> implements IIBIZOrderDetailService {

    @Autowired
    @Lazy
    protected cn.ibizlab.core.sample.service.IIBIZOrderService ibizorderService;
    @Autowired
    @Lazy
    protected cn.ibizlab.core.sample.service.IIBIZUNIProductService ibizuniproductService;

    @Autowired
    @Lazy
    protected cn.ibizlab.core.sample.service.logic.IIBIZOrderDetailCountMoneyLogic countmoneyLogic;

    @Autowired
    @Lazy
    protected cn.ibizlab.core.sample.service.logic.IIBIZOrderDetailGetUnitAndPriceLogic getunitandpriceLogic;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(IBIZOrderDetail et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getIbizorderdetailid()), et);
        updateParentData(et);
        return true;
    }

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

    @Override
    @Transactional
    public IBIZOrderDetail createTemp(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public IBIZOrderDetail createTempMajor(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public boolean update(IBIZOrderDetail et) {
        fillParentData(et);
        if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("ibizorderdetailid", et.getIbizorderdetailid()))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getIbizorderdetailid()), et);
        updateParentData(et);
        return true;
    }

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

    @Override
    @Transactional
    public IBIZOrderDetail updateTemp(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public IBIZOrderDetail updateTempMajor(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        IBIZOrderDetail entity = this.get(key);
        boolean result = removeById(key);
        updateParentData(entity);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<String> idList) {
        List<IBIZOrderDetail> entities= baseMapper.selectBatchIds(idList);
        removeByIds(idList);
        updateParentDataBatch(entities);
    }

    @Override
    @Transactional
    public IBIZOrderDetail removeTemp(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public IBIZOrderDetail removeTempMajor(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public IBIZOrderDetail get(String key) {
        IBIZOrderDetail et = getById(key);
        if(et == null){
            et = new IBIZOrderDetail();
            et.setIbizorderdetailid(key);
        }
        else {
        }
        return et;
    }

    @Override
    @Transactional
    public IBIZOrderDetail getTemp(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public IBIZOrderDetail getTempMajor(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

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

    @Override
    @Transactional
    public IBIZOrderDetail getDraftTemp(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public IBIZOrderDetail getDraftTempMajor(IBIZOrderDetail et) {
        //自定义代码
        return et;
    }

    @Override
    public boolean checkKey(IBIZOrderDetail et) {
        return (!ObjectUtils.isEmpty(et.getIbizorderdetailid())) && (!Objects.isNull(this.getById(et.getIbizorderdetailid())));
    }
    @Override
    @Transactional
    public IBIZOrderDetail countMoney(IBIZOrderDetail et) {
        countmoneyLogic.execute(et);
         return et ;
    }

    @Override
    @Transactional
    public IBIZOrderDetail getUnitAndPrice(IBIZOrderDetail et) {
        getunitandpriceLogic.execute(et);
         return et ;
    }

    @Override
    @Transactional
    public boolean save(IBIZOrderDetail et) {
        if(!saveOrUpdate(et)) {
            return false;
        }
        return true;
    }

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

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

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


	@Override
    public List<IBIZOrderDetail> selectByIbizorderid(String ibizorderid) {
        return baseMapper.selectByIbizorderid(ibizorderid);
    }
    @Override
    public List<IBIZOrderDetail> selectByIbizorderid(Collection<String> ids) {
        return this.list(new QueryWrapper<IBIZOrderDetail>().in("ibizorderid",ids));
    }

    @Override
    public void removeByIbizorderid(String ibizorderid) {
        this.remove(new QueryWrapper<IBIZOrderDetail>().eq("ibizorderid",ibizorderid));
    }

	@Override
    public List<IBIZOrderDetail> selectByIbizuniproductid(String ibizuniproductid) {
        return baseMapper.selectByIbizuniproductid(ibizuniproductid);
    }
    @Override
    public List<IBIZOrderDetail> selectByIbizuniproductid(Collection<String> ids) {
        return this.list(new QueryWrapper<IBIZOrderDetail>().in("ibizuniproductid",ids));
    }

    @Override
    public void removeByIbizuniproductid(String ibizuniproductid) {
        this.remove(new QueryWrapper<IBIZOrderDetail>().eq("ibizuniproductid",ibizuniproductid));
    }


    /**
     * 查询集合 测试明细打印
     */
    @Override
    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());
    }

    /**
     * 查询集合 DEFAULT
     */
    @Override
    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());
    }

    /**
     * 查询集合 查询订单明细中产品数量
     */
    @Override
    public Page<IBIZOrderDetail> searchLOGIC_0007(IBIZOrderDetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrderDetail> pages=baseMapper.searchLOGIC_0007(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrderDetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 x
     */
    @Override
    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());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(IBIZOrderDetail et){
        //实体关系[DER1N_IBIZORDERDETAIL_IBIZORDER_IBIZORDERID]
        if(!ObjectUtils.isEmpty(et.getIbizorderid())){
            cn.ibizlab.core.sample.domain.IBIZOrder ibizorder=et.getIbizorder();
            if(ObjectUtils.isEmpty(ibizorder)){
                cn.ibizlab.core.sample.domain.IBIZOrder majorEntity=ibizorderService.get(et.getIbizorderid());
                et.setIbizorder(majorEntity);
                ibizorder=majorEntity;
            }
            et.setOrderuid(ibizorder.getOrderuid());
            et.setIbizordername(ibizorder.getIbizordername());
        }
        //实体关系[DER1N_IBIZORDERDETAIL_IBIZUNIPRODUCT_IBIZUNIPRODUCTID]
        if(!ObjectUtils.isEmpty(et.getIbizuniproductid())){
            cn.ibizlab.core.sample.domain.IBIZUNIProduct ibizuniproduct=et.getIbizuniproduct();
            if(ObjectUtils.isEmpty(ibizuniproduct)){
                cn.ibizlab.core.sample.domain.IBIZUNIProduct majorEntity=ibizuniproductService.get(et.getIbizuniproductid());
                et.setIbizuniproduct(majorEntity);
                ibizuniproduct=majorEntity;
            }
            et.setUnitprice(ibizuniproduct.getUnitprice());
            et.setUnit(ibizuniproduct.getUnit());
            et.setIbizuniproductname(ibizuniproduct.getIbizuniproductname());
        }
    }

    /**
     * 更新父数据（实体关系属性映射）
     * @param et
     */
    private void updateParentData(IBIZOrderDetail et){
        //实体关系[DER1N_IBIZORDERDETAIL_IBIZORDER_IBIZORDERID]
        if(!ObjectUtils.isEmpty(et.getIbizorderid())){
            cn.ibizlab.core.sample.domain.IBIZOrder ibizorder=new cn.ibizlab.core.sample.domain.IBIZOrder();
            List<Object> objects_0 = baseMapper.selectObjs(new QueryWrapper().select("sum(amount)").eq(true,"ibizorderid",et.getIbizorderid()));
            if(!ObjectUtils.isEmpty(objects_0) && objects_0.size()>0){
                ibizorder.set("amount",objects_0.get(0));
            }
            ibizorder.set("detailnum",baseMapper.selectCount(new QueryWrapper().eq(true,"ibizorderid",et.getIbizorderid())));
            ibizorder.set("ibizorderid",et.getIbizorderid());
            ibizorderService.update(ibizorder);
        }
        //实体关系[DER1N_IBIZORDERDETAIL_IBIZUNIPRODUCT_IBIZUNIPRODUCTID]
        if(!ObjectUtils.isEmpty(et.getIbizuniproductid())){
        }
    }

    /**
     * 批量更新父数据（实体关系属性映射）
     * @param entities
     */
    private void updateParentDataBatch(List <IBIZOrderDetail> entities){
        Map <Object,IBIZOrderDetail> map =new HashMap<>();
        if(entities.size()>0){
            for(IBIZOrderDetail entity: entities){
                 //实体关系[DER1N_IBIZORDERDETAIL_IBIZORDER_IBIZORDERID]
                 if(!ObjectUtils.isEmpty(entity.getIbizorderid()) && !map.containsKey(entity.getIbizorderid())){
                    map.put(entity.getIbizorderid(),entity);
                 }
                 //实体关系[DER1N_IBIZORDERDETAIL_IBIZUNIPRODUCT_IBIZUNIPRODUCTID]
                 if(!ObjectUtils.isEmpty(entity.getIbizuniproductid()) && !map.containsKey(entity.getIbizuniproductid())){
                    map.put(entity.getIbizuniproductid(),entity);
                 }
            }
            if(map.size()>0){
                map.values().forEach(entity -> updateParentData(entity));
            }
        }
    }


    @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<IBIZOrderDetail> getIbizorderdetailByIds(List<String> ids) {
         return this.listByIds(ids);
    }

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




}



