package org.jeecg.modules.statistics.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.device.service.IBuDeviceService;
import org.jeecg.modules.statistics.entity.BuDeviceStatistics;
import org.jeecg.modules.statistics.model.OpenStatistics;
import org.jeecg.modules.statistics.service.IBuDeviceEnergyStatisticsService;
import org.jeecg.modules.statistics.service.IBuDeviceStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.*;

/**
 * @Description: 设备信息统计表
 * @Author: jeecg-boot
 * @Date:   2021-01-18
 * @Version: V1.0
 */
@Api(tags="设备信息统计表")
@RestController
@RequestMapping("/statistics/buDeviceStatistics")
@Slf4j
public class BuDeviceStatisticsController extends JeecgController<BuDeviceStatistics, IBuDeviceStatisticsService> {
	@Autowired
	private IBuDeviceStatisticsService buDeviceStatisticsService;
	@Autowired
	private IBuDeviceEnergyStatisticsService buDeviceEnergyStatisticsService;
	@Autowired
	private IBuDeviceService buDeviceService;

	/**
	 * 分页列表查询
	 *
	 * @param buDeviceStatistics
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "设备信息统计表-分页列表查询")
	@ApiOperation(value="设备信息统计表-分页列表查询", notes="设备信息统计表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BuDeviceStatistics buDeviceStatistics,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BuDeviceStatistics> queryWrapper = QueryGenerator.initQueryWrapper(buDeviceStatistics, req.getParameterMap());
		if (buDeviceStatistics.getYear() != null){
			queryWrapper.eq("year(open_time)",buDeviceStatistics.getYear());
		}
		if (buDeviceStatistics.getMonth() != null){
			queryWrapper.eq("month(open_time)",buDeviceStatistics.getMonth());
		}
		if (buDeviceStatistics.getDay() != null){
			queryWrapper.eq("day(open_time)",buDeviceStatistics.getDay());
		}
		Page<BuDeviceStatistics> page = new Page<BuDeviceStatistics>(pageNo, pageSize);
		IPage<BuDeviceStatistics> pageList = buDeviceStatisticsService.page(page, queryWrapper);
		return Result.OK(pageList);
	}


	 /**
	  * 第一次进页面，展示全设备当月运行状况分析柱形图（按天）
	  */
	 @GetMapping(value = "/getAllDeviceOperation")
	 public Result<?> getAllDeviceOperation(@RequestParam(name="selectMonth", required = true) String selectMonth){
		 JSONObject obj = new JSONObject();
		 int year = 0;String month = "0";
		 if (selectMonth == null || selectMonth.equals("")){
			 Calendar calendar = Calendar.getInstance();
			 year = calendar.get(Calendar.YEAR);
			 month = String.valueOf(calendar.get(Calendar.MONTH)+1);
		 }else {
			 String[] yearMonth = selectMonth.split("-");
			 year = Integer.parseInt(yearMonth[0]);
			 month = yearMonth[1];
		 }
		 List<Integer> x = new ArrayList<>();
		 List<String> y = new ArrayList<>();
		 DecimalFormat df = new DecimalFormat("0.00");
		 int length = 0;
		 if (month.equals("02")){
			 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
				 length = 29;
			 }else {
				 length = 28;
			 }
		 }else if (month.equals("04") || month.equals("06") || month.equals("09") || month.equals("11")){
			 length = 30;
		 }else {
			 length = 31;
		 }
		 for (int i=1; i<length+1;i++){
			 String sum = buDeviceStatisticsService.getSumTime(year, Integer.parseInt(month),i);
			 x.add(i);
			 if (sum == null){
				 y.add("0");
			 }else {
				 y.add((df.format(Double.valueOf(sum))));
			 }
		 }
		 obj.put("x",x);
		 obj.put("y",y);
		 return Result.OK(obj);
	 }











	/**
	 *   添加
	 *
	 * @param buDeviceStatistics
	 * @return
	 */
	@AutoLog(value = "设备信息统计表-添加")
	@ApiOperation(value="设备信息统计表-添加", notes="设备信息统计表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BuDeviceStatistics buDeviceStatistics) {
		buDeviceStatisticsService.save(buDeviceStatistics);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param buDeviceStatistics
	 * @return
	 */
//	@AutoLog(value = "设备信息统计表-编辑")
//	@ApiOperation(value="设备信息统计表-编辑", notes="设备信息统计表-编辑")
//	@PutMapping(value = "/edit")
//	public Result<?> edit(@RequestBody BuDeviceStatistics buDeviceStatistics) {
//		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		if (user.getId().equals("e9ca23d68d884d4ebb19d07889727dae")) {
//			//数据库中年、月、日赋值
//			Date date = buDeviceStatistics.getOpenTime();
//			String year = String.format("%tY", date);
//			String d = String.format("%td", date);
//			String m = String.format("%tm", date);
//			String month = String.valueOf(Integer.parseInt(m));
//			String day = String.valueOf(Integer.parseInt(d));
//			buDeviceStatistics.setYear(year);
//			buDeviceStatistics.setMonth(month);
//			buDeviceStatistics.setDay(day);
//			//数据库总开机时间、总使用时间、总待机时间赋值
//			long startTime = buDeviceStatistics.getOpenTime().getTime();
//			long endTime = buDeviceStatistics.getCloseTime().getTime();
//			long useTime = buDeviceStatistics.getUseTime().getTime();
//			String totalUseTime = Integer.toString((int) ((endTime - useTime) / 1000));
//			String totalOpenTime = Integer.toString((int) ((endTime - startTime) / 1000));
//			String totalIdleTime = Integer.toString((int) ((useTime - startTime) / 1000));
//			buDeviceStatistics.setTotalOpenTime(totalOpenTime);
//			buDeviceStatistics.setTotalUseTime(totalUseTime);
//			buDeviceStatistics.setTotalIdleTime(totalIdleTime);
//			// 设备能耗表赋值
//			BuDeviceEnergyStatistics buDeviceEnergyStatistics = new BuDeviceEnergyStatistics();
//			BuDevice budevice = buDeviceService.getDeviceById(buDeviceStatistics.getDeviceId());
//			buDeviceEnergyStatistics.setDeviceId(buDeviceStatistics.getDeviceId());
//			buDeviceEnergyStatistics.setDeviceCode(budevice.getDeviceCode());
//			buDeviceEnergyStatistics.setOpenTime(buDeviceStatistics.getOpenTime());
//			buDeviceEnergyStatistics.setUsefulTime(totalUseTime);
//			buDeviceEnergyStatistics.setInvalidTime(totalIdleTime);
//			buDeviceEnergyStatisticsService.save(buDeviceEnergyStatistics);
//			buDeviceStatisticsService.updateById(buDeviceStatistics);
//			return Result.OK("编辑成功!");
//		}else {
//			return Result.error("只有管理员才能编辑！");
//		}
//	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备信息统计表-通过id删除")
	@ApiOperation(value="设备信息统计表-通过id删除", notes="设备信息统计表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		buDeviceStatisticsService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "设备信息统计表-批量删除")
	@ApiOperation(value="设备信息统计表-批量删除", notes="设备信息统计表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.buDeviceStatisticsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}



	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备信息统计表-通过id查询")
	@ApiOperation(value="设备信息统计表-通过id查询", notes="设备信息统计表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BuDeviceStatistics buDeviceStatistics = buDeviceStatisticsService.getById(id);
		if(buDeviceStatistics==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buDeviceStatistics);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param buDeviceStatistics
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuDeviceStatistics buDeviceStatistics) {
        return super.exportXls(request, buDeviceStatistics, BuDeviceStatistics.class, "设备信息统计表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BuDeviceStatistics.class);
    }

}
