package org.stm.page.controller;

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.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.stm.metric.entity.MetricMonitorSet;
import org.stm.metric.entity.MetricReport;
import org.stm.metric.service.IMetricMonitorSetService;
import org.stm.metric.service.IMetricReportService;
import org.stm.page.entity.PageMonitorchart;
import org.stm.page.service.IPageMonitorchartService;
import org.stm.rectify.approve.entity.StRectifyApprove;
import org.stm.rectify.approve.service.IStRectifyApproveService;
import org.stm.rectify.assin.entity.StProblemTaskAssin;
import org.stm.rectify.assin.service.IStProblemTaskAssinService;
import org.stm.rectify.exec.entity.StRectifyExec;
import org.stm.rectify.exec.service.IStRectifyExecService;
import org.stm.rectify.plan.entity.StRectifyPlan;
import org.stm.rectify.plan.service.IStRectifyPlanService;

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

/**
 * @Description: 趋势图表设置
 * @Author: jeecg-boot
 * @Date:   2024-01-11
 * @Version: V1.0
 */
@Api(tags="趋势图表设置")
@RestController
@RequestMapping("/page/pageMonitorchart")
@Slf4j
public class PageMonitorchartController extends JeecgController<PageMonitorchart, IPageMonitorchartService> {
	@Autowired
	private IPageMonitorchartService pageMonitorchartService;
	 @Autowired
	 private IMetricMonitorSetService metricMonitorSetService;
	 @Autowired
	 private IMetricReportService metricReportService;
	@Autowired
	private IStProblemTaskAssinService stProblemTaskAssinService;
	@Autowired
	private IStRectifyExecService stRectifyExecService;
	@Autowired
	private IStRectifyApproveService stRectifyApproveService;
	@Autowired
	private IStRectifyPlanService iStRectifyPlanService;

	/**
	 * 分页列表查询
	 *
	 * @param pageMonitorchart
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "趋势图表设置-分页列表查询")
	@ApiOperation(value="趋势图表设置-分页列表查询", notes="趋势图表设置-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<PageMonitorchart>> queryPageList(PageMonitorchart pageMonitorchart,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PageMonitorchart> queryWrapper = new QueryWrapper();//QueryGenerator.initQueryWrapper(pageMonitorchart, req.getParameterMap());
		queryWrapper.orderByAsc("create_time");
		Page<PageMonitorchart> page = new Page<PageMonitorchart>(pageNo, pageSize);
		IPage<PageMonitorchart> pageList = pageMonitorchartService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param pageMonitorchart
	 * @return
	 */
	@AutoLog(value = "趋势图表设置-添加")
	@ApiOperation(value="趋势图表设置-添加", notes="趋势图表设置-添加")
	//@RequiresPermissions("page:page_monitorchart:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody PageMonitorchart pageMonitorchart) {
		String mtrcNo = pageMonitorchart.getMtrcNo();
		QueryWrapper<MetricMonitorSet> queryWrapper = new QueryWrapper();
		queryWrapper.eq("mtrc_no",mtrcNo);
		MetricMonitorSet mms = metricMonitorSetService.getOne(queryWrapper);
		pageMonitorchart.setMtrcName(mms.getMtrcName());
		pageMonitorchartService.save(pageMonitorchart);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param pageMonitorchart
	 * @return
	 */
	@AutoLog(value = "趋势图表设置-编辑")
	@ApiOperation(value="趋势图表设置-编辑", notes="趋势图表设置-编辑")
	//@RequiresPermissions("page:page_monitorchart:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody PageMonitorchart pageMonitorchart) {
		pageMonitorchartService.updateById(pageMonitorchart);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "趋势图表设置-通过id删除")
	@ApiOperation(value="趋势图表设置-通过id删除", notes="趋势图表设置-通过id删除")
	//@RequiresPermissions("page:page_monitorchart:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		pageMonitorchartService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "趋势图表设置-批量删除")
	@ApiOperation(value="趋势图表设置-批量删除", notes="趋势图表设置-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.pageMonitorchartService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	@ApiOperation(value="趋势图表设置-通过id查询", notes="趋势图表设置-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<PageMonitorchart> queryById(@RequestParam(name="id",required=true) String id) {
		PageMonitorchart pageMonitorchart = pageMonitorchartService.getById(id);
		if(pageMonitorchart==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(pageMonitorchart);
	}

    @RequiresPermissions("page:page_monitorchart:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PageMonitorchart pageMonitorchart) {
        return super.exportXls(request, pageMonitorchart, PageMonitorchart.class, "趋势图表设置");
    }

	 @RequestMapping(value = "/getPageChartData")
	 public Result<?> getPageCharData(HttpServletRequest request, HttpServletResponse response) {
		 List<PageMonitorchart> listData =  pageMonitorchartService.list();
		 return Result.OK(listData);
	 }

	 @PostMapping(value = "/getMtricDataByMtrcNo")
	 public Result<?> getMtricData(@RequestBody PageMonitorchart mc) {
		 QueryWrapper<MetricReport> queryWrapper = new QueryWrapper();
		 queryWrapper.eq("mtrc_no",mc.getMtrcNo());
		 queryWrapper.ge("fill_time",mc.getYear());
		 queryWrapper.orderByAsc("fill_time");
		 List<MetricReport> metrcList  =  metricReportService.list(queryWrapper);
		 Map<String,Object> retMap = new HashMap<>();

		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		 List<Float> retList = new ArrayList<>();
		 List<Object> retWarnList = new ArrayList<>();
		 List<Object> retIntvList = new ArrayList<>();
		 List<Object> retTolList = new ArrayList<>();
		 List<String> category = new ArrayList<>();

		 MetricMonitorSet metrcSet = getMetricMonitorSet(mc.getMtrcNo());
		 Float warnVal = metrcSet.getWarnVal();
		 Float intvVal = metrcSet.getIntvVal();

		 if(warnVal!=null){
			 for(MetricReport mr:metrcList){
				 retWarnList.add(warnVal);
			 }
			 retMap.put("warn",retWarnList);
		 }
		 if(intvVal!=null){
			 for(MetricReport mr:metrcList){
				 retIntvList.add(intvVal);
			 }
			 retMap.put("intv",retIntvList);
		 }
		 for(MetricReport mr:metrcList){
			 if(mr.getFillVals()==null)continue;
			 category.add(sdf.format(mr.getFillTime()));
			 retList.add(Float.parseFloat(mr.getFillVals()));
			 retTolList.add(metrcSet.getTolVal());
		 }
		 retMap.put("mtrc",retList);
		 retMap.put("tol",retTolList);
		 retMap.put("category",category);
		 retMap.put("unit",metrcSet.getUnit());

		 if(retList.size()>0) {
			 float max = Collections.max(retList);
			 float min = Collections.min(retList);
			 List<Float> tmpList = new ArrayList<>();
			 tmpList.add(max);
			 tmpList.add(min);
			 if(warnVal!=null) {
				 tmpList.add(warnVal);
			 }
			 if(intvVal!=null) {
				 tmpList.add(intvVal);
			 }
			 max = Collections.max(tmpList);
			 min = Collections.min(tmpList);
			 retMap.put("min",min);
			 retMap.put("max",max);
		 }
		 retMap.put("interval",metrcSet.getUnit());
		 return Result.OK(retMap);
	 }

	@RequestMapping(value = "/metricRiskLevelSta")
	public Result<?> metricRiskLevelSta(HttpServletResponse response) {
		List<Map<String,Object>> listData =  pageMonitorchartService.metricRiskLevelSta();
		return Result.OK(listData);
	}

	@RequestMapping(value = "/problemStat")
	public Result<?> problemStat(HttpServletResponse response) {

		//@ApiModelProperty(value = "审核标志;0 未开始 1 待审核、2 已完成、3 已驳回")

		//问题总数
		long total =  stProblemTaskAssinService.count();
		//接收即确认的问题数
		QueryWrapper<StProblemTaskAssin> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("receive_status","1").or().eq("assin_status","0").or().isNull("receive_status");
		//未分配的
		long noAssignNm =  stProblemTaskAssinService.count(queryWrapper);  //已经分配,但未接收

		QueryWrapper<StRectifyApprove> queryApproveWrapper = new QueryWrapper<>();
		queryApproveWrapper.eq("approve_flag","3");
		long finishNm =  stRectifyApproveService.count(queryApproveWrapper);

		long execNm = stRectifyExecService.count();

		QueryWrapper<StRectifyPlan> queryPlanWrapper = new QueryWrapper<>();
		queryPlanWrapper.ne("edit_flag","1");
		long planNm = iStRectifyPlanService.count(queryPlanWrapper);


//		List<StRectifyPlan> listAllPlan = iStRectifyPlanService.list(queryPlanWrapper);
//		int noPlanNm = 0,planNm =0;
//		for(int i=0;i<listAllPlan.size();i++){
//			StRectifyPlan plan = listAllPlan.get(i);
//			if(plan.getEditFlag().equals("0")) {
//				noPlanNm++;
//			} else {
//				planNm++;
//			}
//		}

		Map<String,Object> retMap = new LinkedHashMap<>();
		retMap.put("total",total);
		retMap.put("execNm",(execNm-finishNm));
		retMap.put("finishNm",finishNm);
		retMap.put("planNm",planNm);
		retMap.put("noAssignNm",noAssignNm);

		return Result.OK(retMap);
	}

	private MetricMonitorSet getMetricMonitorSet(String mtricNo) {
		QueryWrapper<MetricMonitorSet> queryWrapper = new QueryWrapper();
		queryWrapper.eq("mtrc_no",mtricNo);
		MetricMonitorSet metrcSet =metricMonitorSetService.getOne(queryWrapper);
		return metrcSet;
	}

	@RequestMapping(value = "/getPageStatProblemLevel")
	public  Result<?> getPageStatProblemLevel() {
		List<Map<String,Object>> list = stProblemTaskAssinService.statProblemLevel();
		return Result.ok(list);
	}

}
