package com.chinaitop.depot.intelligent.energyMonitor.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.chinaitop.depot.intelligent.basicdata.service.WareHouseBasicInfoService;
import com.chinaitop.depot.intelligent.energyMonitor.model.TEnergyHistory;
import com.chinaitop.depot.intelligent.energyMonitor.model.TEnergyInfo;
import com.chinaitop.depot.intelligent.energyMonitor.service.EnergyDetectionService;
import com.chinaitop.depot.intelligent.grainsituation.service.TemperatureRecordService;
import com.chinaitop.depot.intelligent.socket.SocketClient;
import com.chinaitop.depot.intelligent.utils.RemoteControlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unissoft.model.ResponseEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @author hf
 * @description: 能耗检测
 * @create 2018-12-11 10:57
 */
@RestController
@RequestMapping(value = "/intelligents/energyDetection")
@Api(value = "EnergyDetectionController", description = "能耗检测控制类")
@SuppressWarnings("all")
public class EnergyDetectionController {

    @Resource
    private EnergyDetectionService energyDetectionService;
    @Resource
    private WareHouseBasicInfoService wareHouseBasicInfoService;
    @Resource
    private RemoteControlUtil remoteControlUtil;
    @Autowired
    private TemperatureRecordService temperatureRecordService;

    /**
     * 列表
     * @param pageNum
     * @param pageSize
     * @param orgId
     * @param vnhcode
     * @param vhhtype
     * @param type
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ApiOperation(value = "能耗检测信息列表", notes = "查询能耗检测信息列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "机构id", paramType = "query"),
            @ApiImplicitParam(name = "vnhcode", value = "设备编号", paramType = "query"),
            @ApiImplicitParam(name = "vhhtype", value = "检测类型", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "区分不同模块的能耗监测", paramType = "query")
    })
    public ResponseEntity<PageInfo<TEnergyHistory>> getList(Integer pageNum, Integer pageSize, Integer orgId, 
    		String vnhcode,String vhhtype, String type) {
        List<TEnergyHistory> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            Map<String,Object> map = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(vhhtype)) {
            	map.put("vhhtype", vhhtype);
            }
            if (StringUtils.isNotBlank(vnhcode)) {
            	map.put("vnhcode", vnhcode);
            }
            if (orgId != null) {
            	map.put("orgId", orgId);
            }
            if (StringUtils.isNotBlank(type)) {
            	map.put("type", type);
            }
            list = energyDetectionService.getList(map);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TEnergyHistory> pageInfo = new PageInfo<TEnergyHistory>(list);
        return ResponseEntity.ok(pageInfo);
    }
    
    /**
     * 能耗电表查询
     * @param pageNum
     * @param pageSize
     * @param orgId
     * @param deviceNumber
     * @return
     */
    @RequestMapping(value = "/queryMeterList", method = RequestMethod.GET)
    @ApiOperation(value = "能耗电表查询", notes = "能耗电表查询")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
    	@ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
    	@ApiImplicitParam(name = "orgId", value = "机构Id", paramType = "query"),
    	@ApiImplicitParam(name = "deviceNumber", value = "设备编码", paramType = "query")
    })
    public ResponseEntity<PageInfo<TEnergyInfo>> queryMeterList(Integer pageNum, Integer pageSize, Integer orgId, String deviceNumber) {
    	List<TEnergyInfo> list = null;
    	try {
    		if (null != pageNum && null != pageSize) {
    			PageHelper.startPage(pageNum, pageSize);
    		}
    		
    		Map<String,Object> map = new HashMap<String,Object>();
    		map.put("orgId", orgId);
    		if(deviceNumber != null && deviceNumber != "") {
    			map.put("deviceNumber", deviceNumber);
    		}
    		list = energyDetectionService.queryMeter(map);
    	} catch (Exception e) {
    		e.printStackTrace();
    		ResponseEntity.failed(e.getMessage());
    	}
    	PageInfo<TEnergyInfo> pageInfo = new PageInfo<TEnergyInfo>(list);
    	return ResponseEntity.ok(pageInfo);
    }
    
    /**
     * 获取设备编号列表
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/queryDeviceList", method = RequestMethod.GET)
    @ApiOperation(value = "能耗电表查询", notes = "能耗电表查询")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "orgId", value = "机构Id", paramType = "query")
    })
    public ResponseEntity<PageInfo<TEnergyInfo>> queryDeviceList(Integer orgId) {
    	List<TEnergyInfo> list = null;
    	try {
    		Map<String,Object> map = new HashMap<String,Object>();
    		map.put("orgId", orgId);
    		list = energyDetectionService.queryDeviceList(map);
    	} catch (Exception e) {
    		e.printStackTrace();
    		ResponseEntity.failed(e.getMessage());
    	}
    	PageInfo<TEnergyInfo> pageInfo = new PageInfo<TEnergyInfo>(list);
    	return ResponseEntity.ok(pageInfo);
    }
    
    /**
     * 能耗趋势
     * @param orgId 库id
     * @param startDate 检查开始时间
     * @param endDate 检查结束时间
     * @return
     */
    @RequestMapping(value = "/getTrendThreePage", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    @ApiOperation(value="能耗趋势数据", notes = "能耗趋势数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "组织机构id", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "检查开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "检查结束时间", paramType = "query")
    })
    public List<Map<String, Object>> getTrendThreePage(Integer orgId,String startDate,String endDate) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orgId", orgId);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        List<Map<String, Object>> SelectDay = energyDetectionService.getTrendThreePage(map);
        return SelectDay;
    }
    
    /**
     * 能耗时间点对比
     * @param orgId 库id
     * @param startDate 时间点一
     * @param endDate 时间点二
     * @return
     */
    @RequestMapping(value = "/getTimePointThreePage", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    @ApiOperation(value="能耗时间点对比数据", notes = "能耗时间点对比数据")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "orgId", value = "组织机构id", paramType = "query"),
    	@ApiImplicitParam(name = "startDate", value = "时间点一", paramType = "query"),
    	@ApiImplicitParam(name = "endDate", value = "时间点二", paramType = "query")
    })
    public List<Map<String, Object>> getTimePointThreePage(Integer orgId,String startDate,String endDate) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("orgId", orgId);
    	map.put("startDate", startDate);
    	map.put("endDate", endDate);
    	List<Map<String, Object>> SelectDay = energyDetectionService.getTimePointThreePage(map);
    	return SelectDay;
    }
    
    /**
     * 能耗时间段对比
     * @param orgId 库id
     * @param vHhtype 设备类型
     * @param oneTimeStart 时间段一开始
     * @param oneTimeEnd 时间段一结束
     * @param twoTimeStart 时间段二开始
     * @param twoTimeEnd 时间段二结束
     * @return
     */
    @RequestMapping(value = "/getTimeThreePage", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    @ApiOperation(value="能耗时间段对比数据", notes = "能耗时间段对比数据")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "orgId", value = "组织机构id", paramType = "query"),
    	@ApiImplicitParam(name = "vHhtype", value = "设备类型", paramType = "query"),
    	@ApiImplicitParam(name = "oneTimeStart", value = "时间段一开始", paramType = "query"),
    	@ApiImplicitParam(name = "oneTimeEnd", value = "时间段一结束", paramType = "query"),
    	@ApiImplicitParam(name = "twoTimeStart", value = "时间段二开始", paramType = "query"),
    	@ApiImplicitParam(name = "twoTimeEnd", value = "时间段二结束", paramType = "query")
    })
    public Map<String, Object> getTimeThreePage(Integer orgId,String vHhtype,
    		String oneTimeStart,String oneTimeEnd,String twoTimeStart,String twoTimeEnd) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("orgId", orgId);
    	map.put("type", vHhtype);
    	map.put("startDate", oneTimeStart);
    	map.put("endDate", oneTimeEnd);
    	List<Map<String, Object>> oneTime = energyDetectionService.getTimeThreePage(map);
    	List<Map<String, Object>> twoTime = new ArrayList<Map<String, Object>>();
    	if(twoTimeStart != null && twoTimeStart != "") {
    		map.put("startDate", twoTimeStart);
        	map.put("endDate", twoTimeEnd);
    		twoTime = energyDetectionService.getTimeThreePage(map);
    	}
    	
    	Map<String, Object> mapList = new HashMap<String, Object>();
    	mapList.put("oneTime", oneTime);
    	mapList.put("twoTime", twoTime);
    	return mapList;
    }
    
    /**
     * 按时段统计能耗列表
     * @param pageNum
     * @param pageSize
     * @param orgId
     * @param vhhtype
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "/getDailyConsumptionList", method = RequestMethod.GET)
    @ApiOperation(value = "按时段统计能耗列表", notes = "按时段统计能耗列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织机构id", paramType = "query"),
            @ApiImplicitParam(name = "vHhtype", value = "检测类型", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "统计开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "统计结束时间", paramType = "query")
    })
    public ResponseEntity<PageInfo<TEnergyHistory>> getDailyConsumptionList(Integer pageNum, Integer pageSize, 
    		Integer orgId, String vHhtype, String startDate, String endDate) {
        List<TEnergyHistory> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("orgId", orgId);
            map.put("vhhtype", vHhtype);
            map.put("startDate", startDate);
            map.put("endDate", endDate);
            list = energyDetectionService.getDailyConsumptionList(map);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TEnergyHistory> pageInfo = new PageInfo<TEnergyHistory>(list);
        return ResponseEntity.ok(pageInfo);
    }
    
    /**
     * 按作业统计能耗列表
     * @param pageNum
     * @param pageSize
     * @param orgId
     * @param vhhtype
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "/getTaskConsumptionList", method = RequestMethod.GET)
    @ApiOperation(value = "按作业统计能耗列表", notes = "按作业统计能耗列表，支持分页")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
    	@ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
    	@ApiImplicitParam(name = "orgId", value = "组织机构id", paramType = "query"),
    	@ApiImplicitParam(name = "vHhtype", value = "检测类型", paramType = "query"),
    	@ApiImplicitParam(name = "startDate", value = "统计开始时间", paramType = "query"),
    	@ApiImplicitParam(name = "endDate", value = "统计结束时间", paramType = "query")
    })
    public ResponseEntity<PageInfo<TEnergyHistory>> getTaskConsumptionList(Integer pageNum, Integer pageSize, 
    		Integer orgId, String vHhtype, String startDate, String endDate) {
    	List<TEnergyHistory> list = null;
    	try {
    		if (null != pageNum && null != pageSize) {
    			PageHelper.startPage(pageNum, pageSize);
    		}
    		Map<String,Object> map = new HashMap<String,Object>();
    		map.put("orgId", orgId);
    		map.put("vhhtype", vHhtype);
    		map.put("startDate", startDate);
    		map.put("endDate", endDate);
    		list = energyDetectionService.getTaskConsumptionList(map);
    	} catch (Exception e) {
    		e.printStackTrace();
    		ResponseEntity.failed(e.getMessage());
    	}
    	PageInfo<TEnergyHistory> pageInfo = new PageInfo<TEnergyHistory>(list);
    	return ResponseEntity.ok(pageInfo);
    }
    

    /**
     * 电表列表
     * @param pageNum
     * @param pageSize
     * @param orgId
     * @param vhhtype
     * @param vcfcode
     * @return
     */
    @RequestMapping(value = "/getAmmeterPageInfo", method = RequestMethod.GET)
    @ApiOperation(value = "电表列表", notes = "查询电表列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "库区id", paramType = "query"),
            @ApiImplicitParam(name = "vhhtype", value = "检测类型", paramType = "query"),
            @ApiImplicitParam(name = "vcfcode", value = "库区编码", paramType = "query")
    })
    public ResponseEntity<PageInfo<TEnergyInfo>> getAmmeterPageInfo(Integer pageNum, Integer pageSize, Integer orgId, String vhhtype, String vcfcode) {
        List<TEnergyInfo> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("orgId", orgId);
            map.put("vhhtype", vhhtype);
            map.put("vcfcode", vcfcode);
            map.put("delFlag",1); //未删除
            list = energyDetectionService.getAmmeterPageInfo(map);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseEntity.failed(e.getMessage());
        }
        PageInfo<TEnergyInfo> pageInfo = new PageInfo<>(list);
        return ResponseEntity.ok(pageInfo);
    }
    
    /**
     * 根据id删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ApiOperation(value = "根据id删除", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "电表id", paramType = "form"),
            @ApiImplicitParam(name = "orgId", value = "单位ID", paramType = "form")
    })
    public ResponseEntity deleteById(String id, String ammeterJson, @RequestParam @NotNull String orgId) {
    	// 1.获取库端url
        String url = temperatureRecordService.getRemoteUrl(orgId);
        if (StringUtils.isBlank(url))
            return ResponseEntity.failed("库端硬件地址未配置!");
        // 2.封装请求数据
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("ammeterJson", ammeterJson);
        requestEntity.add("id", id);
        return remoteControlUtil.remoteScan(
                String.format("%s%s", url, RemoteControlUtil.energyDetectionRemove),
                requestEntity
        );
//        if (StringUtils.isNotBlank(id)) {
//            int count = energyDetectionService.deleteById(id, ammeterJson);
//            if (count > 0) {
//                ResponseEntity.ok();
//                return ResponseEntity.ok();
//            } else {
//                return ResponseEntity.failed("删除失败!");
//            }
//        }
//        return ResponseEntity.failed("ID数据有误!");
    }
    
    /**
     * 根据id查询信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    @ApiOperation(value = "根据id查询电表信息", notes = "根据id查询电表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "电表id", paramType = "query")
    })
    public ResponseEntity<TEnergyInfo> getById(String id) {
    	TEnergyInfo tEnergyInfo = null;
        if (StringUtils.isNotBlank(id)) {
        	tEnergyInfo = energyDetectionService.getById(id);
        } else {
            return ResponseEntity.failed("ID数据有误!");
        }
        return ResponseEntity.ok(tEnergyInfo);
    }
    
    /**
     * 验证编码是否重复
     * @param id
     * @param vNhCode
     * @return
     */
    @RequestMapping(value = "/validCode", method = RequestMethod.GET)
    @ApiOperation(value = "根据id查询电表信息", notes = "根据id查询电表信息")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "id", value = "电表id", paramType = "query"),
    	@ApiImplicitParam(name = "vNhCode", value = "电表编码", paramType = "query")
    })
    public ResponseEntity<TEnergyInfo> validCode(String id,String vNhCode) {
    	Map<String,Object> map = new HashMap<String,Object>();
        map.put("id", id);
        map.put("vNhCode", vNhCode);
    	TEnergyInfo tEnergyInfo = energyDetectionService.validCode(map);
    	return ResponseEntity.ok(tEnergyInfo);
    }

    @RequestMapping(value = "/saveAmmeter", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    @ApiOperation(value = "保存数据", notes = "保存数据")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "tEnergyInfoJson", value = "电表id", paramType = "form"),
    	@ApiImplicitParam(name = "orgId", value = "单位ID", paramType = "form")
    })
    public ResponseEntity saveAmmeter(String tEnergyInfoJson, @RequestParam @NotNull String orgId) {
    	// 1.获取库端url
        String url = temperatureRecordService.getRemoteUrl(orgId);
        if (StringUtils.isBlank(url))
            return ResponseEntity.failed("库端硬件地址未配置!");
        // 2.封装请求数据
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("tEnergyInfoJson", tEnergyInfoJson);
        return remoteControlUtil.remoteScan(
                String.format("%s%s", url, RemoteControlUtil.energyDetectionSave),
                requestEntity
        );
//        try {
//        	// JSON字符串转对象
//    		TEnergyInfo tEnergyInfo = (TEnergyInfo)JsonToObjectUtils.jsonToObject(tEnergyInfoJson,"com.chinaitop.depot.intelligent.energyMonitor.model.TEnergyInfo");
//    		tEnergyInfo.setvUpdateTime(new Date());
//            // 获取Max+1值
//            Map<String, Object> valueMax = wareHouseBasicInfoService.getCode("t_energy_info", "v_zd_code", "v_nh_code", null);
//            tEnergyInfo.setvNhCode(valueMax.get("column2").toString());
//    		if (tEnergyInfo.getId() == null) {
//    			energyDetectionService.add(tEnergyInfo);
//                // 推送数据并返回结果
//                SendEntity.cxfFactor().saveEnergyData(SendEntity.energyData(tEnergyInfoJson, "I", tEnergyInfo.getvUpdateTime(), tEnergyInfo.getvNhCode()));
//            } else {
//    			energyDetectionService.update(tEnergyInfo);
//                SendEntity.cxfFactor().saveEnergyData(SendEntity.energyData(tEnergyInfoJson, "U", tEnergyInfo.getvUpdateTime(), null));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.failed("更新失败");
//        }
//        return ResponseEntity.ok();
    }
    
    @Autowired
    private SocketClient socketClient;
    /**
     * 添加能耗检查数据
     * @return
     */
    @RequestMapping(value = "/addHistoryData", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    public ResponseEntity addHistoryData(String orgId) {
        // 1.获取库端url
        String url = temperatureRecordService.getRemoteUrl(orgId);
        if (org.apache.commons.lang.StringUtils.isBlank(url))
            return ResponseEntity.failed("库端硬件地址未配置!");
        // 2.封装请求数据
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        return remoteControlUtil.remoteScan(
                String.format("%s%s", url, remoteControlUtil.energyOrder),
                requestEntity
        );
    }

    @RequestMapping(value = "/synchronizationAll", method = RequestMethod.GET)
    @ApiOperation(value = "与智远同步能耗设备信息基础数据", notes = "与智远同步能耗设备信息基础数据")
    @ApiImplicitParam(name = "orgId", value = "库房编码", paramType = "query")
    public ResponseEntity synchronizationAll(@RequestParam @NotNull String orgId) {
    	// 1.获取库端url
        String url = temperatureRecordService.getRemoteUrl(orgId);
        if (StringUtils.isBlank(url))
            return ResponseEntity.failed("库端硬件地址未配置!");
        // 2.封装请求数据
        Map<String, String> requestEntity = new HashMap<>();
        requestEntity.put("orgId", orgId);
        return remoteControlUtil.remoteScan(
                String.format("%s%s", url, RemoteControlUtil.energyDetectionSYN),
                requestEntity
        );
//    	if (org.apache.commons.lang3.StringUtils.isBlank(orgId)){
//            return ResponseEntity.ok("库房编码不能为空！");
//        }
//        String msg = null;
//        try {
//            msg = energyDetectionService.synchronizationAll(orgId);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.ok("同步失败！");
//        }
//        return ResponseEntity.ok(msg);
    }
}
