package com.tofly.scada.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haiqiu.tools.excel.utils.ExcelUtils;
import com.tofly.common.constant.CalendarHelper;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.scada.common.BaseController;
import com.tofly.scada.common.DateTimeUtil;
import com.tofly.scada.entity.Scada;
import com.tofly.scada.entity.dto.CustomDisplayDto;
import com.tofly.scada.entity.dto.DeviceQuery;
import com.tofly.scada.entity.dto.ScadaMoreQuery;
import com.tofly.scada.entity.dto.ScadaQuery;
import com.tofly.scada.entity.vo.ScadaVo;
import com.tofly.scada.entity.vo.StatisticsScadaVo;
import com.tofly.scada.service.OsmRecordsService;
import com.tofly.scada.service.ScadaService;
import com.tofly.scada.service.StatisticsScadaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;

/**
 * @author HaiQiu
 * @date 2022/4/25
 */
@Api(tags = "SCADA数据操作")
@RequestMapping("/scada")
@RestController
public class ScadaController extends BaseController {

    @Autowired
    private ScadaService scadaService;

    @Autowired
    private StatisticsScadaService statisticsScadaService;


    @Autowired
    private OsmRecordsService osmRecordsService;


    @ApiOperation(value = "查询最新SCADA所有数据")
    @PostMapping("/all")
    public ResultRespone getData() {
        return decide(scadaService.getListData());
    }

    @ApiOperation(value = "根据设备指标查询最新SCADA所有数据")
    @PostMapping("/app/data")
    public ResultRespone getAppData(@RequestBody(required = false) DeviceQuery deviceQuery) {
        return decide(scadaService.getAppData(deviceQuery));
    }


    @ApiOperation(value = "分页查询统计SCADA数据")
    @GetMapping("/page")
    public ResultRespone getMonthsData(Page page, ScadaQuery scadaQuery,
                                       @ApiParam("true 分页，false不分页（默认分页）")
                                       @RequestParam(required = false) Boolean isPage
    ) {

        isPage=isPage==null?true:isPage;
        Page<StatisticsScadaVo> pageList=statisticsScadaService.getPageData(page, scadaQuery,isPage);
        return decide(pageList);

    }

    @ApiOperation(value = "分页查询统计SCADA数据")
    @GetMapping("/export")
    public void export(Page page, ScadaQuery scadaQuery,
                       @RequestParam(required = false) Boolean isHistory) {
        if(isHistory){
            Page<StatisticsScadaVo> pageList=statisticsScadaService.getPageData(page, scadaQuery,false);
            ExcelUtils.getListToExcel(StatisticsScadaVo.class, pageList.getRecords(), "监控历史导出");

        }else{
            Page<ScadaVo> pageList=statisticsScadaService.geTrendData(page, scadaQuery,false,true);
            ExcelUtils.getListToExcel(ScadaVo.class, pageList.getRecords(), "趋势分析导出");

        }

    }


//    @ToFlyAppLog(title = "查询统计SCADA数据列表")
//    @ApiOperation(value = "查询统计SCADA数据列表")
//    @GetMapping("/list")
//    public ResultRespone getDataList(ScadaQuery scadaQuery){
//        return decide(statisticsScadaService.getDataList(scadaQuery));
//    }

    @ApiOperation(value = "趋势分析统计SCADA数据")
    @GetMapping("/trend/page")
    public ResultRespone geTrendData(Page page, ScadaQuery scadaQuery,
                                     @ApiParam("true 分页，false不分页（默认分页）")
                                     @RequestParam(required = false) Boolean isPage) {

        isPage=isPage==null?true:isPage;

        Page<StatisticsScadaVo> pageList=statisticsScadaService.geTrendData(page, scadaQuery,isPage,false);
        return decide(pageList);

    }


   /* @ApiOperation(value = "手动更新范围数据，小时，天，月，年，注意时间格式")
    @PostMapping("/data/fetch")
    public ResultRespone fetchData(@ApiParam("code编码，非必传,多个逗号隔开") @RequestParam(required = false) String code,
                                   @ApiParam("开始时间:2022-01-01 00:00:00") @RequestParam String start,
                                   @ApiParam("结束时间:2022-10-01 14:00:00") @RequestParam String end,
                                   @ApiParam("统计类型0小时，1按天，2月份，3年份") @RequestParam Integer type) {
        try {


            scadaService.fetchData(code, start, end, type);
        }catch (Exception e){
            e.printStackTrace();
            return decide(e.getMessage());

        }

        return decide("更新正在进行中...请稍后再查看结果");
    }*/

    @ApiOperation(value = "手动同步指定日期范围内每天的数据,注意时间格式，只需要年月日")
    @PostMapping("/syncDataRangeComm")
    public ResultRespone syncDataComm(
            @ApiParam("code编码，非必传,多个逗号隔开") @RequestParam(required = false) String codes,
            @ApiParam("开始时间:2023-01-01 00") @RequestParam String startDate,
            @ApiParam("结束时间:2023-10-01 00") @RequestParam String endDate,
            @ApiParam("统计类型,0小时,1按天，2月份，3年份") @RequestParam Integer dateType,
            @ApiParam("按照指标类型来同步") @RequestParam String indexType,
             @ApiParam("是否只同步总流量") @RequestParam String isSynFlow
    ) {
        try {

            scadaService.syncDataRangeComm(codes,startDate,endDate,dateType,indexType,isSynFlow);

        } catch (Exception e) {
            e.printStackTrace();
            return decide(e.getMessage());
        }
        return decide("批量同步成功");
    }

    @ApiOperation(value = "手动同步指定日期范围内每天的售水数据,注意时间格式，只需要年月日")
    @PostMapping("/synSalesWater")
    public ResultRespone synSalesWater(

            @ApiParam("开始时间:2023-01-01") @RequestParam String startDate,
            @ApiParam("结束时间:2023-10-01") @RequestParam String endDate
    ) {
        try {
            scadaService.synSalesWater(startDate,endDate);

        } catch (Exception e) {
            e.printStackTrace();
            return decide(e.getMessage());
        }
        return decide("批量同步成功");
    }

    @ApiOperation(value = "手动同步指定日期范围内每天的用户抄表数据,注意时间格式，只需要年月日")
    @PostMapping("/synOsmRecords")
    public ResultRespone synOsmRecords(
            @ApiParam("开始时间:2023-01-01") @RequestParam String startDate,
            @ApiParam("结束时间:2023-10-01") @RequestParam String endDate
    ) {
        try {
          Date startTime=CalendarHelper.ConvertStrToDate(startDate,"yyyy-MM-dd");
            Date endTime= CalendarHelper.ConvertStrToDate(endDate,"yyyy-MM-dd");
            osmRecordsService.synData(startTime,endTime);

        } catch (Exception e) {
            e.printStackTrace();
            return decide(e.getMessage());
        }
        return decide("批量同步成功");
    }



   /* @ToFlyAppLog(title="test" )
    @ApiOperation(value = "test")
    @PostMapping("/test")
    public ResultRespone test(
            @ApiParam("code编码，非必传,多个逗号隔开") @RequestParam(required = false) String codes,
            @ApiParam("开始时间:2023-01-01") @RequestParam String startDate,
            @ApiParam("结束时间:2023-10-01") @RequestParam String endDate,
            @ApiParam("统计类型1按天，2月份，3年份") @RequestParam Integer dateType
    ) {
        try {

            scadaService.syncDaysData(null,codes); //同步当天的数据

        } catch (Exception e) {
            e.printStackTrace();
            return decide(e.getMessage());
        }
        return decide("批量同步成功");
    }*/


    @ApiOperation(value = "手动更新虚拟表数据")
    @PutMapping("/xn/fetch")
    @Async
    public ResultRespone xnFetchData(String sTime,String eTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            Date startTime = format.parse(sTime);
            Date endTime = format.parse(eTime);
            scadaService.manualSendNetCumulativeFlow(startTime,endTime);
        } catch (Exception e) {
            e.printStackTrace();
            return decide(e.getMessage());
        }


        return decide("更新成功");
    }

    /**
     * 批量新增scada历史数据
     * @param scadaMoreQuery scada历史表
     * @return ResultData
     */
    @ApiOperation(value = "批量新增scada历史数据")
    @PostMapping("/insertBacthHistoryTemp")
    public ResultRespone insertBacthHistoryTemp(@RequestBody ScadaMoreQuery scadaMoreQuery) {
        try {
            statisticsScadaService.insertBacthHistoryTemp(scadaMoreQuery);
        } catch (Exception e) {
            e.printStackTrace();
            return decide(e.getMessage());
        }
        return decide("批量新增成功");
    }





    @GetMapping("/viewScadaData")
    @ApiOperation(value = "查询SCADA指标数据")
    public ResultRespone viewScadaData(CustomDisplayDto dto){
        try {
            return ResultRespone.success(scadaService.viewScadaData(dto));
        }catch (Exception e){
            e.printStackTrace();
            return ResultRespone.failed(e.getMessage());
        }
    }

    @GetMapping("/viewScadaDataNew")
    @ApiOperation(value = "查询SCADA指标数据New")
    public ResultRespone viewScadaDataNew(Page page,CustomDisplayDto dto){
        try {
            return ResultRespone.success(scadaService.viewScadaDataNew(page,dto));
        }catch (Exception e){
            e.printStackTrace();
            return ResultRespone.failed(e.getMessage());
        }
    }
}
