package com.liangjian.dataplatform.member.service.impl;

import com.liangjian.dataplatform.member.constant.DatabaseUrls;
import com.liangjian.dataplatform.member.entity.po.primary.SqlEntity;
import com.liangjian.dataplatform.member.entity.pojo.DataBaseInfo;
import com.liangjian.dataplatform.member.entity.vo.datanodes.MetaDataSource;
import com.liangjian.dataplatform.member.entity.vo.detailvo.DataSourceDetailVo;
import com.liangjian.dataplatform.member.entity.vo.detailvo.DetailVo;
import com.liangjian.dataplatform.member.entity.vo.request.BirdGirdRequest;
import com.liangjian.dataplatform.member.entity.vo.response.BirdGirdTableResponse;
import com.liangjian.dataplatform.member.safe.Tuple;
import com.liangjian.dataplatform.member.service.IBirdGirdService;
import com.liangjian.dataplatform.member.service.IMetaCoreQueryService;
import com.liangjian.dataplatform.member.service.ISqlEntityService;
import com.liangjian.dataplatform.member.util.SimpleSqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 黄子奇
 * @Date: 2019/11/4
 */
@Service
public class BirdGirdService implements IBirdGirdService {

    @Autowired
    private IMetaCoreQueryService iMetaCoreQueryService;
    @Autowired
    private ISqlEntityService iSqlEntityService;

    @Override
    public BirdGirdTableResponse readSql(String dsId, String sqlId, BirdGirdRequest birdGirdRequest) {
        DetailVo detailVo = iMetaCoreQueryService.getNodeDetail(dsId);
        if(!(detailVo instanceof DataSourceDetailVo)) {
            throw new RuntimeException("dsId 对应的不是数据源的节点");
        }
        MetaDataSource dataSource = (MetaDataSource) detailVo.getRealNode();
        DataBaseInfo dataBaseInfo = dataSource.getEntry();
        String host = dataBaseInfo.getHost() + ":" + dataBaseInfo.getPort();
        String url = DatabaseUrls.getByType(dataSource.getType())
                .getUrl(host,dataBaseInfo.getServerName());

        SqlEntity sqlEntity = iSqlEntityService.queryById(sqlId);
        if(sqlEntity == null) {
            System.out.println("没有查询到sql配置");
            BirdGirdTableResponse response = new BirdGirdTableResponse();
            response.setItems(Collections.emptyList());
            response.setTotalCount(0L);
            return response;
        }

        String whereClause = birdGirdRequest.filtersToSql();
        String sql = sqlEntity.getSql() + " where 1 = 1 " + whereClause;
        List<Object> values = birdGirdRequest.getFilters()
                .stream()
                .map(i -> i.getPreValue())
                .collect(Collectors.toList());
        try {
            Map<String,Object> result = SimpleSqlUtil.getDataFromDatabaseWrapperPre(url,dataBaseInfo.getUser(),dataBaseInfo.getPwd(), sql, values, false,
                    birdGirdRequest.getPageIndex(), birdGirdRequest.getPageSize());
            BirdGirdTableResponse response = BirdGirdTableResponse.fromSqlResultMap(result);
            return response;
        } catch (Exception ex) {
            ex.printStackTrace();
            BirdGirdTableResponse response = new BirdGirdTableResponse();
            response.setItems(Collections.emptyList());
            response.setTotalCount(0L);
            return response;
        }
    }

    @Override
    public Tuple<String,BirdGirdTableResponse> readSqlUnpaged(String dsId, String sqlId, BirdGirdRequest birdGirdRequest) {
        DetailVo detailVo = iMetaCoreQueryService.getNodeDetail(dsId);
        if(!(detailVo instanceof DataSourceDetailVo)) {
            throw new RuntimeException("dsId 对应的不是数据源的节点");
        }
        MetaDataSource dataSource = (MetaDataSource) detailVo.getRealNode();
        DataBaseInfo dataBaseInfo = dataSource.getEntry();
        String host = dataBaseInfo.getHost() + ":" + dataBaseInfo.getPort();
        String url = DatabaseUrls.getByType(dataSource.getType())
                .getUrl(host,dataBaseInfo.getServerName());

        SqlEntity sqlEntity = iSqlEntityService.queryById(sqlId);
        if(sqlEntity == null) {
            System.out.println("没有查询到sql配置");
            BirdGirdTableResponse response = new BirdGirdTableResponse();
            response.setItems(Collections.emptyList());
            response.setTotalCount(0L);
            return new Tuple<>("",response);
        }

        String desc = sqlEntity.getDescription();
        String whereClause = birdGirdRequest.filtersToSql();
        String sql = sqlEntity.getSql() + " where 1 = 1 " + whereClause;
        List<Object> values = birdGirdRequest.getFilters()
                .stream()
                .map(i -> i.getPreValue())
                .collect(Collectors.toList());
        try {
            Map<String,Object> result = SimpleSqlUtil.getDataFromDatabaseWrapperUnpagedPre(url,dataBaseInfo.getUser(),dataBaseInfo.getPwd(), sql,values, false);
            BirdGirdTableResponse response = BirdGirdTableResponse.fromSqlResultMap(result);
            return new Tuple<>(desc,response);
        } catch (Exception ex) {
            ex.printStackTrace();
            BirdGirdTableResponse response = new BirdGirdTableResponse();
            response.setItems(Collections.emptyList());
            response.setTotalCount(0L);
            return new Tuple<>(desc,response);
        }
    }
}
