package com.ho.business.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.PageInfo;
import com.ho.business.common.MinioNewUtil;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.*;
import com.ho.business.feignclient.FlowFeignClient;
import com.ho.business.feignclient.TdFeignClient;
import com.ho.business.feignclient.UserFeignClient;
import com.ho.business.mapper.IndustrialElecRegionMapper;
import com.ho.business.mapper.InspectionFaultMapper;
import com.ho.business.service.*;
import com.ho.business.vo.req.*;
import com.ho.business.vo.req.data.ApiPointReq;
import com.ho.business.vo.req.data.PushDataReq;
import com.ho.business.vo.req.data.StationDataReq;
import com.ho.business.vo.req.device.CommonQuery;
import com.ho.business.vo.req.device.DeviceListReq;
import com.ho.business.vo.req.device.DeviceTypeQuery;
import com.ho.business.vo.req.deviceTypeCol.DeviceTypeColQueryVo;
import com.ho.business.vo.req.industrialElec.IndustrialElecPriceReqVo;
import com.ho.business.vo.req.inspectionFault.InspectionFaultVo;
import com.ho.business.vo.req.point.PointCurveReq;
import com.ho.business.vo.req.point.PointReq;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.business.vo.resp.ProvinceStation;
import com.ho.business.vo.resp.data.ApiMappingRelation;
import com.ho.business.vo.resp.data.ApiPointRespVO;
import com.ho.business.vo.resp.pcsStation.OutStaion;
import com.ho.business.vo.resp.pcsStation.OutStationData;
import com.ho.business.vo.resp.pcsStation.OutStationList;
import com.ho.business.vo.resp.pcsStation.PcsStationData;
import com.ho.business.vo.resp.point.PointCurveResp;
import com.ho.business.vo.resp.point.PointRespVO;
import com.ho.common.tools.annotation.TokenIgnore;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.entity.file.OrderFile;
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.service.RedisService;
import com.ho.common.tools.util.PageResult;
import com.ho.common.tools.util.PageUtils;
import com.ho.common.tools.vo.req.StatisticsCurve;
import com.ho.datacollect.api.constant.DataCollectConstant;
import com.ho.datacollect.api.vo.req.add.TdBase;
import com.ho.flow.vo.req.AlarmConfig.AlarmConfigQueryVo;
import com.ho.td.api.entity.elecMeter.ElecPowerGeneration;
import com.ho.user.api.vo.req.QueryDeptReqVO;
import com.ho.user.api.vo.req.SysSubDictVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fancl
 * @desc: 提供给外部调用，不校验token
 * @date 2022/10/14
 */
@RestController
@RequestMapping(ContextConstant.BUSINESS + "outerApi")
@Slf4j
@Api(tags = "提供给外部调用接口")
public class OuterApiController {

    @Autowired
    private StationService stationService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    StationSnService stationSnService;

    @Autowired
    DeviceTypeService deviceTypeService;

    @Autowired
    DeviceTypeConfigService deviceTypeConfigService;

    @Autowired
    TdFeignClient tdFeignClient;

    @Autowired
    FreezeService freezeService;

    @Autowired
    ElecPriceService elecPriceService;

    @Autowired
    ElecMeterValueService elecMeterValueService;

    @Autowired
    ModelDeviceService modelDeviceService;

    @Autowired
    ModelDeviceColService modelDeviceColService;

    @Autowired
    ModelTypeColService modelTypeColService;

    @Autowired
    PictureService pictureService;

    @Autowired
    OutApiService outApiService;

    @Autowired
    DeviceTypeColService deviceTypeColService;

    @Autowired
    RedisService redisService;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    PointDemoService pointDemoService;

    @Autowired
    private FlowFeignClient flowFeignClient;

    @Autowired
    StationHomeService stationHomeService;

    @Autowired
    CommonService commonService;

    @Autowired
    private IndustrialElecPriceService industrialElecPriceService;

    @Autowired
    private IndustrialElecRegionMapper industrialElecRegionMapper;

    @Value("${spring.profiles.active}")
    private String env;

    @Value("${openRedis.host}")
    String host;

    @Value("${openRedis.port}")
    String port;

    @Value("${openRedis.pass}")
    String pass;

    @Value("${openTestRedis.host}")
    String testHost;

    @Value("${openTestRedis.port}")
    String testPort;

    @Value("${openTestRedis.pass}")
    String testPass;

    @Autowired
    MinioNewUtil minioUtil;

    @Autowired
    InspectionFaultMapper inspectionFaultMapper;
    //上传文件
    @PostMapping("uploadFile")
    @TokenIgnore
    public DataResult<OrderFile> uploadFile(@RequestBody MultipartFile file, @RequestParam("bucket") String bucket) {
        //判断该集团的bucket是否存在,不存在就创建
        /*boolean flag = minioUtil.bucketExists(bucket);
        if (!flag) {
            minioUtil.createBucketName(bucket);
        }*/
        String filename = file.getOriginalFilename();
        long date = System.currentTimeMillis();
        String fileName = date + filename;
        String url = minioUtil.minioUpload(file, fileName, bucket);
        log.info("上传文件url:" + url);
        OrderFile orderFile = new OrderFile();
        if (!com.alibaba.druid.util.StringUtils.isEmpty(url)) {
            orderFile.setFileName(filename);
            orderFile.setUrl(url);
        }
        return DataResult.success(orderFile);
    }

    //删除文件
    @PostMapping("deleteFile")
    @TokenIgnore
    public DataResult deleteFile(@RequestParam String bucket, @RequestBody OrderFile orderFile) {
        String msg = "";
        try {
            // minioUtil.deleteFile(bucket, orderFile.getFileName());
        } catch (Exception e) {
            msg = e.getMessage();
        }
        if (!com.alibaba.druid.util.StringUtils.isEmpty(msg)) {
            throw new BusinessException(BaseResponseCode.DELETE_ERROR);
        }
        return DataResult.success();
    }

    //根据电站id查电站
    @PostMapping("selectByStationIds")
    @TokenIgnore
    public DataResult<List<Station>> selectByStationIds(@RequestBody List<Integer> ids, HttpServletRequest request) {
        String lang = request.getHeader(CommonConstant.LANG);
        List<Station> stations = stationService.selectStationsByIds(ids,lang);
        return DataResult.success(stations);
    }

    /**
     * 根据条件查询站点信息
     * @param vo
     * @return
     */
    @PostMapping("selectStationByCondition")
    @TokenIgnore
    public DataResult<List<Station>> selectByStationIds(@RequestBody StationPageReqVO vo) {
        List<Station> stations = stationService.selectStationByCondition(vo);
        return DataResult.success(stations);
    }

    //根据电站id查电站
    @PostMapping("selectResultSn")
    @TokenIgnore
    public DataResult<List<Station>> selectResultSn(@RequestBody List<Integer> ids) {
        List<StationSn> stations = stationSnService.selectByStationIds(ids);
        return DataResult.success(stations);
    }

    //根据电站name模糊查电站
    @PostMapping("selectByName")
    @TokenIgnore
    public DataResult<List<Station>> selectByName(@RequestBody String name) {
        List<Station> stations = stationService.getByName(name);
        return DataResult.success(stations);
    }

    //查询全部电站sn(接入点)
    @PostMapping("selectStationSNAll")
    @TokenIgnore
    public DataResult<List<Station>> selectStationSNAll() {
        //查出所有带你站
        List<Station> stations = stationService.selectAll();
        List<Integer> stationIds = stations.stream().map(Station::getId).collect(Collectors.toList());
        //查出电站所对应的sn
        List<StationSn> list = stationSnService.selectByStationIds(stationIds);
        Map<Integer, List<StationSn>> snMap = list.stream().collect(Collectors.groupingBy(StationSn::getStationId));
        //把对应的电站sn组装带对应的电站中
        for (Station station : stations) {
            List<StationSn> stationSnList = snMap.get(station.getId());
            if (stationSnList != null) {
                List<String> snList = stationSnList.stream().map(StationSn::getSn).collect(Collectors.toList());
                station.setSnList(snList);
            }
        }
        return DataResult.success(stations);
    }

    //根据电站id查电站
    @PostMapping("selectByStationId")
    @TokenIgnore
    public DataResult<Station> selectByStationId(@RequestBody Integer id) {
        Station station = stationService.selectById(id);
        return DataResult.success(station);
    }

    //根据设备id查设备
    @PostMapping("selectByDeviceId")
    @TokenIgnore
    public DataResult<Device> selectByDeviceId(@RequestBody Integer id) {
        Device device = deviceService.selectById(id);
        return DataResult.success(device);
    }

    //根据电站id查询
    @PostMapping("selectByDeviceIds")
    @TokenIgnore
    public DataResult<List<DeviceRespVO>> selectByDeviceIds(@RequestBody List<Integer> deviceIds) {
        List<DeviceRespVO> list = deviceService.selectByIds(deviceIds);
        return DataResult.success(list);
    }

    //根据电站id查电站
    @PostMapping("selectByStationIdAndSrcId")
    @TokenIgnore
    public DataResult<List<DeviceRespVO>> selectByStationIdAndSrcId(@RequestBody Map<Integer, List<Integer>> map) {
        List<DeviceRespVO> list = deviceService.selectByStationIdAndSrcIds(map);
        return DataResult.success(list);
    }

    //包含虚拟设备
    @PostMapping("selectDeviceByStationIdsAndSrcIdVirtual")
    @TokenIgnore
    public DataResult<List<Device>> selectDeviceByStationIdsAndSrcIdVirtual(@RequestBody DeviceListReq deviceListReq) {
        List<Device> list = deviceService.selectByStationIdAndSrcIdsVirtual(deviceListReq);
        return DataResult.success(list);
    }

    /**
     * 根据设备类型获取设备
     *
     * @param deviceType
     * @return
     */
    @PostMapping("selectDeviceByDeviceType")
    @TokenIgnore
    public DataResult<List<DeviceRespVO>> selectDeviceByDeviceType(@RequestBody String deviceType) {
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setDeviceTypePrefix(deviceType);
        List<DeviceRespVO> list = deviceService.getList(deviceReqVO);
        return DataResult.success(list);
    }

    //根据电站id查询
    @PostMapping("selectDeviceByStationIds")
    @TokenIgnore
    public DataResult<List<DeviceRespVO>> selectDeviceByStationIds(@RequestBody DeviceReqVO deviceReqVO) {
        List<DeviceRespVO> list = deviceService.getList(deviceReqVO);
        return DataResult.success(list);
    }

    //根据pid获取设备类型
    @PostMapping("getDeviceTypeOne")
    @TokenIgnore
    public DataResult<DeviceType> getDeviceTypeOne(@RequestBody Integer pid) {
        DeviceType one = deviceTypeService.getOne(pid);
        return DataResult.success(one);
    }

    //根据设备ids获取设备类型集合
    @PostMapping("getDeviceTypes")
    @TokenIgnore
    public DataResult<List<DeviceType>> getDeviceTypes(@RequestBody List<Integer> deviceIds) {
        List<DeviceType> deviceTypes = deviceTypeService.selectByIds(deviceIds);
        return DataResult.success(deviceTypes);
    }

    //根据dept_id查询电站信息
    @PostMapping("selectByDeptId")
    @TokenIgnore
    public DataResult<List<Station>> selectByDeptId(@RequestBody QueryDeptReqVO queryDeptReqVO) {
        DataResult<List<Station>> result = DataResult.success();
        List<Station> stations = stationService.selectByDeptId(queryDeptReqVO);
        result.setData(stations);
        return result;
    }

    //根据dept_id查询电站信息
    @PostMapping("selectByGroupId")
    @TokenIgnore
    public DataResult<List<Station>> selectByGroupId(@RequestBody Integer group) {
        DataResult<List<Station>> result = DataResult.success();
        List<Station> stations = stationService.selectByGroupId(group);
        result.setData(stations);
        return result;
    }

    //所有电站
    @PostMapping("selectAllStation")
    @TokenIgnore
    public DataResult<List<Station>> selectAllStation() {
        DataResult<List<Station>> result = DataResult.success();
        List<Station> stations = stationService.selectAll();
        result.setData(stations);
        return result;
    }

    @PostMapping("getByStationId")
    @ApiOperation(value = "查询电站下的设备列表")
    @TokenIgnore
    public DataResult<List<Device>> getDeviceByStationId(@RequestBody PointCurveReq pointCurveReq) {
        List<Device> list = new ArrayList<>();
        for (Integer stationId : pointCurveReq.getIds()) {
            Device device = new Device();
            device.setStationId(stationId);
            device.setDeviceName(pointCurveReq.getDeviceName());
            device.setDeviceType(pointCurveReq.getDeviceType());
            device.setVirtual(CommonConstant.ZERO);
            device.setCategory(CommonConstant.THREE);
            List<Device> deviceList = deviceService.getRealDevice(device);
            list.addAll(deviceList);
        }

        return DataResult.success(list);
    }

    //根据deptIds查询电站信息
    @PostMapping("selectByDeptIds")
    @TokenIgnore
    public DataResult<List<Station>> selectByDeptIds(@RequestBody QueryDeptReqVO queryDeptReqVO) {
        DataResult<List<Station>> result = DataResult.success();
        log.info("selectByDeptIds deptIds ,{}", queryDeptReqVO.getDeptIds());
        List<Station> stations = stationService.selectByDeptIds(queryDeptReqVO.getDeptIds());
        if (stations == null || stations.isEmpty()) {
            return DataResult.getResult(BaseResponseCode.STATION_NO_FOUND);
        }
        result.setData(stations);
        return result;
    }

    //加工一体柜 充电量放电量,当月充电量,放电量
    @PostMapping("jobIntegratedCabinet")
    @TokenIgnore
    public DataResult jobIntegratedCabinet(@RequestBody MonitorQuery monitorQuery) {
        log.info("jobIntegratedCabinet, {}", monitorQuery);
        outApiService.dayChargeDeal(monitorQuery);
//        outApiService.currentMonthYearDeal(monitorQuery);
//        outApiService.dayPVCharge(monitorQuery);
        outApiService.dayPVMpptCharge(monitorQuery);
        return DataResult.success();
    }
    //暴露接口加工一体柜 充电量放电量,当月充电量,放电量
    @PostMapping("jobCabinet")
    @ApiOperation(value = "暴露接口加工一体柜 充电量放电量,当月充电量,放电量")
    @TokenIgnore
    public DataResult jobCabinet(@RequestBody MonitorQuery monitorQuery) {
        log.info("jobCabinet, {}", monitorQuery);
        //对时间进行处理以及电站进行处理
        List<Integer> stationIds = new ArrayList<>();
        if (monitorQuery.getStationId() != null) {
            stationIds.add(monitorQuery.getStationId());
        }
        monitorQuery.setStationIds(stationIds);
        //时间
        Date BeginDate = DateUtil.parse(monitorQuery.getBeginTime());
        Date endDate = DateUtil.parse(monitorQuery.getEndTime());
        List<DateTime> dateTimes = DateUtil.rangeToList(BeginDate, endDate, DateField.DAY_OF_MONTH);
        for (DateTime dateTime : dateTimes) {
            String dateString = dateTime + "";
            String substring = dateString.substring(0, 10);
            monitorQuery.setBeginTime(substring);
            outApiService.dayChargeDeal(monitorQuery);
        }
        return DataResult.success();
    }

    //加工一体柜 充电量放电量,当月充电量,放电量（小时）
    @PostMapping("jobIntegratedCabinetHour")
    @ApiOperation(value = "加工一体柜 充电量放电量,当月充电量,放电量（小时）")
    @TokenIgnore
    public DataResult jobIntegratedCabinetHour(@RequestBody MonitorQuery monitorQuery) throws ParseException {
        log.info("jobIntegratedCabinetHour, {}", monitorQuery);
        outApiService.hourChargeDeal(monitorQuery);
        return DataResult.success();
    }

    @PostMapping("/selectBySn")
    @TokenIgnore
    public Station selectBySn(@RequestBody StationReqVO vo) {
        Station station = stationService.selectBySn(vo.getSn());
        return station;
    }

    @PostMapping("getDeviceSN")
    @TokenIgnore
    public List<DeviceRespVO> getDeviceSN(@RequestBody @Valid DeviceReqVO deviceReqVO) {
        List<DeviceRespVO> deviceList = deviceService.getList(deviceReqVO);
        return deviceList;
    }

    @PostMapping("getDeviceTypeConfigList")
    @TokenIgnore
    public List<DeviceTypeConfig> getDeviceTypeConfigList(@RequestBody DeviceTypeQuery deviceTypeQuery) {
        List<DeviceTypeConfig> deviceTypeConfigs = deviceTypeConfigService.queryListByCondition(deviceTypeQuery);
        return deviceTypeConfigs;
    }


    /**
     * 定时删除图片和文件
     *
     * @return
     */
    @PostMapping("deletedPicture")
    @TokenIgnore
    public DataResult deletedPicture() {
        //查询全部数据
        List<Picture> pictures = pictureService.selectAll();
        //筛选未关联的工单号的图片和文件数据
        pictures = pictures.stream().filter(s -> {
            return s.getSrcId() == null;
        }).collect(Collectors.toList());
        //工单图片的id
        List<Integer> picturesIds = new ArrayList<>();
        for (Picture picture : pictures) {
            picturesIds.add(picture.getId());
            //删除在虚拟机中的文件
            File file = new File(picture.getUrl());
            file.delete();
        }
        //再删除数据库中的对象
        pictureService.deletedByIds(picturesIds);
        return DataResult.success();
    }


    //包含虚拟设备
    @PostMapping("getQueryEventParam")
    @TokenIgnore
    public List<EventColReq> getQueryEventParam(@RequestBody DeviceListReq deviceListReq) {
        List<EventColReq> list = deviceService.getQueryEventParam(deviceListReq);
        return list;
    }

    //查询日发电量
    @PostMapping("getDailyGenerate")
    @TokenIgnore
    public DataResult<List<ElecPowerGeneration>> getDailyGenerate(@RequestBody MonitorQuery monitorQuery) {
        List<ElecPowerGeneration> powers = new ArrayList<>();
        //多个电站
        List<Integer> stationIds = monitorQuery.getStationIds();
        if (stationIds != null && !stationIds.isEmpty()) {
            for (Integer stationId : stationIds) {
                List<DeviceRespVO> deviceList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.BMS);
                if (!deviceList.isEmpty()) {
                    for (DeviceRespVO deviceRespVO : deviceList) {
                        ElecPowerGeneration dayPower = outApiService.getDayPower(deviceRespVO, monitorQuery.getBegin(), monitorQuery.getEnd());
                        dayPower.setStationId(stationId);
                        dayPower.setSrcId(deviceRespVO.getSrcId());
                        powers.add(dayPower);
                    }
                }
            }
        }
        return DataResult.success(powers);
    }

    //根据站和设备类型查设备列表
    @PostMapping("getDeviceListByDeviceType")
    @TokenIgnore
    public DataResult<List<DeviceRespVO>> getDeviceListByDeviceType(@RequestBody DeviceReqVO deviceReqVO) {
        //结果集
        List<DeviceRespVO> deviceList = new ArrayList<>();
        List<Integer> stationIds = deviceReqVO.getStationIds();
        String deviceType = deviceReqVO.getDeviceType();
        if (stationIds != null && !stationIds.isEmpty()) {
            for (Integer stationId : stationIds) {
                List<DeviceRespVO> list = deviceService.getListByDeviceType(stationId, deviceType);
                if (!list.isEmpty()) {
                    deviceList.addAll(list);
                }
            }
        }

        return DataResult.success(deviceList);
    }

    //根据站id和src_id查设备
    @PostMapping("selectBySrcIdAndStationId")
    @TokenIgnore
    public DataResult<DeviceRespVO> selectBySrcIdAndStationId(@RequestBody DeviceReqVO vo) {
        //结果集
        DeviceRespVO deviceRespVO = deviceService.selectBySrcIdAndStationId(vo.getStationId(), vo.getSrcId());
        return DataResult.success(deviceRespVO);
    }


    @PostMapping("/selectDeviceTypeCol")
    @TokenIgnore
    public List<DeviceTypeCol> selectDeviceTypeCol(@RequestBody DeviceTypeColQueryVo vo) {
        List<DeviceTypeCol> deviceTypeCols = deviceTypeColService.selectDeviceTypeCol(vo);
        return deviceTypeCols;
    }


    /**
     * 对外提供上送数据接口
     *
     * @param vo
     * @return
     */
    @PostMapping("/getAllReportPushData")
    @TokenIgnore
    public DataResult<Map<Object, Object>> getAllReportPushData(@RequestBody PushDataReq vo) {
        String stationId = getStationId(vo.getApiSecret());
        Map<Object, Object> hgetall = new HashMap<>();
        if (stationId != null) {
            String tempId = outApiService.getTempId(Integer.valueOf(stationId));
            if(tempId==null){
//                String redisKey = DataCollectConstant.STATION + ":" + DataCollectConstant.DATA + ":" + stationId;
//                hgetall = redisService.hgetall(redisKey);
                //104
                String pushKey = RedisKeyConstant.FORWARD_DATA + CommonConstant.MQTT_DATATYPE.PUSH_TIMING+":" + DataCollectConstant.DATA + ":" + stationId;
                Map<Object, Object> pushAll = redisService.hgetall(pushKey);
                //105
//                String burstKey = RedisKeyConstant.FORWARD_DATA + CommonConstant.MQTT_DATATYPE.BURST+":" + DataCollectConstant.DATA + ":" + stationId;
//                Map<Object, Object> burstAll = redisService.hgetall(burstKey);
//                JSONObject pushDevice = (JSONObject)pushAll.get(DataCollectConstant.DEVICE);
//                JSONObject burstDevice = (JSONObject)burstAll.get(DataCollectConstant.DEVICE);
//                JSONArray list1 = (JSONArray)pushDevice.get(DataCollectConstant.LIST);
//                JSONArray list2 = (JSONArray)burstDevice.get(DataCollectConstant.LIST);
//                List deviceList1 = Arrays.asList(list1.stream().toArray());
//                List deviceList2 = Arrays.asList(list2.stream().toArray());
//                for (int i = 0; i < deviceList1.size(); i++) {
//                    JSONObject deviceObject = (JSONObject) deviceList1.get(i);
//                    JSONObject dataSet = (JSONObject)deviceObject.get(DataCollectConstant.DATA_SET);
//                    String s = deviceObject.get(DataCollectConstant.ID).toString();
//                    for (int j = 0; j < deviceList2.size(); j++) {
//                        JSONObject deviceObject1 = (JSONObject) deviceList2.get(j);
//                        JSONObject dataSet2 = (JSONObject)deviceObject1.get(DataCollectConstant.DATA_SET);
//                        String id = deviceObject1.get(DataCollectConstant.ID).toString();
//                        if(id.equals(s)){
//                            dataSet.putAll(dataSet2);
//                        }
//                    }
//                }
//                Object freeTime = burstAll.get(DataCollectConstant.FREEZE_TIME);
//                pushAll.put(DataCollectConstant.FREEZE_TIME,freeTime);
                hgetall = pushAll;
                log.info("转发数据:{},数据:{}",stationId,hgetall);
            }else{
                hgetall = outApiService.getForwardPushData(Integer.valueOf(stationId),Integer.valueOf(tempId));
            }
        }
        return DataResult.success(hgetall);
    }

    /**
     * 对外提供控制的点的集合
     *
     * @param vo
     * @return
     */
    @PostMapping("/pointPage")
    @TokenIgnore
    public DataResult<PageResult<ApiPointRespVO>> pointPage(@RequestBody ApiPointReq vo) {
        String stationId = getStationId(vo.getApiSecret());
        List<PointRespVO> pointList = new ArrayList<>();
        if (stationId != null) {
            vo.setStationId(Integer.valueOf(stationId));
            String name = vo.getName();
            if (name != null) {
                name = name.trim();
                vo.setName(name);
            }
            PointReq pointReq = new PointReq();
            BeanUtil.copyProperties(vo, pointReq);
            pointReq.setIsSave(CommonConstant.ONE);
            pointList = pointDemoService.getPointList(pointReq);
        }
        //java内存分页
        PageResult pageResult = new PageResult<>();
        if (!pointList.isEmpty()) {
            ApiPointRespVO apiPointRespVO = null;
            List<ApiPointRespVO> resultPointList = new ArrayList<>();
            for (PointRespVO point : pointList) {
                apiPointRespVO = new ApiPointRespVO();
                BeanUtil.copyProperties(point, apiPointRespVO);
                resultPointList.add(apiPointRespVO);
            }
            List list = PageUtils.dealList(resultPointList, vo.getPageNum(), vo.getPageSize());
            pageResult = PageUtils.getPageResult(new PageInfo<>(list));
            pageResult.setTotalRows(resultPointList.size());
            pageResult.setTotalPages(resultPointList.size() / vo.getPageSize() + 1);
        } else {
            pageResult = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }
        return DataResult.success(pageResult);
    }

    private String getStationId(String apiSecret) {
        SysSubDictVO sysSubDictVO = new SysSubDictVO();
        sysSubDictVO.setType(CommonConstant.PUSH_DATA);
        Map<String, String> sysSubDict = userFeignClient.getSysSubDict(sysSubDictVO);
        String stationId = sysSubDict.get(apiSecret);
        return stationId;
    }


    /**
     * 对外提供历史数据数据接口
     *
     * @param vo
     * @return
     */
    @PostMapping("/getAllHisData")
    @TokenIgnore
    public DataResult<PageResult<Map<Object, Object>>> getAllHisData(@RequestBody PushDataReq vo) {
        PageResult<Map<Object, Object>> pointCurveRespList = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        String stationIdString = getStationId(vo.getApiSecret());
        Map<Object, Object> hgetall = new HashMap<>();
        if (stationIdString != null) {
            //写具体代码
            //开始结束时间
            Date date = new Date();
            String nowDay = DateUtil.format(date, CommonConstant.DATE);
            Calendar c = Calendar.getInstance();
            //过去七天
            c.setTime(new Date());
            c.add(Calendar.DATE, -6);
            Date d = c.getTime();
            String begin = DateUtil.format(d, CommonConstant.DATE);

            Integer stationId = Integer.valueOf(stationIdString);
            Device deviceStorage = deviceService.selectByStationIdAndSrcId(stationId, vo.getSrcId());
            if (deviceStorage == null || deviceStorage.getDeviceType() == null) {
                log.error("deviceType:{} Not Found !!");
            }
            String deviceType = deviceStorage.getDeviceType().trim();
            log.info("deviceType:" + deviceType);
            //改为从deviceTypeConfig表查数据
            DeviceTypeQuery deviceTypeQuery = new DeviceTypeQuery();
            deviceTypeQuery.setGroupId(deviceStorage.getGroupId());
            deviceTypeQuery.setDeviceType(deviceType);
            List<DeviceTypeConfig> deviceTypeConfigs = deviceTypeConfigService.queryListByCondition(deviceTypeQuery);
            if (deviceTypeConfigs.isEmpty()) {
                log.error("未找到该设备配置类型");
            }
            DeviceTypeConfig deviceTypeConfig = deviceTypeConfigs.get(0);
            if (StringUtils.isEmpty(deviceTypeConfig.getModelName())) {
                log.error("未配置modelName 超级表类型");
            }
            //组表明，进行查询
            TdBase tdBase = new TdBase();
            tdBase.setGroupId(deviceStorage.getGroupId());
            tdBase.setStationId(stationId);
            tdBase.setSrcId(vo.getSrcId());
            tdBase.setTableName(deviceTypeConfig.getModelName());
            tdBase.setBeginTime(begin);
            tdBase.setEndTime(nowDay);
            tdBase.setBeginNum((vo.getPageNum() - 1) * vo.getPageSize());
            tdBase.setPageSize(vo.getPageSize());
            pointCurveRespList = pointDemoService.getPointAllData(tdBase);

        }
        return DataResult.success(pointCurveRespList);
    }

    /**
     * 对外提供col和中文映射关系
     *
     * @param vo
     * @return
     */
    @PostMapping("/getMappingRelationship")
    @ApiOperation(value = "对外提供col和中文映射关系")
    @TokenIgnore
    public DataResult<PageResult<ApiMappingRelation>> getMappingRelationship(@RequestBody ApiPointReq vo) {
        SysSubDictVO sysSubDictVO = new SysSubDictVO();
        sysSubDictVO.setType(CommonConstant.PUSH_DATA);
        Map<String, String> sysSubDict = userFeignClient.getSysSubDict(sysSubDictVO);
        String stationId = sysSubDict.get(vo.getApiSecret());
        List<PointRespVO> pointList = new ArrayList<>();
        if (stationId != null) {
            vo.setStationId(Integer.valueOf(stationId));
            String name = vo.getName();
            if (name != null) {
                name = name.trim();
                vo.setName(name);
            }
            PointReq pointReq = new PointReq();
            BeanUtil.copyProperties(vo, pointReq);
            pointList = pointDemoService.getPointList(pointReq);
        }
        //java内存分页
        PageResult pageResult = new PageResult<>();
        if (!pointList.isEmpty()) {
            ApiMappingRelation apiPointRespVO = null;
            List<ApiMappingRelation> resultPointList = new ArrayList<>();
            for (PointRespVO point : pointList) {
                apiPointRespVO = new ApiMappingRelation();
                BeanUtil.copyProperties(point, apiPointRespVO);
                resultPointList.add(apiPointRespVO);
            }
            List list = PageUtils.dealList(resultPointList, vo.getPageNum(), vo.getPageSize());
            pageResult = PageUtils.getPageResult(new PageInfo<>(list));
            pageResult.setTotalRows(resultPointList.size());
            pageResult.setTotalPages(resultPointList.size() / vo.getPageSize() + 1);
        } else {
            pageResult = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }
        return DataResult.success(pageResult);
    }

    /**
     * 对外提电站信息数据
     *
     * @param vo
     * @return
     */
    @PostMapping("/getStationData")
    @TokenIgnore
    public DataResult<OutStationData> getStationData(@RequestBody StationDataReq vo) {
        String stationId = getStationId(vo.getApiSecret());
        OutStationData stationData = new OutStationData();
        if (null != stationId) {
            StationReq req = new StationReq();
            req.setStationId(Integer.valueOf(stationId));
            stationData = stationHomeService.getStationData(req);
        }
        return DataResult.success(stationData);
    }

    /**
     * 获取电站列表
     *
     * @param vo
     * @return
     */
    @PostMapping("/getProvinceStationList")
    @TokenIgnore
    public DataResult<List<OutStationList>> getProvinceStationList(@RequestBody StationDataReq vo) {
        SysSubDictVO sysSubDictVO = new SysSubDictVO();
        sysSubDictVO.setType(CommonConstant.DEMO_USER);
        Map<String, String> sysSubDict = userFeignClient.getSysSubDict(sysSubDictVO);
        String stationId = sysSubDict.get(vo.getApiSecret());
        List<OutStationList> resultList = new ArrayList<>();
        if (stationId != null) {
            String[] split = stationId.split(",");
            List<Integer> ids = new ArrayList<>();
            for (String s : split) {
                ids.add(Integer.valueOf(s));
            }
            SimpleUser user = new SimpleUser();
            user.setStationIds(ids);
            List<ProvinceStation> provinceStationList = stationService.getProvinceStationList(user);
            for (ProvinceStation p : provinceStationList) {
                OutStationList outStationList = new OutStationList();
                List<OutStaion> list = new ArrayList<>();
                List<Station> stationList = p.getList();
                for (Station s : stationList) {
                    OutStaion outStaion = new OutStaion();
                    outStaion.setId(s.getId());
                    outStaion.setName(s.getName());
                    list.add(outStaion);
                }
                outStationList.setName(p.getName());
                outStationList.setList(list);
                resultList.add(outStationList);
            }
        }
        return DataResult.success(resultList);
    }

    //电站运维数据定时任务
    @PostMapping("jobStationState")
    @TokenIgnore
    public DataResult jobStationState() {
        //查询未删除和要统计的电站数据
        Integer deleted = 1;
        Integer dailyCount = 1;
        List<Station> stationList = stationService.selectStatistics(deleted, dailyCount);
        outApiService.getJobStationState(stationList);
        return DataResult.success();
    }

    //曲线数据查询(供外部API)
    @PostMapping("pointCurveForApi")
    @TokenIgnore
    public List<PointCurveResp> pointCurveForApi(@RequestBody @Valid PointCurveReq pointCurveReq) {
        List<PointCurveResp> pointCurveRespList = new ArrayList<>();
        //对开始结束时间进行处理 （对bug129）
        if (pointCurveReq.getBeginTime() != null) {
            pointCurveReq.setBeginTime(pointCurveReq.getBeginTime().substring(0, pointCurveReq.getBeginTime().length() - 1) + "1");
        }
        if (pointCurveReq.getEndTime() != null) {
            pointCurveReq.setEndTime(pointCurveReq.getEndTime().substring(0, pointCurveReq.getEndTime().length() - 1) + "1");
        }
        //对传输过来的col集合进行判断是否大于10个
        if (pointCurveReq.getDeviceIdList().size() < 50) {
            pointCurveRespList = pointDemoService.getPointCurve(pointCurveReq);
        }
        for (PointCurveResp pointCurveResp : pointCurveRespList) {
            List<StatisticsCurve> staticCurveList = pointCurveResp.getStaticCurveList();
            for (StatisticsCurve statisticsRespVO : staticCurveList) {
                if (null != statisticsRespVO.getDigital()) {
                    statisticsRespVO.setDigital(NumberUtil.round(statisticsRespVO.getDigital(), 2).doubleValue());
                }
            }
        }
        return pointCurveRespList;
    }

    @PostMapping("/pcsStationData")
    @ApiOperation(value = "电站信息")
    @TokenIgnore
    public DataResult<PcsStationData> getPcsStationData(@RequestBody StationReq req,HttpServletRequest request) {
        String lang = request.getHeader(CommonConstant.LANG);
        PcsStationData data = stationHomeService.getPcsStationData(req.getStationId(),lang);
        return DataResult.success(data);
    }

    @PostMapping("/getSummaryData")
    @ApiOperation(value = "提供给前置机汇总数据使用")
    @TokenIgnore
    public DataResult<cn.hutool.json.JSONObject> getSummaryData(@RequestBody CommonQuery reqVo) {
        Object middlePart = commonService.getSummaryData(reqVo);
        return DataResult.success(middlePart);

    }

    @PostMapping("jobGetDayDate")
    @ApiOperation(value = "定时获取每个电站的日充日放")
    @TokenIgnore
    public DataResult jobGetDayDate() {
        log.info("jobGetDayDate");
        List<Station> stationList = stationService.selectAll();
        freezeService.getDayDate(stationList);
        return DataResult.success();
    }

    @PostMapping("jobGetSystemEfficiency")
    @ApiOperation(value = "定时计算电站的效率（colcount中配置的要算）")
    @TokenIgnore
    public DataResult jobGetSystemEfficiency() {
        log.info("jobGetSystemEfficiency ");
        outApiService.getSystemEfficiency();
        return DataResult.success();
    }

    /**
     * 对外提供上送筛选的数据接口(暂不开放，将功能合并到原实时上送的数据中)
     * @param vo
     * @return
     */
    @PostMapping("/getForwardPushData")
    @TokenIgnore
    public DataResult<Map<Object, Object>> getForwardPushData(@RequestBody PushDataReq vo) {
        String stationId = getStationId(vo.getApiSecret());
        Map<Object, Object> forwardPushData = new HashMap<>();
        if (null != stationId) {
            String tempId = outApiService.getTempId(Integer.valueOf(stationId));
            if(null != tempId){
                forwardPushData = outApiService.getForwardPushData(Integer.valueOf(stationId),Integer.valueOf(tempId));
            }
        }
        return DataResult.success(forwardPushData);
    }

    @PostMapping("page")
    @ApiOperation(value = "点表列表,分页")
    @TokenIgnore
    public DataResult<PageResult<PointRespVO>> page(@RequestBody @Valid PointReq pointReq) {
        String name = pointReq.getName();
        if (name != null) {
            name = name.trim();
            pointReq.setName(name);
        }
        List<PointRespVO> pointList = pointDemoService.getPointList(pointReq);
        //java内存分页
        PageResult pageResult = new PageResult<>();
        if (!pointList.isEmpty()) {
            List list = PageUtils.dealList(pointList, pointReq.getPageNum(), pointReq.getPageSize());
            pageResult = PageUtils.getPageResult(new PageInfo<>(list));
            pageResult.setTotalRows(pointList.size());
            pageResult.setTotalPages(pointList.size() / pointReq.getPageSize() + 1);
        } else {
            pageResult = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }
        return DataResult.success(pageResult);
    }

    @PostMapping("getIndustrialElecPricePage")
    @ApiOperation(value = "查询所有代理电价-分页")
    @TokenIgnore
    public DataResult<PageResult<IndustrialElecPrice>> getIndustrialElecPricePage(@RequestBody IndustrialElecPriceReqVo reqVo) {
        return industrialElecPriceService.getElecPriceList(reqVo);
    }

    @GetMapping("/getMaxPriceDiffById/{id}")
    @ApiOperation(value = "根据id查询峰谷电差价折线图/表格")
    @TokenIgnore
    public DataResult getMaxPriceDiffById(@PathVariable("id")Long id) {
        Map<String,Object> lineData = industrialElecPriceService.getMaxPriceDiffById(id);
        return DataResult.success(lineData);
    }

    @GetMapping("/getTouLineById/{id}")
    @ApiOperation(value = "根据id查询分时电价折线图")
    @TokenIgnore
    public DataResult getTouLineById(@PathVariable("id")Long id) {
        List<Map<String,Object>> lineData = industrialElecPriceService.getTouLineById(id);
        return DataResult.success(lineData);
    }

    @GetMapping("/getTouLineHistoryById/{id}")
    @ApiOperation(value = "根据id查询分时电价历史数据图表/表格")
    @TokenIgnore
    public DataResult getTouLineHistoryById(@PathVariable("id")Long id) {
        Map<String,Object> lineData = industrialElecPriceService.getTouLineHistoryById(id);
        return DataResult.success(lineData);
    }

    @PostMapping("getIndustrialElecPriceList")
    @ApiOperation(value = "查询所有代理电价区域-列表")
    @TokenIgnore
    public DataResult<IndustrialElecRegion> list() {
        List<IndustrialElecRegion> industrialElecPrices = industrialElecRegionMapper.findAllList();
        return DataResult.success(industrialElecPrices);
    }

    @PostMapping("/updateInspectionFault")
    @TokenIgnore
    public DataResult updateInspectionFault(@RequestBody InspectionFaultVo vo) {
        int count = inspectionFaultMapper.updateInspectionFault(vo.getOrderId(),vo.getStatus());
        return DataResult.success(count);
    }
}



