
package com.lideeyunji.core.framework.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.lideeyunji.core.framework.config.aspect.enhance.LideeYunJiSqlEnhance;
import com.lideeyunji.core.framework.entity.EnhanceSqlEntity;
import com.lideeyunji.core.framework.entity.HistoryDbformEntity;
import com.lideeyunji.core.framework.mapper.EnhanceSqlMapper;
import com.lideeyunji.core.framework.mapper.HistoryDbFormMapper;
import com.lideeyunji.core.framework.service.IEnhanceSqlService;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.tool.framework.common.constant.lideeYunJiBaseConstant;
import com.lideeyunji.tool.framework.yunji.adapter.IlideeYunjiAdapter;
import com.lideeyunji.tool.framework.yunji.annotation.lideeYunjiCache;
import com.lideeyunji.tool.framework.yunji.constant.lideeRedisConstants;
import com.lideeyunji.tool.framework.yunji.enums.YNEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


/**
 * @author JX
 * @create 2024-03-06 9:55
 * @dedescription:
 */

@Service
public class EnhanceSqlServiceImpl extends ServiceImpl<EnhanceSqlMapper, EnhanceSqlEntity> implements IEnhanceSqlService {

    @Autowired
    private HistoryDbFormMapper historyDbFormMapper;

    @Autowired
    private IlideeYunjiAdapter lideeYunJiAdapter;

    @Override
    public List<EnhanceSqlEntity> getSlectList(Long dbFormId){
        LambdaQueryWrapper<EnhanceSqlEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EnhanceSqlEntity::getDbformId, dbFormId);
        List<EnhanceSqlEntity> list = this.list(wrapper);
        return list;
    }


    //新增sql增强
    @lideeYunjiCache(cacheNames = lideeRedisConstants.REDIS_DBFORM +":*",delCache = true)
    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public void saveEnhanceSql(EnhanceSqlEntity enhanceSqlEntity){
        long id = IdWorker.getId();
        enhanceSqlEntity.setId(id);
        this.save(enhanceSqlEntity);
        //加入插件管理
        LideeYunJiSqlEnhance.addEnhance(enhanceSqlEntity);
        //加历史记录
        this.saveHistoryLog(id,enhanceSqlEntity);
    }

    //编辑sql增强
    @lideeYunjiCache(cacheNames = lideeRedisConstants.REDIS_DBFORM +":*",delCache = true)
    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public void updateEnhanceSql(EnhanceSqlEntity enhanceSqlEntity){
        this.updateById(enhanceSqlEntity);
        if (Func.equals(enhanceSqlEntity.getActiveStatus(), YNEnum.Y.getCode())){
           LideeYunJiSqlEnhance.updateEnhance(enhanceSqlEntity);
        } else {
           LideeYunJiSqlEnhance.removeEnhance(enhanceSqlEntity);
        }
        //加历史记录
        this.saveHistoryLog(enhanceSqlEntity.getId(),enhanceSqlEntity);
    }

    @DS(lideeYunJiBaseConstant.DS_lideeyunji)
    @Override
    public void copy(Long sourceFormIdId,Long targetFormIdId){
        LambdaQueryWrapper<EnhanceSqlEntity> sqlWrapper=new LambdaQueryWrapper<>();
        sqlWrapper.eq(EnhanceSqlEntity::getDbformId,sourceFormIdId);
        sqlWrapper.orderByAsc(EnhanceSqlEntity::getId);
        List<EnhanceSqlEntity> sqlEntityList = this.list(sqlWrapper);
        //清空默认值并修改dbformId值
        sqlEntityList.stream().forEach(sqlEntity->{
            sqlEntity.setDbformId(targetFormIdId);
            sqlEntity.setId(null);
            sqlEntity.setTenantId(null);
            sqlEntity.setCreateDept(null);
            sqlEntity.setCreateTime(null);
            sqlEntity.setCreateUser(null);
            sqlEntity.setUpdateTime(null);
            sqlEntity.setUpdateUser(null);
            sqlEntity.setIsDeleted(null);
        });
        this.saveBatch(sqlEntityList);
    }


    //保存历史记录
    private void saveHistoryLog(Long jsId, EnhanceSqlEntity enhanceSqlEntity){

        HistoryDbformEntity entity=new HistoryDbformEntity();
        entity.setId(IdWorker.getId());
        entity.setTenantId(lideeYunJiAdapter.getTenantId());
        entity.setCreateUser(lideeYunJiAdapter.getOnlineUserId());
        entity.setCreateTime(LocalDateTime.now());
        entity.setCreateUserName(lideeYunJiAdapter.getOnlineUserName());

        entity.setDbformId(enhanceSqlEntity.getDbformId());
        entity.setServiceType("sql");
        entity.setServiceId(jsId);
        entity.setServiceJson(Func.json2Str(enhanceSqlEntity));

        historyDbFormMapper.insert(entity);
    }

    @Override
    public List<EnhanceSqlEntity> getAllSqlEnhance() {
        LambdaQueryWrapper<EnhanceSqlEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EnhanceSqlEntity::getActiveStatus, YNEnum.Y.getCode());
        wrapper.isNotNull(EnhanceSqlEntity::getExecuteSql);
        wrapper.isNotNull(EnhanceSqlEntity::getDbformId);
        List<EnhanceSqlEntity> enhanceSqlEntities = baseMapper.selectList(wrapper);
        return enhanceSqlEntities;
    }

    //批量删除
    @lideeYunjiCache(cacheNames = lideeRedisConstants.REDIS_DBFORM +":*",delCache = true)
    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public void removeByIds(List<Long> ids){
        for(Long id:ids){
            baseMapper.deleteById(id);
        }
    }
}
