package com.zcloud.controller.scheduling;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.scheduling.ShiftWorkPeriodService;
import com.zcloud.service.scheduling.ShiftWorkRulesService;
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.util.*;

/**
 * 说明：倒班规则
 * 作者：luoxiaobao
 * 时间：2021-12-07
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/shiftworkrules")
public class ShiftWorkRulesController extends BaseController {

	@Autowired
	private ShiftWorkRulesService shiftworkrulesService;
	@Autowired
	private ShiftWorkPeriodService shiftWorkPeriodService;

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("shiftworkrules:add")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "排班管理",instructionsOperate = "排班管理",instructionsType = "新增")
	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("SHIFTWORKRULES_ID", this.get32UUID());	//主键
		pd.put("CREATOR", Jurisdiction.getUSER_ID());	//添加人
		pd.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
		pd.put("OPERATOR", Jurisdiction.getUSER_ID());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID()); // 企业id
		pd.put("ISDELETE", "0");	//是否删除 1-是  0-否
		if (Tools.notEmpty(pd.getString("ISCUSTOM")) && "1".equals(pd.getString("ISCUSTOM"))
				&& pd.get("periodList") != null && !pd.get("periodList").equals("")) {
			List<JSONObject> periodList = (List<JSONObject>) JSON.parse(pd.get("periodList").toString());
			for (int i = 0; i < periodList.size(); i++) {
				PageData period = new PageData();
				period.put("SHIFTWORKPERIOD_ID",this.get32UUID());
				period.put("ONDAY",periodList.get(i).get("ONDAY"));
				period.put("OFFDAY",periodList.get(i).get("OFFDAY"));
				period.put("CREATOR", Jurisdiction.getUSER_ID());	//添加人
				period.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
				period.put("OPERATOR", Jurisdiction.getUSER_ID());	//修改人
				period.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
				period.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID()); // 企业id
				period.put("ISDELETE", "0");	//是否删除 1-是  0-否
				period.put("SHIFTWORKRULES_ID", pd.get("SHIFTWORKRULES_ID"));
				period.put("SORT", i+1);
				period.put("ISEND", i < periodList.size()-1 ? 0 : 1);
				shiftWorkPeriodService.save(period);
			}
		}
		shiftworkrulesService.save(pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteOne")
	// @RequiresPermissions("shiftworkrules:del")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "排班管理",instructionsOperate = "排班管理",instructionsType = "删除")
	public Object deleteOne() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SHIFTDUTYONE", pd.get("SHIFTWORKRULES_ID"));
		int count = shiftworkrulesService.isUseOne(pd);
		if(count == '0') {
			pd.put("OPERATOR", Jurisdiction.getUSER_ID());	//修改人
			pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
			shiftWorkPeriodService.deleteByUpRules(pd);
			shiftworkrulesService.delete(pd);
			pd.put("PARENTID", pd.get("SHIFTWORKRULES_ID"));
			shiftworkrulesService.deleteByPar(pd);

			map.put("type", "success");				//返回结果
		} else {
			map.put("type", "error");//返回结果

		}
		map.put("result", errInfo);				//返回结果
		return map;
	}



	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteTwo")
	// @RequiresPermissions("shiftworkrules:del")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "排班管理",instructionsOperate = "排班管理",instructionsType = "删除")
	public Object deleteTwo() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SHIFTDUTYTWO", pd.get("SHIFTWORKRULES_ID"));
		int count = shiftworkrulesService.isUseTwo(pd);
		if(count == 0) {
			pd.put("OPERATOR", Jurisdiction.getUSER_ID());	//修改人
			pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
			shiftWorkPeriodService.deleteByRules(pd);
			shiftworkrulesService.delete(pd);
			map.put("type", "success");				//返回结果
		} else {
			map.put("type", "error");				//返回结果
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**验证排班周期是否使用中
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/isUseTwo")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "排班管理",instructionsOperate = "排班管理",instructionsType = "验证排班周期是否使用中")
	public Object isUseTwo() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SHIFTDUTYTWO", pd.get("SHIFTWORKRULES_ID"));
		int count = shiftworkrulesService.isUseTwo(pd);
		if(count == 0) {
			map.put("type", "success");				//返回结果
		} else {
			map.put("type", "error");				//返回结果
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("shiftworkrules:edit")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "排班管理",instructionsOperate = "排班管理",instructionsType = "修改")
	public Object edit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUSER_ID());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		shiftworkrulesService.edit(pd);
		if (Tools.notEmpty(pd.getString("ISCUSTOM")) && "1".equals(pd.getString("ISCUSTOM"))
				&& pd.get("periodList") != null && !pd.get("periodList").equals("")) {
			List<JSONObject> periodList = (List<JSONObject>) JSON.parse(pd.get("periodList").toString());
			shiftWorkPeriodService.deleteByRules(pd);
			for (int i = 0; i < periodList.size(); i++) {
				PageData period = new PageData();
				period.put("SHIFTWORKPERIOD_ID",this.get32UUID());
				period.put("ONDAY",periodList.get(i).get("ONDAY"));
				period.put("OFFDAY",periodList.get(i).get("OFFDAY"));
				period.put("CREATOR", Jurisdiction.getUSER_ID());	//添加人
				period.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
				period.put("OPERATOR", Jurisdiction.getUSER_ID());	//修改人
				period.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
				period.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID()); // 企业id
				period.put("ISDELETE", "0");	//是否删除 1-是  0-否
				period.put("SHIFTWORKRULES_ID", pd.get("SHIFTWORKRULES_ID"));
				period.put("SORT", i+1);
				period.put("ISEND", i < periodList.size()-1 ? 0 : 1);
				shiftWorkPeriodService.save(period);
			}
		}
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	// @RequiresPermissions("shiftworkrules:list")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "排班管理",instructionsOperate = "排班管理",instructionsType = "列表")
	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();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID()); // 企业id
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		page.setPd(pd);
		List<PageData>	varList = shiftworkrulesService.list(page);	//列出ShiftWorkRules列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	// @RequiresPermissions("shiftworkrules:edit")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "排班管理",instructionsOperate = "排班管理",instructionsType = "去修改页面获取数据")
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = shiftworkrulesService.findById(pd);	//根据ID读取
		List<PageData> periodList = shiftWorkPeriodService.listAll(pd);
		map.put("pd", pd);
		map.put("periodList", periodList);
		map.put("result", errInfo);
		return map;
	}

	/**获取倒班规则集合
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/listAll")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "用户管理",instructionsType = "获取倒班规则集合")
	public Object listAll() 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()); // 企业
		List<PageData> varList = shiftworkrulesService.listAll(pd);	//根据ID读取
		map.put("varList", varList);
		map.put("result", errInfo);
		return map;
	}

	 /**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("shiftworkrules: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(",");
			shiftworkrulesService.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
		titles.add("连续上班天数（周期二）");	//4
		titles.add("连续休班天数（周期二）");	//5
		titles.add("连续上班天数（周期三）");	//6
		titles.add("连续休班天数（周期三）");	//7
		titles.add("企业ID");	//8
		titles.add("添加人");	//9
		titles.add("添加时间");	//10
		titles.add("修改人");	//11
		titles.add("修改时间");	//12
		titles.add("是否删除 1-是  0-否");	//13
		dataMap.put("titles", titles);
		List<PageData> varOList = shiftworkrulesService.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("RULESBIANMA"));	    //1
			vpd.put("var2", varOList.get(i).getString("ONDAYONE"));	    //2
			vpd.put("var3", varOList.get(i).getString("OFFDAYONE"));	    //3
			vpd.put("var4", varOList.get(i).getString("ONDAYTWO"));	    //4
			vpd.put("var5", varOList.get(i).getString("OFFDAYTWO"));	    //5
			vpd.put("var6", varOList.get(i).getString("ONDAYTHREE"));	    //6
			vpd.put("var7", varOList.get(i).getString("OFFDAYTHREE"));	    //7
			vpd.put("var8", varOList.get(i).getString("CORPINFO_ID"));	    //8
			vpd.put("var9", varOList.get(i).getString("CREATOR"));	    //9
			vpd.put("var10", varOList.get(i).getString("CREATTIME"));	    //10
			vpd.put("var11", varOList.get(i).getString("OPERATOR"));	    //11
			vpd.put("var12", varOList.get(i).getString("OPERATTIME"));	    //12
			vpd.put("var13", varOList.get(i).getString("ISDELETE"));	    //13
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}

}
