/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.oa.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.collect.Maps;
import com.jeeplus.modules.oa.dao.OaAttendancePlaceDao;
import com.jeeplus.modules.oa.entity.OaAttendancePlace;
import com.jeeplus.modules.oa.service.OaAttendancePlaceService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.oa.entity.OaAttendanceRule;
import com.jeeplus.modules.oa.service.OaAttendanceRuleService;
import com.jeeplus.modules.sys.entity.Office;

/**
 * 考勤规则Controller
 * @author 孟祥越
 * @version 2017-05-10
 */
@Controller
@RequestMapping(value = "${adminPath}/oa/oaAttendanceRule")
public class OaAttendanceRuleController extends BaseController {

	@Autowired
	private OaAttendanceRuleService oaAttendanceRuleService;
	@Autowired
	private OaAttendancePlaceService oaAttendancePlaceService;
	@ModelAttribute
	public OaAttendanceRule get(@RequestParam(required=false) String id) {
		OaAttendanceRule entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = oaAttendanceRuleService.get(id);
		}
		if (entity == null){
			entity = new OaAttendanceRule();
		}
		return entity;
	}
	
	/**
	 * 考勤规则列表页面
	 */
	@RequiresPermissions("oa:oaAttendanceRule:list")
	@RequestMapping(value = {"list", ""})
	public String list(OaAttendanceRule oaAttendanceRule, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		oaAttendanceRule.setCompany(user.getCompany());
		Page<OaAttendanceRule> page = oaAttendanceRuleService.findPage(new Page<OaAttendanceRule>(request, response), oaAttendanceRule);
		List<OaAttendanceRule> ruleList= page.getList();
		List outterList = Lists.newArrayList();
		for(OaAttendanceRule rule : ruleList){
			String[] placeIds = rule.getPlaceId().split(",");
			String[] placeNames = new String[5];
			for(int i=0;i<placeIds.length;i++){
				String placeName = oaAttendancePlaceService.getPlaceNameById(placeIds[i]);
				if(placeName ==null || placeName.length()==0){
					placeName = "-1";
				}
				placeNames[i] = placeName ;
			}
			String[] wifiCodes = rule.getWifi().split(",");
			String[] wifiNames = rule.getWifiName().split(",");

			for(int i=0;i<placeNames.length;i++){
				String placeName = placeNames[i];
				String wifiCode  = wifiCodes[i];
				String wifiName  = wifiNames[i];
/*				if(!(placeName.equals("-1") && wifiCode.equals("-1"))){
					String str = placeName+"+"+wifiCode+"+"+wifiName;
					outterList.add(str);
				}*/
				placeName=(placeName.equals("-1")||placeName==null)?"-":placeName;
				wifiCode = (wifiCode.equals("-1")||wifiCode==null)?"-":wifiCode;
				wifiName = (wifiName.equals("-1")||wifiName==null)?"-":wifiName;
				if(!(placeName.equals("-")&&wifiCode.equals("-")&&wifiName.equals("-"))){
					String str = placeName+"+"+wifiCode+"+"+wifiName;
					outterList.add(str);
				}
			}
		}
		model.addAttribute("outterList",outterList);
		model.addAttribute("page", page);
		return "modules/oa/oaAttendanceRuleList";
	}

	/**
	 * 查看，增加，编辑考勤规则表单页面
	 */
	@RequiresPermissions(value={"oa:oaAttendanceRule:view","oa:oaAttendanceRule:add","oa:oaAttendanceRule:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(@RequestParam(value = "readAttr",required = false)String readAttr,OaAttendanceRule oaAttendanceRule, Model model,HttpServletRequest request) {

		String place_wifi_name = request.getParameter("place_wifi_name");
		if(!StringUtils.isBlank(place_wifi_name)){
			String[] arr = place_wifi_name.split(" ");
			model.addAttribute("rule_place",arr[0]);
			model.addAttribute("rule_wifi",arr[1]);
			model.addAttribute("rule_wifi_name",arr[2]);
		}
		model.addAttribute("oaAttendanceRule", oaAttendanceRule);
		model.addAttribute("disabled",(readAttr==null||"".equals(readAttr))?"false":"true");

		return "modules/oa/oaAttendanceRuleForm";
	}

	/**
	 * 查看，增加，编辑考勤规则表单页面
	 */
	@RequiresPermissions(value={"oa:oaAttendanceRule:view","oa:oaAttendanceRule:add","oa:oaAttendanceRule:edit"},logical=Logical.OR)
	@RequestMapping(value = "companyRuleForm")
	public String companyRuleForm(String companyId, Model model) {
		model.addAttribute("oaAttendanceRule", oaAttendanceRuleService.findAttendanceRuleByCompany(companyId));
		return "modules/oa/oaAttendanceRuleForm";
	}
	
	/**
	 * 保存考勤规则
	 */
	@RequiresPermissions(value={"oa:oaAttendanceRule:add","oa:oaAttendanceRule:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(OaAttendanceRule oaAttendanceRule, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, oaAttendanceRule)){
			return form("",oaAttendanceRule, model,null);
		}
		if(!oaAttendanceRule.getIsNewRecord()){//编辑表单保存
			OaAttendanceRule t = oaAttendanceRuleService.get(oaAttendanceRule.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(oaAttendanceRule, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			oaAttendanceRuleService.save(t);//保存
		}else{//新增表单保存
			oaAttendanceRuleService.save(oaAttendanceRule);//保存
		}
		addMessage(redirectAttributes, "保存考勤规则成功");
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendanceRule/?repage";
	}
	
	/**
	 * 删除考勤规则
	 */
	@RequiresPermissions("oa:oaAttendanceRule:del")
	@RequestMapping(value = "delete")
	public String delete(OaAttendanceRule oaAttendanceRule, RedirectAttributes redirectAttributes) {
		oaAttendanceRuleService.delete(oaAttendanceRule);
		addMessage(redirectAttributes, "删除考勤规则成功");
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendanceRule/?repage";
	}
	
	/**
	 * 批量删除考勤规则
	 */
	@RequiresPermissions("oa:oaAttendanceRule:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			oaAttendanceRuleService.delete(oaAttendanceRuleService.get(id));
		}
		addMessage(redirectAttributes, "删除考勤规则成功");
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendanceRule/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("oa:oaAttendanceRule:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(OaAttendanceRule oaAttendanceRule, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "考勤规则"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<OaAttendanceRule> page = oaAttendanceRuleService.findPage(new Page<OaAttendanceRule>(request, response, -1), oaAttendanceRule);
    		new ExportExcel("考勤规则", OaAttendanceRule.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出考勤规则记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendanceRule/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("oa:oaAttendanceRule:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<OaAttendanceRule> list = ei.getDataList(OaAttendanceRule.class);
			for (OaAttendanceRule oaAttendanceRule : list){
				try{
					oaAttendanceRuleService.save(oaAttendanceRule);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条考勤规则记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条考勤规则记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入考勤规则失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendanceRule/?repage";
    }
	
	/**
	 * 下载导入考勤规则数据模板
	 */
	@RequiresPermissions("oa:oaAttendanceRule:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "考勤规则数据导入模板.xlsx";
    		List<OaAttendanceRule> list = Lists.newArrayList(); 
    		new ExportExcel("考勤规则数据", OaAttendanceRule.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendanceRule/?repage";
    }
	
	
	

}