package com.gyee.wisdom.dataadapter.controller.timeseries;

import com.alibaba.fastjson.JSONObject;
import com.gyee.wisdom.common.data.timeseries.*;
import com.gyee.wisdom.dataadapter.domain.timeseries.TsDataService;
import com.gyee.wisdom.dataadapter.domain.timeseries.TsPointService;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 *
 * @author songwb
 */


@RestController
@RequestMapping("/ts")
@CrossOrigin
public class TsDataController {

    @Autowired
    protected TsDataService tsDataService;

    @Autowired
    protected TsPointService tsPointService;



    //thingId：具体设施Id
    //thingType：场站(station)，风机(windturbine)，升压站(electrical)
    //uniformCode：统一编码
    @GetMapping("/latest")
    public Map<String, TsData> getLatest(
            @RequestParam(value = "keys", required = false) Optional<String> keyStr,
            @RequestParam(value = "thingType", required = false) Optional<String> thingType,
            @RequestParam(value = "thingId", required = false) Optional<String> thingId,
            @RequestParam(value = "uniformCodes", required = false) Optional<String> uniformCodes
    ) {
        if (keyStr.isPresent()) {
            String[] tagNames = keyStr.get().split(",");
            Map<String, TsData> data = tsDataService.getLatest(tagNames);
            if (data == null) {
                Map<String, TsData> nullData = new HashMap<>();
                return nullData;
            } else {
                return data;
            }
        } else if (thingType.isPresent() && thingId.isPresent() && uniformCodes.isPresent()) {
            String[] uCodes = uniformCodes.get().split(",");
            return tsDataService.getLatestByUniformCodes(thingType.get(), thingId.get(), uCodes);
        } else {
            Map<String, TsData> nullData = new HashMap<>();
            return nullData;
        }
    }

    @GetMapping("/history/raw")
    public List<TsData> getHistoryRaw(@RequestParam(value = "tagName", required = false) Optional<String> tagName,
                                      @RequestParam(value = "thingType", required = false) Optional<String> thingType,
                                      @RequestParam(value = "thingId", required = false) Optional<String> thingId,
                                      @RequestParam(value = "uniformCode", required = false) Optional<String> uniformCode,
                                      @RequestParam(value = "startTs", required = false) Optional<Long> startTs,
                                      @RequestParam(value = "endTs", required = false) Optional<Long> endTs) {
        if (tagName.isPresent() && startTs.isPresent() && endTs.isPresent()) {
            List<TsData> list = tsDataService.getHistoryRaw(tagName.get(), startTs.get(), endTs.get());
            if (list == null)
                list = new ArrayList<>();
            return list;
        }

        if (thingType.isPresent() && thingId.isPresent() && uniformCode.isPresent() && startTs.isPresent() && endTs.isPresent()) {
            List<TsData> list = tsDataService.getHistoryRaw(thingType.get(), thingId.get(), uniformCode.get(), startTs.get(), endTs.get());
            if (list == null)
                list = new ArrayList<>();
            return list;
        } else {
            List<TsData> list = new ArrayList<>();
            return list;
        }

    }

    @GetMapping("/history/snap")
    public List<TsData> getHistorySnap(@RequestParam(value = "tagName", required = false) Optional<String> tagName,
                                       @RequestParam(value = "thingId", required = false) Optional<String> thingId,
                                       @RequestParam(value = "thingType", required = false) Optional<String> thingType,
                                       @RequestParam(value = "uniformCode", required = false) Optional<String> uniformCode,
                                       @RequestParam(value = "startTs", required = false) Optional<Long> startTs,
                                       @RequestParam(value = "endTs", required = false) Optional<Long> endTs,
                                       @RequestParam(value = "interval", required = false) Optional<Integer> interval) {
        if (tagName.isPresent() && startTs.isPresent() && endTs.isPresent()) {
            int intVal = interval.isPresent()?interval.get():60;
            List<TsData> resultMap = tsDataService.getHistorySnap(tagName.get(), startTs.get(), endTs.get(), intVal);
            if (resultMap == null)
                resultMap = new ArrayList<>();
            return resultMap;
        } else if (thingId.isPresent() && thingType.isPresent() && uniformCode.isPresent() && startTs.isPresent() && endTs.isPresent()) {
            int intVal = interval.isPresent()?interval.get():60;
            List<TsData> resultMap = tsDataService.getHistorySnap(thingType.get(), thingId.get(), uniformCode.get(), startTs.get(), endTs.get(), intVal);
            if (resultMap == null)
                resultMap = new ArrayList<>();
            return resultMap;
        } else {
            List<TsData> resultMap = new ArrayList<>();
            return resultMap;
        }
    }

    @GetMapping("/history/stat")
    public List<DoubleStatData> getHistoryStat(@RequestParam(value = "tagName", required = false) Optional<String> tagName,
                                               @RequestParam(value = "thingType", required = false) Optional<String> thingType,
                                               @RequestParam(value = "thingId", required = false) Optional<String> thingId,
                                               @RequestParam(value = "uniformCode", required = false) Optional<String> uniformCode,
                                               @RequestParam(value = "startTs", required = false) Optional<Long> startTs,
                                               @RequestParam(value = "endTs", required = false) Optional<Long> endTs,
                                               @RequestParam(value = "interval", required = false) Optional<Integer> interval) {
        if (tagName.isPresent() && startTs.isPresent() && endTs.isPresent()) {
            int intVal = interval.isPresent()?interval.get():60;
            List<DoubleStatData> list = tsDataService.getHistoryStat(tagName.get(), startTs.get(), endTs.get(), intVal);
            if (list == null)
                list = new ArrayList<>();
            return list;
        } else if (thingType.isPresent() && thingId.isPresent() && uniformCode.isPresent() && startTs.isPresent() && endTs.isPresent()) {
            int intVal = interval.isPresent()?interval.get():60;
            List<DoubleStatData> list = tsDataService.getHistoryStat(thingType.get(), thingId.get(), uniformCode.get(), startTs.get(), endTs.get(), intVal);
            if (list == null)
                list = new ArrayList<>();
            return list;
        } else {
            List<DoubleStatData> list = new ArrayList<>();
            return list;
        }
    }

    @GetMapping("/history/section")
    public Map<String, TsData> getHistorySection(@RequestParam(value = "tagNames", required = false) Optional<String> tagNames,
                                                 @RequestParam(value = "thingType", required = false) Optional<String> thingType,
                                                 @RequestParam(value = "thingId", required = false) Optional<String> thingId,
                                                 @RequestParam(value = "uniformCodes", required = false) Optional<String> uniformCodes,
                                                 @RequestParam(value = "ts", required = false) Optional<Long> ts) throws Exception {
        try {
            if (tagNames.isPresent() && ts.isPresent()) {
                String[] tagNameArr = tagNames.get().split(",");
                Map<String, TsData> map = tsDataService.getHistorySection(ts.get(), tagNameArr);
                if (map == null)
                    map = new HashMap<>();
                return map;
            } else if (thingType.isPresent() && thingId.isPresent() && uniformCodes.isPresent() && ts.isPresent()) {
                String[] unifromCodeArray = uniformCodes.get().split(",");
                Map<String, TsData> map = tsDataService.getHistorySection(ts.get(), thingId.get(), thingType.get(), unifromCodeArray);
                if (map == null)
                    map = new HashMap<>();
                return map;
            } else {
                Map<String, TsData> map = new HashMap<>();
                return map;
            }

        } catch (Exception e) {
            Map<String, TsData> map = new HashMap<>();
            return map;
        }

    }

    @PostMapping("/history/batch")
    //@ResponseBody
    public boolean writeHistoryBatch(@RequestBody List<TsPointData> tsDataList) {
        try {
            tsDataService.writeHistory(tsDataList);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @PostMapping("/history")
   //@ResponseBody
    public boolean writeHistory(@RequestBody TsPointData tsData) {
        try {
            List<TsPointData> list = new ArrayList<>();
            list.add(tsData);
            tsDataService.writeHistory(list);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @PostMapping("/history/list")
    //@ResponseBody
    public boolean writeHistoryList(@RequestBody TsPointDataList tsData) {
        try {
            List<TsPointData> tsDataList = new ArrayList<>();
            if (tsData != null) {
                for (int i = 0; i < tsData.getTsDataList().size(); i++) {
                    TsPointData data = new TsPointData();
                    data.setTagName(tsData.getTagName());
                    data.setTsData(tsData.getTsDataList().get(i));
                    tsDataList.add(data);
                }
                tsDataService.writeHistory(tsDataList);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

    }

    @PostMapping("/latest/batch")
    //@ResponseBody
    public boolean writeLatestBatch(@RequestBody List<TsPointData> tsDataList) throws Exception {
        return tsDataService.writeLatest(tsDataList);
    }

    @PostMapping("/latest")
    //@ResponseBody
    public boolean writeLatest(@RequestBody TsPointData tsData) throws Exception {
        List<TsPointData> tsDataList = new ArrayList<>();
        tsDataList.add(tsData);
        return tsDataService.writeLatest(tsDataList);
    }

}


