package cn.ibizlab.core.lite.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.lite.domain.MetaEntity;
import cn.ibizlab.core.lite.filter.MetaEntitySearchContext;
import cn.ibizlab.core.lite.service.IMetaEntityService;

import cn.ibizlab.util.helper.CachedBeanCopier;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import com.alibaba.fastjson.JSONObject;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.core.lite.mapper.MetaEntityMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.springframework.util.StringUtils;

/**
 * 实体[实体] 服务对象接口实现
 */
@Slf4j
@Service("MetaEntityServiceImpl")
public class MetaEntityServiceImpl extends ServiceImpl<MetaEntityMapper, MetaEntity> implements IMetaEntityService {

    @Autowired
    @Lazy
    protected cn.ibizlab.core.lite.service.ITableSyncService tablesyncService;
    @Autowired
    @Lazy
    protected cn.ibizlab.core.lite.service.IMetaDataSetService metadatasetService;
    @Autowired
    @Lazy
    protected cn.ibizlab.core.lite.service.IMetaFieldService metafieldService;
    @Autowired
    @Lazy
    protected cn.ibizlab.core.lite.service.IMetaRelationshipService metarelationshipService;
    @Autowired
    @Lazy
    protected cn.ibizlab.core.lite.service.IDstDataSourceService dstdatasourceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.core.lite.service.IDstSystemService dstsystemService;
    @Autowired
    @Lazy
    protected cn.ibizlab.core.lite.service.IMetaModuleService metamoduleService;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(MetaEntity et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et))) {
            return false;
        }
        metadatasetService.saveByEntityId(et.getEntityId(), et.getDataSets());
        metafieldService.saveByEntityId(et.getEntityId(), et.getFields());
        metarelationshipService.saveByEntityId(et.getEntityId(), et.getParentEntitys());
        metarelationshipService.saveByRefEntityId(et.getEntityId(), et.getSubEntitys());
        CachedBeanCopier.copy(get(et.getEntityId()), et);
        return true;
    }

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

    @Override
    @Transactional
    public boolean update(MetaEntity et) {
        fillParentData(et);
        if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("entityid", et.getEntityId()))) {
            return false;
        }
        metadatasetService.saveByEntityId(et.getEntityId(), et.getDataSets());
        metafieldService.saveByEntityId(et.getEntityId(), et.getFields());
        metarelationshipService.saveByEntityId(et.getEntityId(), et.getParentEntitys());
        metarelationshipService.saveByRefEntityId(et.getEntityId(), et.getSubEntitys());
        CachedBeanCopier.copy(get(et.getEntityId()), et);
        return true;
    }

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

    @Override
    @Transactional
    public boolean remove(String key) {
        metadatasetService.removeByEntityId(key) ;
        metafieldService.removeByEntityId(key) ;
        metarelationshipService.removeByEntityId(key) ;
        metarelationshipService.removeByRefEntityId(key) ;
        boolean result = removeById(key);
        return result ;
    }

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

    @Override
    @Transactional
    public MetaEntity get(String key) {
        MetaEntity et = getById(key);
        if (et == null) {
            throw new BadRequestAlertException("数据不存在", this.getClass().getSimpleName(), key);
        }
        else {
            et.setDataSets(metadatasetService.selectByEntityId(key));
            et.setFields(metafieldService.selectByEntityId(key));
            et.setParentEntitys(metarelationshipService.selectByEntityId(key));
            et.setSubEntitys(metarelationshipService.selectByRefEntityId(key));
        }
        return et;
    }

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

    @Override
    public boolean checkKey(MetaEntity et) {
        return (!ObjectUtils.isEmpty(et.getEntityId())) && (!Objects.isNull(this.getById(et.getEntityId())));
    }
    @Override
    @Transactional
    public MetaEntity getDefaultModel(MetaEntity et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public boolean getDefaultModelBatch(List<MetaEntity> etList) {
        for(MetaEntity et : etList) {
            getDefaultModel(et);
        }
        return true;
    }

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

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

    @Override
    @Transactional
    public boolean saveBatch(Collection<MetaEntity> list) {
        list.forEach(item->fillParentData(item));
        List<MetaEntity> create = new ArrayList<>();
        List<MetaEntity> update = new ArrayList<>();
        for (MetaEntity et : list) {
            if (ObjectUtils.isEmpty(et.getEntityId()) || ObjectUtils.isEmpty(getById(et.getEntityId()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
        return true;
    }

    @Override
    @Transactional
    public void saveBatch(List<MetaEntity> list) {
        list.forEach(item->fillParentData(item));
        List<MetaEntity> create = new ArrayList<>();
        List<MetaEntity> update = new ArrayList<>();
        for (MetaEntity et : list) {
            if (ObjectUtils.isEmpty(et.getEntityId()) || ObjectUtils.isEmpty(getById(et.getEntityId()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
    }


	@Override
    public List<MetaEntity> selectByDsId(String ds_id) {
        return baseMapper.selectByDsId(ds_id);
    }
    @Override
    public void removeByDsId(String ds_id) {
        this.remove(new QueryWrapper<MetaEntity>().eq("dsid",ds_id));
    }

	@Override
    public List<MetaEntity> selectBySystemId(String pssystemid) {
        return baseMapper.selectBySystemId(pssystemid);
    }
    @Override
    public void removeBySystemId(String pssystemid) {
        this.remove(new QueryWrapper<MetaEntity>().eq("systemid",pssystemid));
    }

	@Override
    public List<MetaEntity> selectByModuleId(String id) {
        return baseMapper.selectByModuleId(id);
    }
    @Override
    public void removeByModuleId(String id) {
        this.remove(new QueryWrapper<MetaEntity>().eq("moduleid",id));
    }


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



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    public void fillParentData(MetaEntity et){
        //实体关系[DER1N_META_ENTITY_DST_DATASOURCE_DSID]
        if(!ObjectUtils.isEmpty(et.getDsId())){
            cn.ibizlab.core.lite.domain.DstDataSource dataSource=et.getDataSource();
            if(ObjectUtils.isEmpty(dataSource)){
                cn.ibizlab.core.lite.domain.DstDataSource majorEntity=dstdatasourceService.getById(et.getDsId());
                et.setDataSource(majorEntity);
                dataSource=majorEntity;
            }
            et.setDsName(dataSource.getDsName());
        }
        //实体关系[DER1N_META_ENTITY_DST_SYSTEM_SYSTEMID]
        if(!ObjectUtils.isEmpty(et.getSystemId())){
            cn.ibizlab.core.lite.domain.DstSystem system=et.getSystem();
            if(ObjectUtils.isEmpty(system)){
                cn.ibizlab.core.lite.domain.DstSystem majorEntity=dstsystemService.getById(et.getSystemId());
                et.setSystem(majorEntity);
                system=majorEntity;
            }
            et.setSystemName(system.getPssystemname());
        }
        //实体关系[DER1N_META_ENTITY_META_MODULE_MODULEID]
        if(!ObjectUtils.isEmpty(et.getModuleId())){
            cn.ibizlab.core.lite.domain.MetaModule module=et.getModule();
            if(ObjectUtils.isEmpty(module)){
                cn.ibizlab.core.lite.domain.MetaModule majorEntity=metamoduleService.getById(et.getModuleId());
                et.setModule(majorEntity);
                module=majorEntity;
            }
            et.setModuleName(module.getName());
        }
    }




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





    public IMetaEntityService getProxyService() {
        return cn.ibizlab.util.security.SpringContextHolder.getBean(this.getClass());
    }
}



