package com.zcloud.controller.statistics;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.statistics.ListStatisticsService;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.ObjectExcelView;
import com.zcloud.util.Tools;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 说明：清单统计记录
 * 作者：luoxiaobao
 * 时间：2021-01-27
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/liststatistics")
public class ListStatisticsController extends BaseController {

	@Autowired
	private ListStatisticsService liststatisticsService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private DepartmentService departmentService;

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("liststatisticsday:add")
	@ResponseBody
	public Object add() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("LISTSTATISTICS_ID", this.get32UUID());	//主键
		pd.put("STARTTIME", DateUtil.date2Str(new Date()));	//开始时间
		pd.put("ENDTIME", DateUtil.date2Str(new Date()));	//结束时间
		liststatisticsService.save(pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("liststatisticsday:del")
	@ResponseBody
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		liststatisticsService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("liststatisticsday:edit")
	@ResponseBody
	public Object edit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		liststatisticsService.edit(pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	// @RequiresPermissions("liststatisticsday:list")
	@ResponseBody
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		page.setPd(pd);
		List<PageData>	varList = liststatisticsService.list(page);	//列出ListStatisticsDay列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	// @RequiresPermissions("liststatisticsday:edit")
	@ResponseBody
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = liststatisticsService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	 /**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("liststatisticsday:del")
	@ResponseBody
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			liststatisticsService.deleteAll(ArrayDATA_IDS);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel() throws Exception{
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		Map<String,Object> dataMap = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("开始时间");	//1
		titles.add("结束时间");	//2
		titles.add("待检查项数");	//3
		dataMap.put("titles", titles);
		List<PageData> varOList = liststatisticsService.listAll(pd);
		List<PageData> varList = new ArrayList<PageData>();
		for(int i=0;i<varOList.size();i++){
			PageData vpd = new PageData();
			vpd.put("var1", varOList.get(i).getString("STARTTIME"));	    //1
			vpd.put("var2", varOList.get(i).getString("ENDTIME"));	    //2
			vpd.put("var3", varOList.get(i).get("NOTEXAMINEDNUM").toString());	//3
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}


	@RequestMapping(value="/getTimeAstrict")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "统计分析",instructionsOperate = "员工日常检测情况",instructionsType = "获取时间")
	public Object getTimeAstrict() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
		pd = liststatisticsService.getTimeAstrict(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**checkSituation
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/checkSituation")
	// @RequiresPermissions("checkSituation:list")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "统计分析",instructionsOperate = "员工使用情况分析",instructionsType = "列表")
	public Object checkSituation() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		PageData npd = new PageData();
		pd = this.getPageData();
		npd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		npd.put("ISMAIN", Jurisdiction.getIS_MAIN());
		npd.put("ISSUPERVISE", Jurisdiction.getISSUPERVISE());
		npd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());

		String TIME = pd.getString("TIME");
		if(Tools.notEmpty(TIME)) {
			npd.put("STARTTIME", TIME);
			npd.put("ENDTIME", TIME);
		}
		String DEPTIDS = pd.getString("DEPTIDS");
		if(Tools.notEmpty(DEPTIDS)) {
			String DEPT_IDS[] = DEPTIDS.split(",");
			npd.put("DEPT_IDS", DEPT_IDS);
		}
		pd.put("USER_ID",Jurisdiction.getUSER_ID());
		PageData cpd = new PageData();
		cpd = usersService.findById(pd);
		npd.put("ISLEADER", cpd.getString("ISLEADER"));
		if(cpd.getString("ISLEADER") != null && cpd.getString("ISLEADER").equals("1")){
			String DEPARTMENT_ID = npd.getString("DEPARTMENT_ID");
			String ids = departmentService.getDEPARTMENT_IDS(DEPARTMENT_ID);
			ids=npd.getString("DEPARTMENT_ID")+","+ids;   //把自己部门插入进去
			if(ids!=null && Tools.notEmpty(ids)&& ids.lastIndexOf(",")>-1) {
				ids = ids.substring(0,ids.lastIndexOf(","));
				npd.put("DEPARTMENT_IDS", ids.split(","));
			}else {
				npd.put("DEPARTMENT_IDS", DEPARTMENT_ID);
			}
		}else {
			if(npd.getString("ISMAIN").equals("0")){
				npd.put("USER_ID",Jurisdiction.getUSER_ID());
			}
		}
		String KEYWORDS = pd.getString("KEYWORDS"); // 关键词检索条件
		if (Tools.notEmpty(KEYWORDS))
			npd.put("KEYWORDS", KEYWORDS.trim());
		npd.put("STATE",pd.getString("STATE"));
		List<PageData> varList = liststatisticsService.checkSituation(npd);	//根据ID读取

		Map<String, PageData> countMap = new HashMap<String, PageData>();//查询负责清单数
		Map<String, String> staMap = new HashMap<String, String>();//查询负责清单数
		List<PageData> stas = liststatisticsService.countListStaByUser(npd);
		if(stas != null && stas.size() > 0) {
			for(PageData sta : stas) {
				staMap.put(sta.get("USER_ID").toString(), sta.get("NUM").toString());
			}
		}
		// 登录人数
		Double loginNum = 0d;
		// 部门待检查清单数
		Double listNoCheckNum = 0d;
		// 部门已检查清单数
		Double listCheckedNum = 0d;

		for(PageData u : varList) {
			if(staMap.containsKey(u.get("USER_ID").toString())) {
				u.put("NOTEXAMINEDNUM", staMap.get(u.get("USER_ID").toString()));
			} else {
				u.put("NOTEXAMINEDNUM", 0);
			}
			if(u.get("ISLOGIN") != null && Tools.notEmpty(u.get("ISLOGIN").toString()) && Integer.parseInt(u.get("ISLOGIN").toString()) > 0) {
				loginNum++;
			}

			DecimalFormat df = new DecimalFormat("#0.00");
			if (Integer.valueOf(u.get("NOTEXAMINEDNUM").toString()) == 0) {
				u.put("PERCENT", df.format(0) + "%");
			} else {
				u.put("PERCENT", df.format(Double.valueOf(u.get("INSPECTEDNUM").toString()) / Double.valueOf(u.get("NOTEXAMINEDNUM").toString()) * 100) + "%");
			}
			listCheckedNum += Double.valueOf(u.get("INSPECTEDNUM").toString());
			listNoCheckNum += Double.valueOf(u.get("NOTEXAMINEDNUM").toString());
		}
		// 部门清单检查率
		Double checkTheRate = 0d;
		if(listNoCheckNum != 0) {
			checkTheRate = listCheckedNum / listNoCheckNum * 100;
		}
		//登录率
		Double achieving = 0d;
		if (varList != null && varList.size() > 0) {
			achieving = loginNum / varList.size() * 100;
		}
		DecimalFormat df = new DecimalFormat("#0.00");
		map.put("loginNum", loginNum);
		map.put("achieving", df.format(achieving));
		map.put("checkTheRate", df.format(checkTheRate));
		map.put("listCheckedNum", listCheckedNum);
		map.put("listNoCheckNum", listNoCheckNum);
		map.put("varList", varList);
		map.put("result", errInfo);
		return map;
	}


}
