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.IBIZBOOK;
import cn.ibizlab.core.sample.filter.IBIZBOOKSearchContext;
import cn.ibizlab.core.sample.service.IIBIZBOOKService;

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.IBIZBOOKMapper;
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("IBIZBOOKServiceImpl")
public class IBIZBOOKServiceImpl extends ServiceImpl<IBIZBOOKMapper, IBIZBOOK> implements IIBIZBOOKService {


    protected int batchSize = 500;

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

    @Override
    @Transactional
    public void createBatch(List<IBIZBOOK> list) {
        this.saveBatch(list, batchSize);
    }

    @Override
    @Transactional
    public boolean update(IBIZBOOK et) {
        if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("ibizbookid", et.getIbizbookid()))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getIbizbookid()), et);
        return true;
    }

    @Override
    @Transactional
    public void updateBatch(List<IBIZBOOK> list) {
        updateBatchById(list, batchSize);
    }

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

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

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

    @Override
    public IBIZBOOK getDraft(IBIZBOOK et) {
        return et;
    }

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

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

    @Override
    @Transactional
    public boolean saveBatch(Collection<IBIZBOOK> list) {
        saveOrUpdateBatch(list,batchSize);
        return true;
    }

    @Override
    @Transactional
    public void saveBatch(List<IBIZBOOK> list) {
        saveOrUpdateBatch(list,batchSize);
    }

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



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







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

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

    @Autowired
    @Lazy
    IIBIZBOOKService proxyService;

    @Value("${ibiz.syncImportLimit:1000}")
    private int syncImportLimit;

    /**
     * 上传数据检查
     * @param entities
     * @param isIgnoreError
     * @return
     */
    private JSONObject testImportData(List<IBIZBOOK> entities,boolean isIgnoreError) {

        JSONObject rs=new JSONObject();
        Set ids=new HashSet<>();
        List<String> errorMsgs = new ArrayList<>();
        List<Integer> errorLines = new ArrayList<>();
        List<IBIZBOOK> duplicateKeys=new ArrayList<>();
        String keyField= DEFieldCacheMap.getDEKeyField(IBIZBOOK.class);
        if(ObjectUtils.isEmpty(keyField)){
            errorLines.add(1);
            rs.put("rst", 1);
            rs.put("msg", "数据导入失败，未能获取到实体[IBIZBOOK]的主键属性");
            rs.put("errorLines", errorLines);
            return rs;
        }
        //主键重复性判断.外键约束判断（上传数据自身的检查/数据库的检查）
        for(int i=0;i<entities.size();i++) {
            IBIZBOOK entity = entities.get(i);
            Object id = entity.getIbizbookid();
            if(ObjectUtils.isEmpty(id)) {
                id = entity.getDefaultKey(true);
                if(ObjectUtils.isEmpty(id)){
                    Integer lineNum = i + 1;
                    errorLines.add(lineNum);
                    errorMsgs.add("第" + lineNum + "行：无法获取当前数据主键。");
                    continue;
                }
                else{
                    entity.setIbizbookid((String) id);
                }
            }
            if(!ids.contains(id)){
                ids.add(id);
            }
            else{
                Integer lineNum = i + 1;
                errorLines.add(lineNum);
                errorMsgs.add("第" + lineNum + "行：导入数据之间存在重复数据。");
                if(isIgnoreError){
                    duplicateKeys.add(entity);
                    continue;
                }
                else{
                    break;
                }
            }
        }
        if(duplicateKeys.size()>0){
            for(IBIZBOOK duplicateKey:duplicateKeys){
                entities.remove(duplicateKey);
            }
        }
        if (errorMsgs.size() > 0) {
            rs.put("rst", 1);
            rs.put("msg", String.join("<br>", errorMsgs));
            rs.put("errorLines", errorLines);
            return rs;
        }
        rs.put("rst", 0);
        return rs;
    }

    /**
     * 实体数据导入
     * @param entities
     * @param batchSize
     * @param isIgnoreError
     * @return
     */
    @Override
    @Transactional
    public JSONObject importData(List<IBIZBOOK> entities, int batchSize ,boolean isIgnoreError) {
        if(entities.size()>syncImportLimit){
            proxyService.asyncImportData(entities,batchSize,isIgnoreError);
            JSONObject rs=new JSONObject();
            rs.put("rst", 0);
            rs.put("msg",String.format("当前导入数据已超过同步导入数量上限[%s]，系统正在进行异步导入，请稍后!",syncImportLimit));
            rs.put("data",entities);
            return rs;
        }
        else{
            return syncImportData(entities,batchSize,isIgnoreError);
        }
    }

    @Override
    @Transactional
    public void asyncImportData(List<IBIZBOOK> entities, int batchSize ,boolean isIgnoreError){
        executeImportData(entities,batchSize,isIgnoreError);
    }

    @Transactional
    public JSONObject syncImportData(List<IBIZBOOK> entities, int batchSize ,boolean isIgnoreError){
        return executeImportData(entities,batchSize,isIgnoreError);
    }

    @Transactional
    public JSONObject executeImportData(List<IBIZBOOK> entities, int batchSize ,boolean isIgnoreError) {
        JSONObject rs=testImportData(entities,isIgnoreError);
        if(rs.getInteger("rst")==1 && !isIgnoreError) {
            return rs;
        }
        List<IBIZBOOK> tempDEList=new ArrayList<>();
        Set tempIds=new HashSet<>();

        for(int i=0;i<entities.size();i++) {
            IBIZBOOK entity = entities.get(i);
            tempDEList.add(entity);
            Object id=entity.getIbizbookid();
            if(!ObjectUtils.isEmpty(id)) {
                tempIds.add(id);
            }
            if(tempDEList.size()>=batchSize || (tempDEList.size()<batchSize && i==entities.size()-1)){
                commit(tempDEList,tempIds);
                tempDEList.clear();
                tempIds.clear();
                }
            }
        rs.put("rst", 0);
        rs.put("data",entities);
        return rs;
    }

    /**
     * 批量提交
     * @param entities 数据
     * @param ids 要提交数据的id
     */
    @Transactional
    public void commit(List<IBIZBOOK> entities, Set ids){
        List<IBIZBOOK> _create=new ArrayList<>();
        List<IBIZBOOK> _update=new ArrayList<>();
        Set oldIds=new HashSet<>();
        if(ids.size()>0){
            List<IBIZBOOK> oldEntities=this.listByIds(ids);
            for(IBIZBOOK entity:oldEntities){
                oldIds.add(entity.getIbizbookid());
            }
        }
        for(IBIZBOOK entity:entities){
            Object id=entity.getIbizbookid();
            if(oldIds.contains(id)) {
                _update.add(entity);
            }
            else {
                _create.add(entity);
            }
        }
        if(_update.size()>0) {
            proxyService.updateBatch(_update);
        }
        if(_create.size()>0) {
            proxyService.createBatch(_create);
        }
    }



}



