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.IBIZOrder;
import cn.ibizlab.core.sample.filter.IBIZOrderSearchContext;
import cn.ibizlab.core.sample.service.IBIZOrderService;
import cn.ibizlab.core.sample.mapper.IBIZOrderMapper;
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.IBIZCustomer;
import cn.ibizlab.core.sample.service.IBIZCustomerService;


/**
 * 实体[订单] 服务对象接口实现
 */
@Slf4j
@Service("IBIZOrderService")
public class IBIZOrderServiceBase extends ServiceImpl<IBIZOrderMapper,IBIZOrder> implements IBIZOrderService {

    @Autowired
    @Lazy
    protected IBIZCustomerService ibizCustomerService;
   

    protected int batchSize = 500;

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

    public void fillParentData(IBIZOrder et) {
        if(!ObjectUtils.isEmpty(et.getIbizCustomerId())) {
            IBIZCustomer ibizCustomer = et.getIbizcustomer();
            if(!ObjectUtils.isEmpty(ibizCustomer)) {
                et.setIbizCustomerName(ibizCustomer.getIbizCustomerName());   
            }
        }    
    }

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

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

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

    @Transactional
    public boolean update(IBIZOrder et) {
        UpdateWrapper qw=et.getUpdateWrapper(true);
        qw.eq("ibizorderid", et.getIbizOrderId());
        if(!update(et, qw)) {
            return false;
        }
        get(et);
        return true;
    }

    @Transactional
    public boolean updateBatch(List<IBIZOrder> list) {
        updateBatchById(list, batchSize);
        return true;
    }

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

    @Transactional
    public boolean saveBatch(List<IBIZOrder> list) {
        List<IBIZOrder> rt=this.getByEntities(list);
        Set<Serializable> keys=new HashSet<>();
        rt.forEach(et->{
            Serializable key = et.getIbizOrderId();
            if(!ObjectUtils.isEmpty(key))
                keys.add(key);
        });
        List<IBIZOrder> _create=new ArrayList<>();
        List<IBIZOrder> _update=new ArrayList<>();
        list.forEach(et-> {
            Serializable key = et.getIbizOrderId();
            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(IBIZOrder et) {
        String key = et.getIbizOrderId();

        if(!remove(new QueryWrapper<IBIZOrder>()
                .eq("ibizorderid", et.getIbizOrderId())
            )) {
            return false;
        }
        return true ;
    }

    @Transactional
    public boolean removeByEntities(List<IBIZOrder> entities) {
        this.baseMapper.deleteEntities(entities);
        return true;
    }

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

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

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

    @Transactional
    public IBIZOrder updateTempMajor(IBIZOrder 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 IBIZOrder getTemp(String key) {
        return null;
    }

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

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

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

    @Transactional
    public IBIZOrder buiAction(IBIZOrder dto) {
        return dto;
    }

    @Transactional
    public IBIZOrder mulUpdate(IBIZOrder dto) {
        return dto;
    }

    public Page<IBIZOrder> searchCsdy(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchCsdy(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listCsdy(IBIZOrderSearchContext context) {
        return baseMapper.listCsdy(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchCurState30(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchCurState30(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listCurState30(IBIZOrderSearchContext context) {
        return baseMapper.listCurState30(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchDdjetjbb(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchDdjetjbb(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listDdjetjbb(IBIZOrderSearchContext context) {
        return baseMapper.listDdjetjbb(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchDdReport(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchDdReport(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listDdReport(IBIZOrderSearchContext context) {
        return baseMapper.listDdReport(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchDyddmxsjy(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchDyddmxsjy(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listDyddmxsjy(IBIZOrderSearchContext context) {
        return baseMapper.listDyddmxsjy(context,context.getSelectCond());
    }

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

    public Page<IBIZOrder> searchEchartsDefaultDataSource(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchEchartsDefaultDataSource(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listEchartsDefaultDataSource(IBIZOrderSearchContext context) {
        return baseMapper.listEchartsDefaultDataSource(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchGaugeDataSource(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchGaugeDataSource(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listGaugeDataSource(IBIZOrderSearchContext context) {
        return baseMapper.listGaugeDataSource(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchGaugeDataSourceByTime(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchGaugeDataSourceByTime(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listGaugeDataSourceByTime(IBIZOrderSearchContext context) {
        return baseMapper.listGaugeDataSourceByTime(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchLogic22(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchLogic22(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listLogic22(IBIZOrderSearchContext context) {
        return baseMapper.listLogic22(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchRadarDataSource(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchRadarDataSource(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listRadarDataSource(IBIZOrderSearchContext context) {
        return baseMapper.listRadarDataSource(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchShzOrder(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchShzOrder(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listShzOrder(IBIZOrderSearchContext context) {
        return baseMapper.listShzOrder(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchState10(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchState10(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listState10(IBIZOrderSearchContext context) {
        return baseMapper.listState10(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchState30(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchState30(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listState30(IBIZOrderSearchContext context) {
        return baseMapper.listState30(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchState40(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchState40(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listState40(IBIZOrderSearchContext context) {
        return baseMapper.listState40(context,context.getSelectCond());
    }

    public Page<IBIZOrder> searchXecx(IBIZOrderSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZOrder> pages=baseMapper.searchXecx(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZOrder>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }
    public List<IBIZOrder> listXecx(IBIZOrderSearchContext context) {
        return baseMapper.listXecx(context,context.getSelectCond());
    }

    public List<IBIZOrder> selectByIbizCustomerId(String ibizCustomerId) {
        return baseMapper.selectByIbizCustomerId(ibizCustomerId);
    }

    public boolean removeByIbizCustomerId(String ibizCustomerId) {
        return this.remove(new QueryWrapper<IBIZOrder>().eq("ibizcustomerid",ibizCustomerId));
    }

    public boolean resetByIbizCustomerId(String ibizCustomerId) {
        return this.update(new UpdateWrapper<IBIZOrder>().set("ibizcustomerid",null).eq("ibizcustomerid",ibizCustomerId));
    }

    public boolean saveByIbizcustomer(IBIZCustomer ibizCustomer,List<IBIZOrder> list) {
        if(list==null)
            return true;
        Set<String> delIds=new HashSet<String>();
        List<IBIZOrder> _update=new ArrayList<IBIZOrder>();
        List<IBIZOrder> _create=new ArrayList<IBIZOrder>();
        for(IBIZOrder before:selectByIbizCustomerId(ibizCustomer.getIbizCustomerId())){
            delIds.add(before.getIbizOrderId());
        }
        for(IBIZOrder sub:list) {
            sub.setIbizCustomerId(ibizCustomer.getIbizCustomerId());
            sub.setIbizcustomer(ibizCustomer);
            if(ObjectUtils.isEmpty(sub.getIbizOrderId()))
                sub.setIbizOrderId((String)sub.getDefaultKey(true));
            if(delIds.contains(sub.getIbizOrderId())) {
                delIds.remove(sub.getIbizOrderId());
                _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;
    }




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

}