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

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.ISqlExportService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private IBirdGirdService iBirdGirdService;

    @Override
    public Tuple<String,Workbook> exportSql(String dsId, String sqlId, BirdGirdRequest birdGirdRequest) {
        Tuple<String,BirdGirdTableResponse> tuple = getSqlResponse(dsId, sqlId, birdGirdRequest);
        BirdGirdTableResponse tableResponse = tuple.get_2();
        List<Map<String,Object>> tableDatas = tableResponse.getItems();
        Workbook workbook = createExcel(tableDatas);
        return new Tuple<>(tuple.get_1(),workbook);
    }

    protected Tuple<String,BirdGirdTableResponse> getSqlResponse(String dsId, String sqlId, BirdGirdRequest birdGirdRequest) {
        return iBirdGirdService.readSqlUnpaged(dsId, sqlId, birdGirdRequest);
    }

    protected Workbook createExcel(List<Map<String,Object>> tableData) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        //查询出错，直接返回空的excel
        if(tableData.isEmpty()) {
            return workbook;
        }

        //先写表头
        List<String> colNames = new ArrayList<>();
        boolean hasColNames = false;

        for (int k = 0; k < tableData.size(); k++) {
            Map<String,Object> row = tableData.get(k);
            int colCount = row.keySet().size();
            //写表头
            if(!hasColNames) {
                Row excelRow = sheet.createRow(0);
                colNames.addAll(row.keySet());
                for (int i = 0; i < colCount; i++) {
                    Cell cell = excelRow.createCell(i);
                    cell.setCellValue(colNames.get(i));
                }
                hasColNames = true;
            }

            //写数据
            Row excelRow = sheet.createRow(k + 1);
            for (int i = 0; i < colCount; i++) {
                Cell cell = excelRow.createCell(i);
                Object val = row.get(colNames.get(i));
                String data = val == null ? "" : val.toString();
                cell.setCellValue(data);
            }
        }

        return workbook;
    }
}
