package com.yeejoin.amos.boot.module.jxiop.biz.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.biz.core.framework.GatewayIdAutowired;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.FanHealthIndexDto;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.FullViewRecallDataDTO;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.FullViewRecallInfoDTO;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.PvHealthIndexDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanHealthLevel;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvHealthLevel;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizFanHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizFanHealthLevelMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizPvHealthLevelMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanWaringRecordMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.PvHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.PvWaringRecordMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanHealthIndex;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanWarningRecord;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.PvHealthIndex;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.PvWarningRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.yeejoin.amos.boot.biz.common.utils.DateUtils.DATE_TIME_PATTERN;

@RestController
@Api(tags = "智能分析相关API - TD数据源")
@RequestMapping(value = "/tdInfoQueryApi")
public class TdInfoQueryController {

    @Autowired
    private FanHealthIndexMapper fanHealthIndexMapper;

    @Autowired
    private PvHealthIndexMapper pvHealthIndexMapper;

    @Autowired
    private FanWaringRecordMapper fanWaringRecordMapper;

    @Autowired
    private PvWaringRecordMapper pvWaringRecordMapper;

    @Autowired
    IdxBizFanHealthLevelMapper idxBizFanHealthLevelMapper;

    @Autowired
    IdxBizPvHealthLevelMapper idxBizPvHealthLevelMapper;

    @Autowired
    IdxBizFanHealthIndexMapper idxBizFanHealthIndexMapper;
    public final DecimalFormat df = new DecimalFormat("#.0");


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/getFanHealthIndexInfo")
    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 风电", notes = "分页查询健康指数信息 - 风电")
    @GatewayIdAutowired
    public ResponseModel<Page<FanHealthIndex>> getFanHealthIndexInfo(@RequestBody FanHealthIndexDto dto) throws ParseException {
        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
            String startDate = dto.getStartDate();
            Date date = DateUtils.dateParse(startDate, DATE_TIME_PATTERN);
            String startDateString = DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN);
            dto.setStartDate(startDateString);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
            String endDate = dto.getEndDate();
            Date endDateDate = DateUtils.dateParse(endDate, DATE_TIME_PATTERN);
            String endDateString = DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN);
            dto.setEndDate(endDateString);
        }
        Page<FanHealthIndex> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
                dto.setSorts(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
        List<String> orderByList = new ArrayList<>();
        for (Map<String, String> map : orderWeight) {
            String replace = map.get("order").replace("end", "");
            String columnOrder = convert(map.get("columnKey")) + " " + replace;
            orderByList.add(columnOrder);
        }
        String join = String.join(",", orderByList);
        dto.setOrderColumns(join);
        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
            String[] split = dto.getSortOne().split(",");
            String replace = split[1].replace("end", "");
            String orderColumn = convert(split[0]) + " " + replace;
            dto.setSortOne(orderColumn);
        }

        List<FanHealthIndex> fanHealthIndexIPage = fanHealthIndexMapper.getInfoByPage(dto);
        fanHealthIndexIPage.forEach(item -> item.setHealthIndex(Double.valueOf(df.format(item.getHealthIndex()))));
        Integer infoByPageTotal = fanHealthIndexMapper.getInfoByPageTotal(dto);
        resultPage.setRecords(fanHealthIndexIPage);
        resultPage.setTotal(infoByPageTotal);
        return ResponseHelper.buildResponse(resultPage);
    }

    public static String convert(String camelCase) {
        StringBuilder result = new StringBuilder();
        if (camelCase.equals("analysisTime")) {
            return "ts";
        }
        for (int i = 0; i < camelCase.length(); i++) {
            char currentChar = camelCase.charAt(i);
            if (Character.isUpperCase(currentChar)) {
                result.append("_").append(Character.toLowerCase(currentChar));
            } else {
                result.append(currentChar);
            }
        }
        return result.toString();
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/getPvHealthIndexInfo")
    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 光伏", notes = "分页查询健康指数信息 - 光伏")
    @GatewayIdAutowired
    public ResponseModel<Page<PvHealthIndex>> getPvHealthIndexInfo(@RequestBody PvHealthIndexDto dto) throws ParseException {
        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
            String startDate = dto.getStartDate();
            Date date = DateUtils.dateParse(startDate, DATE_TIME_PATTERN);
            String startDateString = DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN);
            dto.setStartDate(startDateString);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
            String endDate = dto.getEndDate();
            Date endDateDate = DateUtils.dateParse(endDate, DATE_TIME_PATTERN);
            String endDateString = DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN);
            dto.setEndDate(endDateString);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
                dto.setSorts(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Page<PvHealthIndex> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
        List<String> orderByList = new ArrayList<>();
        for (Map<String, String> map : orderWeight) {
            String replace = map.get("order").replace("end", "");
            String columnOrder = convert(map.get("columnKey")) + " " + replace;
            orderByList.add(columnOrder);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
            String[] split = dto.getSortOne().split(",");
            String replace = split[1].replace("end", "");
            String orderColumn = convert(split[0]) + " " + replace;
            dto.setSortOne(orderColumn);
        }
        String join = String.join(",", orderByList);
        dto.setOrderColumns(join);
        List<PvHealthIndex> pvHealthIndexIPage = pvHealthIndexMapper.getInfoByPage(dto);
        pvHealthIndexIPage.forEach(item -> item.setHealthIndex(Double.valueOf(df.format(item.getHealthIndex()))));
        Integer infoByPageTotal = pvHealthIndexMapper.getInfoByPageTotal(dto);
        resultPage.setRecords(pvHealthIndexIPage);
        resultPage.setTotal(infoByPageTotal);
        return ResponseHelper.buildResponse(resultPage);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/getFanWarningRecordInfo")
    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 风电", notes = "分页查询健康指数信息 - 风电")
    @GatewayIdAutowired
    public ResponseModel<Page<FanWarningRecord>> getFanWarningRecordInfo(@RequestBody FanHealthIndexDto dto) throws ParseException {
        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
            String startDate = dto.getStartDate();
            Date date = DateUtils.dateParse(startDate, DATE_TIME_PATTERN);
            String startDateString = DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN);
            dto.setStartDate(startDateString);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
            String endDate = dto.getEndDate();
            Date endDateDate = DateUtils.dateParse(endDate, DATE_TIME_PATTERN);
            String endDateString = DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN);
            dto.setEndDate(endDateString);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
                dto.setSorts(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Page<FanWarningRecord> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
        List<String> orderByList = new ArrayList<>();
        for (Map<String, String> map : orderWeight) {
            String replace = map.get("order").replace("end", "");
            String columnOrder = convert(map.get("columnKey")) + " " + replace;
            orderByList.add(columnOrder);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
            String[] split = dto.getSortOne().split(",");
            String replace = split[1].replace("end", "");
            String orderColumn = convert(split[0]) + " " + replace;
            dto.setSortOne(orderColumn);
        }
        String join = String.join(",", orderByList);
        dto.setOrderColumns(join);
        List<FanWarningRecord> fanWarningRecordsIPage = fanWaringRecordMapper.getInfoByPage(dto);
        Integer infoByPageTotal = fanWaringRecordMapper.getInfoByPageTotal(dto);
        resultPage.setRecords(fanWarningRecordsIPage);
        resultPage.setTotal(infoByPageTotal);
        return ResponseHelper.buildResponse(resultPage);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/getPvWarningRecordInfo")
    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 光伏", notes = "分页查询健康指数信息 - 光伏")
    @GatewayIdAutowired
    public ResponseModel<Page<PvWarningRecord>> getPvWarningRecordInfo(@RequestBody FanHealthIndexDto dto) throws ParseException {
        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
            String startDate = dto.getStartDate();
            Date date = DateUtils.dateParse(startDate, DATE_TIME_PATTERN);
            String startDateString = DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN);
            dto.setStartDate(startDateString);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
            String endDate = dto.getEndDate();
            Date endDateDate = DateUtils.dateParse(endDate, DATE_TIME_PATTERN);
            String endDateString = DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN);
            dto.setEndDate(endDateString);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
                dto.setSorts(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Page<PvWarningRecord> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
        List<String> orderByList = new ArrayList<>();
        for (Map<String, String> map : orderWeight) {
            String replace = map.get("order").replace("end", "");
            String columnOrder = convert(map.get("columnKey")) + " " + replace;
            orderByList.add(columnOrder);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
            String[] split = dto.getSortOne().split(",");
            String replace = split[1].replace("end", "");
            String orderColumn = convert(split[0]) + " " + replace;
            dto.setSortOne(orderColumn);
        }
        String join = String.join(",", orderByList);
        dto.setOrderColumns(join);
        List<PvWarningRecord> pvWarningRecords = pvWaringRecordMapper.getInfoByPage(dto);
        Integer infoByPageTotal = pvWaringRecordMapper.getInfoByPageTotal(dto);
        resultPage.setRecords(pvWarningRecords);
        resultPage.setTotal(infoByPageTotal);
        return ResponseHelper.buildResponse(resultPage);
    }

}
