package com.ho.business.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.ho.business.entity.DeviceTypeCol;
import com.ho.business.entity.DeviceTypeConfig;
import com.ho.business.entity.Station;
import com.ho.business.service.AutoDeviceCurveService;
import com.ho.business.service.DeviceTypeColService;
import com.ho.business.service.DeviceTypeConfigService;
import com.ho.business.service.StationService;
import com.ho.business.vo.AutoDeviceCurveVo;
import com.ho.business.vo.SingleValueColVo;
import com.ho.business.vo.req.device.DeviceTypeQuery;
import com.ho.business.vo.resp.point.PointCurveHomeResp;
import com.ho.common.tools.annotation.TokenIgnore;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.vo.req.StationHomeRespVo;
import com.ho.td.api.entity.query.TdBaseTimeQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author catkins
 * @date 2023年10月23日 15:40
 */
@RestController
@RequestMapping(ContextConstant.BUSINESS + "autoDeviceCurve")
@Api(tags = "多媒体-自动化设备测试-曲线通用查询")
@Slf4j
public class AutoDeviceCurveController {

    @Autowired
    private AutoDeviceCurveService autoDeviceCurveService;

    @Autowired
    private DeviceTypeConfigService deviceTypeConfigService;

    @Autowired
    private StationService stationService;

    @Autowired
    DeviceTypeColService deviceTypeColService;

    @GetMapping("/time")
    @TokenIgnore
    public String checkTime() {
        return "时区：" + TimeZone.getDefault().getID() +
                " | 时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").format(new Date());
    }

    @PostMapping("queryCurve")
    @ApiOperation(value = "查询两个曲线的差值/查询单条曲线")
    @TokenIgnore
    public DataResult<List<StationHomeRespVo>> queryCurve(@RequestBody AutoDeviceCurveVo vo) {
        if (vo == null) {
            throw new BusinessException(BaseResponseCode.NON_DATA);
        }
        Integer stationId = vo.getStationId();
        String deviceType = vo.getDeviceType();

        // 根据电站id查询电站详细信息
        Station station = stationService.selectById(stationId);
        DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceType, station.getGroupId());

        /** todo: 组装第一个col的td查询参数 */
        /** start */
        TdBaseTimeQuery col_1_td_query = null;
        String col1 = vo.getCol1();
        if (StringUtil.isNotEmpty(col1)) {
            vo.setCol(vo.getCol1());
            col_1_td_query = processParams(vo, station, deviceTypeConfig);
        } else {
            throw new BusinessException(BaseResponseCode.NON_DATA);
        }

        // 如果第一个结果集就为空则不往下继续,直接返回空结果
        if( col_1_td_query == null ){
            return DataResult.success();
        }

        List<StationHomeRespVo> vos_1 = autoDeviceCurveService.queryData(col_1_td_query);
        /** end */

        /** todo: 组装第二个col的td查询参数 */
        /** start */
        TdBaseTimeQuery col_2_td_query = null;
        String col2 = vo.getCol2();
        if (StringUtil.isNotEmpty(col2)) {
            vo.setCol(vo.getCol2());
            col_2_td_query = processParams(vo, station, deviceTypeConfig);
        }
        List<StationHomeRespVo> vos_2 = null;
        if ( col_2_td_query != null ) {
            vos_2 = autoDeviceCurveService.queryData(col_2_td_query);
        }
        /** end */
        String startTime = vo.getStartTime();
        String endTime = vo.getEndTime();
        List<String> min = getMin(DateUtil.parse(startTime), DateUtil.parse(endTime), vo.getInterval());

        List<StationHomeRespVo> curve = autoDeviceCurveService.getCurve(vos_1, vos_2,min);
        //根据登录人设置集团id和用户id
        return DataResult.success(curve);
    }

    @PostMapping("getOneValue")
    @ApiOperation(value = "查询单个值")
    @TokenIgnore
    public DataResult<BigDecimal> getOneValue(@RequestBody AutoDeviceCurveVo vo) {

        Integer stationId = vo.getStationId();
        String deviceType = vo.getDeviceType();

        // 根据电站id查询电站详细信息
        Station station = stationService.selectById(stationId);
        DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceType, station.getGroupId());

        /** todo: 组装td查询参数 */
        /** start */
        TdBaseTimeQuery col_1_td_query = null;
        String col1 = vo.getCol1();
        if (StringUtil.isNotEmpty(col1)) {
            vo.setCol(vo.getCol1());
            col_1_td_query = processParams(vo, station, deviceTypeConfig);
        } else {
            throw new BusinessException(BaseResponseCode.NON_DATA);
        }

        if( col_1_td_query == null ){
            return DataResult.success();
        }

        List<StationHomeRespVo> vos_1 = autoDeviceCurveService.queryData(col_1_td_query);
        /** end */
        BigDecimal oneValue = autoDeviceCurveService.getOneValue(vos_1);

        return DataResult.success(oneValue);
    }


    /**
     * 处理td数据库查询参数方法
     * @param vo
     * @param station
     * @param deviceTypeConfig
     * @return
     */
    private TdBaseTimeQuery processParams(AutoDeviceCurveVo vo, Station station, DeviceTypeConfig deviceTypeConfig) {
        if (vo == null) {
            return null;
        }
        TdBaseTimeQuery tdBaseQuery = new TdBaseTimeQuery();
        tdBaseQuery = new TdBaseTimeQuery();
        tdBaseQuery.setBeginTime(vo.getStartTime());
        tdBaseQuery.setEndTime(vo.getEndTime());
        tdBaseQuery.setTime("1m");
        tdBaseQuery.setStationId(station.getId());
        tdBaseQuery.setGroupId(station.getGroupId());
        tdBaseQuery.setTableName(deviceTypeConfig.getModelName());
        DeviceTypeQuery deviceTypeQuery = new DeviceTypeQuery();
        deviceTypeQuery.setGroupId(station.getGroupId());
        deviceTypeQuery.setDeviceType(vo.getDeviceType());
        List<DeviceTypeConfig> deviceTypeConfigs = deviceTypeConfigService.queryListByCondition(deviceTypeQuery);
        if (deviceTypeConfigs == null || deviceTypeConfigs.size() == 0) {
            return null;
        }
        tdBaseQuery.setModelName(deviceTypeConfigs.get(0).getModelName());
        String deviceCol = vo.getCol();
        tdBaseQuery.setCol(deviceCol);
        Integer srcId = autoDeviceCurveService.getSrcIdByStationId(station.getId(), vo.getDeviceType());
        tdBaseQuery.setSrcId(srcId);
        return tdBaseQuery;
    }

    /**
     * 按照指定分钟间隔获取两个时间段内所有时间字符串集合
     * @param startDate
     * @param endDate
     * @param delay 间隔的分钟数
     * @return
     */
    private List<String> getMin(Date startDate, Date endDate, int delay) {
        List<String> allMin = new ArrayList<>();
        Calendar t1 = Calendar.getInstance();
        t1.setTime(startDate);//开始时间
        Calendar t2 = Calendar.getInstance();
        t2.setTime(endDate);//结束时间
        for (; t1.compareTo(t2) < 0; t1.add(Calendar.MINUTE, delay)) {
            allMin.add(DateUtil.format(t1.getTime(), "yyyy-MM-dd HH:mm"));
        }
        return allMin;
    }


    @PostMapping("queryCurveNew")
    @ApiOperation(value = "查询两个曲线的差值/查询单条曲线,返回的对象是一个包含点位定义的符合对象")
    @TokenIgnore
    public DataResult<List<PointCurveHomeResp>> queryCurveNew(@RequestBody List<AutoDeviceCurveVo> voList) {
        //创建返回对象
        List<PointCurveHomeResp> list = new ArrayList<>();
        if(voList!=null && !voList.isEmpty()){
            for (AutoDeviceCurveVo vo : voList) {
                PointCurveHomeResp homeVo = getHomeVo(vo);
                if(homeVo!=null){
                    list.add(homeVo);
                }
            }
        }
        return DataResult.success(list);
    }

    //获取曲线返回对象
    private PointCurveHomeResp getHomeVo(AutoDeviceCurveVo vo){
        if (vo == null) {
            return null;
        }
        //创建返回对象
        PointCurveHomeResp pointCurveHomeResp = new PointCurveHomeResp();
        Integer stationId = vo.getStationId();
        String deviceType = vo.getDeviceType();

        // 根据电站id查询电站详细信息
        Station station = stationService.selectById(stationId);
        DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceType, station.getGroupId());
        //有设备类型才做后面的事
        if(deviceTypeConfig == null){
            log.error("查询设备类型配置为空, deviceType:{} , groupId: {}" ,deviceType,station.getGroupId() );
            return null;
        }
        //查点定义
        DeviceTypeCol deviceTypeCol = deviceTypeColService.selectTypeAndCol(vo.getCol1(), vo.getDeviceType(),null);
        pointCurveHomeResp.setDeviceName(deviceTypeConfig.getName());
        if(deviceTypeCol!=null){
            pointCurveHomeResp.setCol(vo.getCol1());
            pointCurveHomeResp.setColName(deviceTypeCol.getColName());
        }
        /** todo: 组装第一个col的td查询参数 */
        /** start */
        TdBaseTimeQuery col_1_td_query = null;
        String col1 = vo.getCol1();
        if (StringUtil.isNotEmpty(col1)) {
            vo.setCol(vo.getCol1());
            col_1_td_query = processParams(vo, station, deviceTypeConfig);
        } else {
            throw new BusinessException(BaseResponseCode.NON_DATA);
        }

        // 如果第一个结果集就为空则不往下继续,直接返回空结果
        if( col_1_td_query == null ){
            log.error("col_1_td_query is null");
            return null;
        }
        List<StationHomeRespVo> curve = autoDeviceCurveService.queryData(col_1_td_query);
        pointCurveHomeResp.setStaticCurveList(curve);
        return pointCurveHomeResp;
    }


    @PostMapping("getOneValueNew")
    @ApiOperation(value = "查询单个值 返回复合对象")
    @TokenIgnore
    public DataResult<SingleValueColVo> getOneValueNew(@RequestBody AutoDeviceCurveVo vo) {

        Integer stationId = vo.getStationId();
        String deviceType = vo.getDeviceType();
        // 根据电站id查询电站详细信息
        Station station = stationService.selectById(stationId);
        DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceType, station.getGroupId());

        /** todo: 组装td查询参数 */
        /** start */
        TdBaseTimeQuery col_1_td_query = null;
        String col1 = vo.getCol1();
        if (StringUtil.isNotEmpty(col1)) {
            vo.setCol(vo.getCol1());
            col_1_td_query = processParams(vo, station, deviceTypeConfig);
        } else {
            throw new BusinessException(BaseResponseCode.NON_DATA);
        }
        if( col_1_td_query == null ){
            return DataResult.success();
        }
        List<StationHomeRespVo> vos_1 = autoDeviceCurveService.queryData(col_1_td_query);
        /** end */
        BigDecimal oneValue = autoDeviceCurveService.getOneValue(vos_1);
        //查点对应的点表信息
        //因为配置的点是不带站结尾,所以需要拼接 deviceType
        DeviceTypeCol deviceTypeCol = deviceTypeColService.selectTypeAndCol(col1, deviceType,null);
        SingleValueColVo singleValueColVo = new SingleValueColVo();
        if(deviceTypeCol!=null){
            BeanUtil.copyProperties(deviceTypeCol,singleValueColVo);
        }
        singleValueColVo.setValue(oneValue);
        return DataResult.success(singleValueColVo);
    }

}
