package com.zcloud.controller.scheduling;

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.system.UsersService;
import com.zcloud.util.DateUtil;
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.SimpleDateFormat;
import java.util.*;

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

	@Autowired
	private ShiftWorkPeriodService shiftworkperiodService;
	@Autowired
	private UsersService usersService;

	/**
	 * 新增
	 *StatisticsController
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/add")
	// @RequiresPermissions("shiftworkperiod: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("SHIFTWORKPERIOD_ID", this.get32UUID()); // 主键
		pd.put("CREATOR", ""); // 添加人
		pd.put("CREATTIME", DateUtil.date2Str(new Date())); // 添加时间
		pd.put("OPERATOR", ""); // 修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date())); // 修改时间
		pd.put("ISDELETE", ""); // 是否删除 1-是 0-否
		shiftworkperiodService.save(pd);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 删除
	 *
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete")
	// @RequiresPermissions("shiftworkperiod: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();
		shiftworkperiodService.delete(pd);
		map.put("result", errInfo); // 返回结果
		return map;
	}

	/**
	 * 修改
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/edit")
	// @RequiresPermissions("shiftworkperiod: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();
		shiftworkperiodService.edit(pd);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 列表
	 *
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	// @RequiresPermissions("shiftworkperiod: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 = shiftworkperiodService.list(page); // 列出ShiftWorkPeriod列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 获取排版日历
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/getWorkDate")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "用户管理",instructionsType = "获取排班日历")
	public Object getWorkDate() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		int duration = 1;	// 工作状态持续时间（天）
		int workstatus = 1;	// 工作状态 1-上班 2-休班
		int workperiod = 1;	// 当前工作周期数
		if(Tools.notEmpty(pd.getString("DURATION"))
				&& Tools.notEmpty(pd.getString("WORKSTATUS"))
				&& Tools.notEmpty(pd.getString("WORKPERIOD"))) {
			duration = Integer.valueOf(pd.getString("DURATION"));
			workstatus = Integer.valueOf(pd.getString("WORKSTATUS"));
			workperiod = Integer.valueOf(pd.getString("WORKPERIOD"));
		}
		List<PageData> varList = new ArrayList<PageData>();
		if(Tools.notEmpty(pd.getString("USER_ID"))) {	// 编辑时，获取当前用户处于工作周期中的哪天
			PageData user = usersService.findById(pd);

		}
		if (Tools.notEmpty(pd.getString("MONTHS"))) {
			int months = Integer.valueOf(pd.getString("MONTHS"));
			List<String> dateList = DateUtil.getDayListOfMonth(months);	// 获取目标月所有日期
			if(Tools.notEmpty(pd.getString("SHIFTWORKRULES_ID"))) {	// 指定规则排班情况
				List<PageData> perList = shiftworkperiodService.listAll(pd);
				if(perList != null && perList.size() > 0) {	// 规则有自定义周期
					int daySum = 0;	// 所有周期一共有多少天
					int userDays = -1;	// 用户当前处于周期中的第几天（因duration最小为1，所以此处初始化为-1）
					for (int i = 0; i < perList.size(); i++) {
						if (Integer.valueOf(perList.get(i).getString("SORT")) == workperiod) {
							userDays += duration;
							if (workstatus == 2) {
								userDays += Integer.valueOf(perList.get(i).getString("ONDAY"));
							}
							userDays += daySum;
						}
						daySum += Integer.valueOf(perList.get(i).getString("ONDAY"));
						daySum += Integer.valueOf(perList.get(i).getString("OFFDAY"));
					}

					SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
					String todayStr = sdfDay.format(DateUtil.getDateBefore(new Date(), userDays));	// 第一个周期的第一天
					for (String date : dateList) {
						PageData d = new PageData();
						d.put("DATE", date);
						int day = DateUtil.daysBetween(todayStr, date);
						if (day < 0) { // 今天之前
							int days = Math.abs(day) % daySum; // 取余，算出此日期是一个周期内的第几天
							if(days == 0) {// 余数为0，说明此日期是一个周期中的最后一天
								days = daySum;
							}
							int total = 0;
							for (int i = perList.size() - 1; i >= 0; i--) {
								total += Integer.valueOf(perList.get(i).getString("OFFDAY"));
								if (days <= total) {
									d.put("STATE", "2");
									break;
								}
								total += Integer.valueOf(perList.get(i).getString("ONDAY"));
								if (days <= total) {
									d.put("STATE", "1");
									break;
								}
							}
						} else if (day == 0) { // 今天
							d.put("STATE", "1");
						} else if (day > 0) {
							int days = day % daySum;
							int total = -1;
							for (int i = 0; i < perList.size(); i++) {
								total += Integer.valueOf(perList.get(i).getString("ONDAY"));
								if (days <= total) {
									d.put("STATE", "1");
									break;
								}
								total += Integer.valueOf(perList.get(i).getString("OFFDAY"));
								if (days <= total) {
									d.put("STATE", "2");
									break;
								}
							}
						}
						varList.add(d);
					}

				} else {	// 无自定义周期，所有都是上班
					for (String date : dateList) {
						PageData d = new PageData();
						d.put("DATE", date);
						d.put("STATE", "1");
						varList.add(d);
					}
				}
			} else {	// 无指定规则，所有都是上班
				for (String date : dateList) {
					PageData d = new PageData();
					d.put("DATE", date);
					d.put("STATE", "1");
					varList.add(d);
				}
			}

			map.put("varList", varList);
		}
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 去修改页面获取数据
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/goEdit")
	// @RequiresPermissions("shiftworkperiod: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 = shiftworkperiodService.findById(pd); // 根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}


	/**
	 * 去修改页面获取数据
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/listPeriods")
	@ResponseBody
	public Object listPeriods() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		List<PageData> periodList = shiftworkperiodService.listAll(pd); // 根据ID读取
		List<PageData> varList = new ArrayList<PageData>();
		if(periodList != null && periodList.size() > 0) {
			int num = 0;
			for(int i = 0; i < periodList.size(); i++) {
				int onday = Integer.valueOf(periodList.get(i).get("ONDAY").toString());
				int offday = Integer.valueOf(periodList.get(i).get("OFFDAY").toString());
				for(int m = 1; m <= onday; m++) {
					PageData p = new PageData();
					PageData period = new PageData();
					period.put("DURATION", String.valueOf(m));
					period.put("WORKSTATUS", "1");
					period.put("WORKPERIOD", periodList.get(i).get("SORT"));
					if(num != 0 && num%7 == 0) {
						p.put("isBr", "true");
					}
					num++;
					p.put("period", period);
					p.put("periodStr", period.getString("DURATION")+','+period.getString("WORKSTATUS")+','+period.getString("WORKPERIOD"));
					varList.add(p);
				}
				for(int n = 1; n <= offday; n++) {
					PageData p = new PageData();
					PageData period = new PageData();
					period.put("DURATION", String.valueOf(n));
					period.put("WORKSTATUS", "2");
					period.put("WORKPERIOD", periodList.get(i).get("SORT"));
					if(num != 0 && num%7 == 0) {
						p.put("isBr", "true");
					}
					num++;
					p.put("period", period);
					p.put("periodStr", period.getString("DURATION")+','+period.getString("WORKSTATUS")+','+period.getString("WORKPERIOD"));
					varList.add(p);
				}
			}
		} else {
			PageData p = new PageData();
			PageData period = new PageData();
			period.put("DURATION", "1");
			period.put("WORKSTATUS", "1");
			period.put("WORKPERIOD", "1");

			p.put("periodStr", period.getString("DURATION")+','+period.getString("WORKSTATUS")+','+period.getString("WORKPERIOD"));
			p.put("period", period);
			varList.add(p);
		}
		map.put("varList", varList);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 批量删除
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteAll")
	// @RequiresPermissions("shiftworkperiod: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(",");
			shiftworkperiodService.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("企业ID"); // 3
		titles.add("添加人"); // 4
		titles.add("添加时间"); // 5
		titles.add("修改人"); // 6
		titles.add("修改时间"); // 7
		titles.add("是否删除 1-是  0-否"); // 8
		titles.add("倒班规则id"); // 9
		titles.add("倒班周期排序"); // 10
		dataMap.put("titles", titles);
		List<PageData> varOList = shiftworkperiodService.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("ONDAY")); // 1
			vpd.put("var2", varOList.get(i).getString("OFFDAY")); // 2
			vpd.put("var3", varOList.get(i).getString("CORPINFO_ID")); // 3
			vpd.put("var4", varOList.get(i).getString("CREATOR")); // 4
			vpd.put("var5", varOList.get(i).getString("CREATTIME")); // 5
			vpd.put("var6", varOList.get(i).getString("OPERATOR")); // 6
			vpd.put("var7", varOList.get(i).getString("OPERATTIME")); // 7
			vpd.put("var8", varOList.get(i).getString("ISDELETE")); // 8
			vpd.put("var9", varOList.get(i).getString("SHIFTWORKRULES_ID")); // 9
			vpd.put("var10", varOList.get(i).getString("SORT")); // 10
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv, dataMap);
		return mv;
	}

}
