package io.renren.modules.dataSet.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import io.minio.PutObjectOptions;
import io.renren.common.utils.MinIoUtils;
import io.renren.modules.dataSet.entity.PreviewData;
import io.renren.modules.dataSet.service.StaticSystemService;
import io.renren.modules.dataSet.upload.NoModelDataListener_pre;
import io.renren.modules.dataSet.upload.UpLoadService;
import io.renren.modules.sys.dao.dataset.DataSetMapper;
import io.renren.modules.sys.entity.dataset.DataSet;
import lgh.springboot.starter.hbase.template.HBaseTemplate;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StaticSystemServiceImpl implements StaticSystemService {


    @Autowired
    DynamicSystemServiceImpl dynamicSystemService;

    @Autowired
    UpLoadService upLoadService;

    @Override
    public String runStaticSave(Map onemap) {
        Map onemap1 = (Map) onemap.get("st_imsql");
        System.out.println(onemap1);
//        {oldname=1_stsum, choosedata={id=0, userID=1, sql=[string_title, number_title], upUrl=E:\test\615\renren-fast\aupload\demo 1.xlsx}}
        Boolean onlyStatic = (Boolean) onemap.get("onlyStatic");
        final String id = onemap1.get("id").toString();
        final String userID = onemap1.get("userID").toString();
        final String[] sqls = onemap1.get("sql").toString().replaceAll("\\[|\\]", "").split(", ");
        final String upUrl = onemap1.get("upUrl").toString();
        final String oldname = onemap1.get("oldFileName").toString();
        final String lastNewFileName = onemap1.get("newFileName").toString();
        final String type = onemap1.get("type").toString();
        String path = System.getProperty("user.dir") + File.separator + "csv" + File.separator + userID;
        // 判断上传路径是否存在
        if (!FileUtil.exist(path)) {
            FileUtil.mkdir(path);
        }

        List<Map<String, Object>> allList = null;
        if ("excel".equals(type)) {
            NoModelDataListener_pre noModelDataListener_pre = new NoModelDataListener_pre(sqls);
            EasyExcel.read(upUrl, noModelDataListener_pre).doReadAll();
            allList = noModelDataListener_pre.getAllList();
        } else if ("word".equals(type)) {
            allList = upLoadService.readWithCsvMapReaderColumns(upUrl, sqls, false);
        } else {
            allList = new ArrayList<>();
        }


        String oldFileName = path + File.separator + oldname + ".csv";
        String newFileName = "";
        for (String sql : sqls) {
            List<String> fileds = new ArrayList<>();
            newFileName = userID + sql; // 不需要设置根路径 已经在 addColumn 中设置了
            fileds.add(sql);
            for (Map<String, Object> stringObjectMap : allList) {
                final String s = stringObjectMap.get(sql).toString();
                fileds.add(s);
            }

            // 数据集不使用系统数据
            final File oldFileNamefile = new File(oldFileName);
            if (onlyStatic) {
                try {
                    dynamicSystemService.creatCSV(oldFileNamefile, fileds);
                    onlyStatic = false;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                // 数据集使用系统数据
                try {
                    dynamicSystemService.addColumn(oldFileNamefile, fileds, newFileName, userID);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                oldFileName = path + File.separator + newFileName;
            }


        }

        new File(oldFileName).renameTo(new File(path, lastNewFileName + ".csv"));
        Date date = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String info = ft.format(date) + "  本地文件 ：" + onemap1.get("fileName").toString() + "   "
                + "  抽取字段：" + onemap1.get("sql").toString() + "  抽取成功!!";
        return info;
    }


    @Autowired
    DataSetMapper dataSetMapper;

    @Override
    public Boolean stSubmit(Map map) {
        System.out.println(map);
        final String oldname = map.get("oldname").toString();
        final String userId = map.get("userId").toString();
        final String datasetName = map.get("datasetName").toString();

        String path = System.getProperty("user.dir") + File.separator + "csv" + File.separator + userId;
        File oldFileName = new File(path, oldname + ".csv");
        File newFileName = new File(path, datasetName + ".csv");
        if (newFileName != null || newFileName.toString().length() != 0) {
            try {
                oldFileName.renameTo(newFileName);
            } catch (Exception e) {
                System.out.println(e);
            }
        }

        DataSet dataSet = new DataSet();
        dataSet.setDatasetName(datasetName);
        dataSet.setCategoryId(Long.parseLong(map.get("classification").toString()));
        dataSet.setDfsUrl(newFileName.getAbsolutePath());
        dataSet.setDatasetStatus((byte) 1);
        dataSet.setRemark(map.get("remarks").toString());
        dataSet.setCreateTime(new Date());
        dataSet.setUid(Long.parseLong(userId));
        dataSetMapper.insert(dataSet);

        try {
            PutObjectOptions putObjectOptions = new PutObjectOptions(newFileName.length(), PutObjectOptions.MIN_MULTIPART_SIZE);
            MinIoUtils.uploadLocalFile("dataset", newFileName.getName(), newFileName.getAbsolutePath(), putObjectOptions);
            //  删除本地数据文件
            FileUtil.del(newFileName);
        } catch (Exception e) {
            System.out.println(e);
        }
        return true;
    }


}
