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.IBIZSample0007;
import cn.ibizlab.core.sample.filter.IBIZSample0007SearchContext;
import cn.ibizlab.core.sample.service.IIBIZSample0007Service;

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.IBIZSample0007Mapper;
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("IBIZSample0007ServiceImpl")
public class IBIZSample0007ServiceImpl extends ServiceImpl<IBIZSample0007Mapper, IBIZSample0007> implements IIBIZSample0007Service {

    @Autowired
    @Lazy
    protected cn.ibizlab.core.sample.service.IIBIZSample0006Service ibizsample0006Service;

    protected int batchSize = 500;

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

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

    @Override
    @Transactional
    public boolean update(IBIZSample0007 et) {
        fillParentData(et);
        if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("ibizsample0007id", et.getIbizsample0007id()))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getIbizsample0007id()), et);
        return true;
    }

    @Override
    @Transactional
    public void updateBatch(List<IBIZSample0007> list) {
        list.forEach(item->fillParentData(item));
        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 IBIZSample0007 get(String key) {
        IBIZSample0007 et = getById(key);
        if(et == null){
            et = new IBIZSample0007();
            et.setIbizsample0007id(key);
        }
        else {
        }
        return et;
    }

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

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

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

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

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


	@Override
    public List<IBIZSample0007> selectByIbizsample0006id(String ibizsample0006id) {
        return baseMapper.selectByIbizsample0006id(ibizsample0006id);
    }
    @Override
    public void resetByIbizsample0006id(String ibizsample0006id) {
        this.update(new UpdateWrapper<IBIZSample0007>().set("ibizsample0006id",null).eq("ibizsample0006id",ibizsample0006id));
    }

    @Override
    public void resetByIbizsample0006id(Collection<String> ids) {
        this.update(new UpdateWrapper<IBIZSample0007>().set("ibizsample0006id",null).in("ibizsample0006id",ids));
    }

    @Override
    public void removeByIbizsample0006id(String ibizsample0006id) {
        this.remove(new QueryWrapper<IBIZSample0007>().eq("ibizsample0006id",ibizsample0006id));
    }


    /**
     * 查询集合 当前公文
     */
    @Override
    public Page<IBIZSample0007> searchCurGW(IBIZSample0007SearchContext context) {
        fillWFTaskContext(context);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IBIZSample0007> pages=baseMapper.searchCurGW(context.getPages(),context,context.getSelectCond());
        return new PageImpl<IBIZSample0007>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

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


    @Autowired
    private cn.ibizlab.util.client.IBZWFFeignClient ibzwfFeignClient;

    /**
     * 查询工作流待办
     * @param context
     */
    private void fillWFTaskContext(IBIZSample0007SearchContext context){

        if(!StringUtils.isEmpty(context.getUserTaskId()) && !StringUtils.isEmpty(context.getProcessDefinitionKey())){
            List<String> businessKeys= ibzwfFeignClient.getbusinesskeysByUserId("demosys", cn.ibizlab.util.security.AuthenticationUser.getAuthenticationUser().getUserid(),"ibizsample0007s",context.getProcessDefinitionKey(),context.getUserTaskId());
            if(businessKeys.size()>0){
                context.getSelectCond().in("ibizsample0007id",businessKeys);
            }
            else{
                context.getSelectCond().apply("1<>1");
            }
        }
    }

    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(IBIZSample0007 et){
        //实体关系[DER1N_IBIZSAMPLE0007_IBIZSAMPLE0006_IBIZSAMPLE0006ID]
        if(!ObjectUtils.isEmpty(et.getIbizsample0006id())){
            cn.ibizlab.core.sample.domain.IBIZSample0006 ibizsample0006=et.getIbizsample0006();
            if(ObjectUtils.isEmpty(ibizsample0006)){
                cn.ibizlab.core.sample.domain.IBIZSample0006 majorEntity=ibizsample0006Service.get(et.getIbizsample0006id());
                et.setIbizsample0006(majorEntity);
                ibizsample0006=majorEntity;
            }
            et.setDnum(ibizsample0006.getDnum());
            et.setDdate(ibizsample0006.getDdate());
            et.setDtext(ibizsample0006.getDtext());
            et.setIbizsample0006name(ibizsample0006.getIbizsample0006name());
        }
    }




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

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




}



