package cn.yw.operationcount.alarmcount.action;


import cn.base.aspect.OperateType;
import cn.base.bean.BaseAction;
import cn.base.excel.ExcelCol;
import cn.base.excel.ExportEngine;
import cn.base.pdf.ExportPDF;
import cn.base.util.*;
import cn.yw.operationcount.alarmcount.service.YwalarmcountService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@SuppressWarnings({"all"})
@Component("ywalarmcountAction")
public class YwalarmcountAction extends BaseAction{
	private static final long serialVersionUID = 1L;
	private static Logger iLog = Logger.getLogger(YwalarmcountAction.class);
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private YwalarmcountService service;
	
	/**
	 * 分页  区域设备告警统计
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="listYwalarmcountByPage")
	public void listYwalarmcountByPage(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			int page = Integer.parseInt(Struts2Utils.getParameter("page"));
			int rows = Integer.parseInt(Struts2Utils.getParameter("rows"));
			int start = ( (page == 0 ?  1 : page ) - 1) * rows ;
			map.put("start",start );
			map.put("limit",rows );
			//判断设备类别
			List<Map> list = service.query_Ywmalarmcount(map);
			Integer totalCount = service.count_Ywmalarmcount(map);
			map.clear();
			map.put("total", totalCount);
			map.put("rows", list);
			Struts2Utils.renderJson(map);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwcountlalcollectAction-listYwalarmcountByPage-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	// 首页 设备恢复率统计
	@OperateType(value = LogConstants.LOG_QUERY ,info ="count_HomepageHfl")
	public void count_HomepageHfl(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			String nowTime = DateUtil.getDateTimeStr(new Date());
//			String zStartTime = sdf.format(DateUtil.day(new Date(),-7));    // 最近一周
//			String yStartTime = sdf.format(DateUtil.month(-1));			 // 最近一个月
//			String nStartTime = sdf.format(DateUtil.year(-1));				 // 最近一年
			String type = map.get("type")+"";
			String startTime = sdf.format(DateUtil.day(new Date(),-7));
			if("1".equals(type)){// 最近一个月
				startTime = sdf.format(DateUtil.month(-1));		
			}else if("2".equals(type)){// 最近一年
				startTime = sdf.format(DateUtil.year(-1));
			}
			
			map.put("timeEnd", nowTime);
			
			map.put("timeStart", startTime);
			List<Map> zList = service.query_Ywmalarmcount(map);			
			/*map.put("timeStart", yStartTime);
			List<Map> yList = service.query_Ywmalarmcount(map);
			map.put("timeStart", nStartTime);
			List<Map> nList = service.query_Ywmalarmcount(map);*/
			
			map.clear();
			map.put("zList", zList);
			/*map.put("yList", yList);
			map.put("nList", nList);*/
			
			Struts2Utils.renderJson(map);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwcountlalcollectAction-count_HomepageHfl-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	
	/**
	 * 分页  区域告警设备列表
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="listAlarmAreaByPage")
	public void listAlarmAreaByPage(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			int page = Integer.parseInt(Struts2Utils.getParameter("page"));
			int rows = Integer.parseInt(Struts2Utils.getParameter("rows"));
			int start = ( (page == 0 ?  1 : page ) - 1) * rows ;
			map.put("start",start );
			map.put("limit",rows );
			List<Map> list = service.query_alarmbyArea(map);
			Integer totalCount = service.count_alarmbyArea(map);
			map.clear();
			map.put("total", totalCount);
			map.put("rows", list);
			Struts2Utils.renderJson(map);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwcountlalcollectAction-listAlarmAreaByPage-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	// 柱状图
	@OperateType(value = LogConstants.LOG_QUERY ,info ="count_showBar")
	public void count_showBar(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			List<Map> list = service.query_Ywmalarmcount(map);			
			Struts2Utils.renderJson(list);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwcountlalcollectAction-count_showBar-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	@OperateType(value = LogConstants.LOG_QUERY ,info ="count_Ywmalarmcount")
	public void count_Ywmalarmcount(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			int total = service.count_Ywmalarmcount(map);			
			Struts2Utils.renderJson(total);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwcountlalcollectAction-count_Ywmalarmcount-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	/**
	 * 导出Excel
	 */
	@OperateType(value = LogConstants.LOG_EXPORT ,info ="exp_Ywalarmcount")
	public void exp_Ywalarmcount(){
		try {
			Map map = Struts2Utils.getRequestParameterMap();
			map.put("start",0 );
			map.put("limit",5000);
			List<Map> sList = service.query_Ywmalarmcount(map);	
			Map footMap = new HashMap();
			String[] footArr = {"zs","zhf","hfl"};
			if(RHUtil.isNotEmpty(sList)) {
				Integer zs = 0;
				Integer zhf = 0;
				String zhfl = "0";
				for(Map smap : sList) {
					String zcount = (String) smap.get("zcount");
					String hfcount = (String) smap.get("hfcount");
					String hfl = "0";
					if("0".equals(hfcount)) {
						smap.put("hfl", hfl);
					}else {
						hfl = division(Integer.parseInt(hfcount),Integer.parseInt(zcount));
						smap.put("hfl", hfl);
					}
					
					zs = zs + Integer.parseInt(zcount);
					zhf = zhf + Integer.parseInt(hfcount);							
				}
				if(zhf!=0) {
					zhfl = division(zhf,zs);
				}					
				footMap.put("xzmc", "总计");
				footMap.put("zcount", zs);
				footMap.put("hfcount", zhf);
				footMap.put("hfl", zhfl);
				sList.add(footMap);
			}
			String[] zdbm = {"xzmc", "zcount","hfcount","hfl"};                          
			String[] zdmc = {"行政区划", "告警总数","已恢复数","恢复率"};
			int excelNum = zdbm.length;
			ExcelCol[] cells = new ExcelCol[excelNum];
			for(int i=0;i<excelNum;i++){
				cells[i] = new ExcelCol();
				cells[i].setColKey(zdbm[i]);
				cells[i].setColName(zdmc[i]);
			}		
			SimpleDateFormat formart = new SimpleDateFormat("yyyy-MM-dd");   
        	String dateTime=formart.format(new Date()); 
			Map params = new HashMap();
			params.put("fileName", "区域设备告警统计-"+dateTime);
			params.put("sheetName", "区域设备告警统计信息");
			params.put("header", "区域设备告警统计(制表时间："+dateTime+")");
			new ExportEngine().exportCommData(params, cells, (ArrayList)sList, Struts2Utils.getResponse());
		//	exportCommData(params, cells, (ArrayList)sList,footMap,footArr, Struts2Utils.getResponse());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwalarmcountAction-exp_Ywalarmcount-error:" +e);
			
		}
	}
	/**
	 * 导出pdf
	 */
	@OperateType(value = LogConstants.LOG_EXPORT ,info ="expPDF_Ywalarmcount")
	public void expPDF_Ywalarmcount(){
		try {
			Map map = Struts2Utils.getRequestParameterMap();
			map.put("start",0 );
			map.put("limit",5000);
			List<Map> sList = service.query_Ywmalarmcount(map);	
					
			//表头
			String[] header = {"行政区划", "告警总数","已恢复数","恢复率"};
			//内容
			String[][] expArr = null;
			if(RHUtil.isNotEmpty(sList)) {
				expArr = new String[sList.size()+1][header.length];
				Integer zs = 0;
				Integer zhf = 0;
				String zhfl = "0";
				int index = 0;
				for(Map smap : sList) {
					
					String zcount = (String) smap.get("zcount");
					String hfcount = (String) smap.get("hfcount");
					String hfl = "0";
					if("0".equals(hfcount)) {
						smap.put("hfl", hfl);
					}else {
						hfl = division(Integer.parseInt(hfcount),Integer.parseInt(zcount));
						smap.put("hfl", hfl);
					}
					expArr[index][0] = StringUtil.transEmpty(smap.get("xzmc")+"");
					expArr[index][1] = zcount;
					expArr[index][2] = hfcount;
					expArr[index][3] = hfl;
					index++;
					zs = zs + Integer.parseInt(zcount);
					zhf = zhf + Integer.parseInt(hfcount);							
				}
				if(zhf!=0) {
					zhfl = division(zhf,zs);
				}
				expArr[index][0] = "总计";
				expArr[index][1] = zs+"";
				expArr[index][2] = zhf+"";
				expArr[index][3] = zhfl;
			}
			SimpleDateFormat formart = new SimpleDateFormat("yyyy-MM-dd");   
			String dateTime=formart.format(new Date()); 
			Map params = new HashMap();
			params.put("fileName", "区域设备告警统计-"+dateTime);
			params.put("sheetName", "区域设备告警统计信息");
			params.put("header", "区域设备告警统计(制表时间："+DateUtil.currentDateTime()+")");
//			new ExportEngine().exportCommData(params, cells, (ArrayList)sList, Struts2Utils.getResponse());
			new ExportPDF().exportCommPDF(params,header,new ArrayList(),0, expArr, Struts2Utils.getResponse());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwalarmcountAction-expPDF_Ywalarmcount-error:" +e);
			
		}
	}
	
	/**
     * 转成百分数
     * 当前数除以总数
     * @param  num1 ,num2  num1/num2
     * @return  rate  保留2位小数的
     */
    public static String  division(int num1,int num2){
        String rate="0.00%";
        //定义格式化起始位数
        String format="0.00";
        if(num2 != 0 && num1 != 0){
            DecimalFormat dec = new DecimalFormat(format);
            rate =  dec.format((double) num1 / num2*100)+"%";
            while(true){
                if(rate.equals(format+"%")){
                    format=format+"0";
                    DecimalFormat dec1 = new DecimalFormat(format);
                    rate =  dec1.format((double) num1 / num2*100)+"%";
                }else {
                    break;
                }
            }
        }else if(num1 != 0 && num2 == 0){
            rate = "100%";
        }
        return rate;
    }

    public String getDateWeek() {  
        Calendar cal = Calendar.getInstance();  
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);  
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);  
        return  sdf.format(cal.getTime());  
    } 
    // 获取 月份第一天的日期     参数 m=0 代表本月   m=1代表下月  m=-1 代表上个月
    public String getMonthdate(int m){
    	Calendar calendar=Calendar.getInstance();
    	calendar.add(Calendar.MONTH, m);
    	calendar.set(Calendar.DAY_OF_MONTH, 1);
    	return sdf.format(calendar.getTime());
    }
    public static void main(String[] args) {
    	YwalarmcountAction wm = new YwalarmcountAction();
		System.out.println(wm.getDateWeek());
		System.out.println(wm.getMonthdate(0));
		System.out.println(DateUtil.getDateTimeStr(new Date()));
		System.out.println(sdf.format(DateUtil.day(new Date(),-7)));
		
		String[][] strs = new String[10][2];
		for(int i=0; i<10;i++){
			strs[i][0] = "我"+i;
			strs[i][1] = "你"+i;
		}
		for(int i=0;i<strs.length;i++){
			System.out.println(strs[i][0]);
			System.out.println(strs[i][1]);
		}
		
	}
}
