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

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.BaiduApi;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.service.AreaService;
import com.jeeplus.modules.workattendance.entity.WorkAttendanceInfo;
import com.jeeplus.modules.workattendance.service.WorkAttendanceInfoService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import net.sf.json.JSONObject;
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.*;
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.workattendance.entity.WorkAttendanceRule;
import com.jeeplus.modules.workattendance.service.WorkAttendanceRuleService;

import static com.jeeplus.common.utils.GetLocation.getLogLatByCity;

/**
 * 考勤规则Controller
 * @author 杨帆
 * @version 2018-09-05
 */
@Controller
@RequestMapping(value = "${adminPath}/workattendance/workAttendanceRule")
public class WorkAttendanceRuleController extends BaseController {

	@Autowired
	private WorkAttendanceRuleService workAttendanceRuleService;
	@Autowired
	private WorkAttendanceInfoService workAttendanceInfoService;
	@Autowired
	private AreaService areaService;
	
	@ModelAttribute
	public WorkAttendanceRule get(@RequestParam(required=false) String id) {
		WorkAttendanceRule entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workAttendanceRuleService.get(id);
		}
		if (entity == null){
			entity = new WorkAttendanceRule();
		}
		return entity;
	}
	
	/**
	 * 考勤规则管理列表页面
	 */
	@RequiresPermissions("workattendance:workAttendanceRule:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkAttendanceRule workAttendanceRule, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkAttendanceRule> page = workAttendanceRuleService.findPage(new Page<WorkAttendanceRule>(request, response), workAttendanceRule); 
		model.addAttribute("page", page);
		return "modules/workattendance/workAttendanceRuleList";
	}

	/**
	 * 查看，增加，编辑考勤规则表单页面
	 */
	@RequiresPermissions(value={"workattendance:workAttendanceRule:view","workattendance:workAttendanceRule:add","workattendance:workAttendanceRule:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkAttendanceRule workAttendanceRule, HttpServletRequest request, Model model) {
		String ip = BaiduApi.getIpAddr(request);
		try {
			if (StringUtils.isBlank(ip)||ip.equals("127.0.0.1") ||ip.equals("0:0:0:0:0:0:0:1")){
				ip = "218.244.52.226";
			}
			JSONObject object = BaiduApi.baiduGetCityCode(ip);
			JSONObject content = object.getJSONObject("content");
			Object address = content.get("address");
			String areaName = "";
			if (address!=null){
				areaName = address.toString();
			}else {
				areaName = "北京市";
			}
			String areaId = areaService.getAreaIdByCityName(areaName);
			if (StringUtils.isBlank(areaId)){
				areaId = "C8B02087336B4974A2D424EA71E33863";
			}
			Area area = new Area(areaId);
			area.setName(areaName);
			workAttendanceRule.setArea(area);
			logger.info("address"+address);
		} catch (IOException e) {
			e.printStackTrace();
		}
		model.addAttribute("workAttendanceRule", workAttendanceRule);
		if(StringUtils.isBlank(workAttendanceRule.getView())) {
			return "modules/workattendance/workAttendanceRuleForm";
		}else {
			return "modules/workattendance/workAttendanceRuleView";
		}
	}

	/**
	 * 保存考勤规则
	 */
	@RequiresPermissions(value={"workattendance:workAttendanceRule:add","workattendance:workAttendanceRule:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkAttendanceRule workAttendanceRule, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workAttendanceRule)){
			return form(workAttendanceRule,request, model);
		}
		workAttendanceRuleService.save(workAttendanceRule);//保存
		addMessage(redirectAttributes, "保存考勤规则成功");
		return "redirect:"+Global.getAdminPath()+"/workattendance/workAttendanceRule/?repage";
	}
	
	/**
	 * 保存考勤规则
	 */
	@RequestMapping(value = "isSave")
	@ResponseBody
	public AjaxJson isSave(String id, String userIds, String officeIds,String branchOffice, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson json = new AjaxJson();
		try {
			String msg = workAttendanceRuleService.isSave(id,userIds,officeIds,branchOffice);
			if(StringUtils.isNotBlank(msg)){
                json.setMsg(msg);
                json.setSuccess(false);
            }else {
			    json.setSuccess(true);
            }
		}catch (Exception e){
			json.setMsg("系统错误，请稍后再试！");
			json.setSuccess(false);
		}

		return json;
	}

	/**
	 * 删除考勤规则管理
	 */
	@RequiresPermissions("workattendance:workAttendanceRule:del")
	@RequestMapping(value = "delete")
	public String delete(WorkAttendanceRule workAttendanceRule, RedirectAttributes redirectAttributes) {
		workAttendanceRuleService.delete(workAttendanceRule);
		addMessage(redirectAttributes, "删除考勤规则成功");
		return "redirect:"+Global.getAdminPath()+"/workattendance/workAttendanceRule/?repage";
	}
	/**
	 * 调用百度api
	 */
	@RequestMapping(value = "baidiApi")
	public String baidiApi(String name,String city,String itude, HttpServletRequest request, Model model) {
		model.addAttribute("name", name);
		model.addAttribute("city", city);
        String x = "";
        String y = "";
		if (StringUtils.isNotBlank(itude)){
            x = itude.split(",")[0];
            y = itude.split(",")[1];
        }
        model.addAttribute("x", x);
        model.addAttribute("y", y);
		model.addAttribute("city", city);
		return "modules/workattendance/baiduApi";
	}

	/**
	 * 批量删除考勤规则
	 */
	@RequiresPermissions("workattendance:workAttendanceRule:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workAttendanceRuleService.delete(workAttendanceRuleService.get(id));
		}
		addMessage(redirectAttributes, "删除考勤规则成功");
		return "redirect:"+Global.getAdminPath()+"/workattendance/workAttendanceRule/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workattendance:workAttendanceRule:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkAttendanceRule workAttendanceRule, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "考勤规则"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkAttendanceRule> page = workAttendanceRuleService.findPage(new Page<WorkAttendanceRule>(request, response, -1), workAttendanceRule);
    		new ExportExcel("考勤规则", WorkAttendanceRule.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出考勤规则记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workattendance/workAttendanceRule/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workattendance:workAttendanceRule: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<WorkAttendanceRule> list = ei.getDataList(WorkAttendanceRule.class);
			for (WorkAttendanceRule workAttendanceRule : list){
				try{
					workAttendanceRuleService.save(workAttendanceRule);
					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()+"/workattendance/workAttendanceRule/?repage";
    }
	
	/**
	 * 下载导入考勤规则数据模板
	 */
	@RequiresPermissions("workattendance:workAttendanceRule:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "考勤规则数据导入模板.xlsx";
    		List<WorkAttendanceRule> list = Lists.newArrayList(); 
    		new ExportExcel("考勤规则数据", WorkAttendanceRule.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workattendance/workAttendanceRule/?repage";
    }

	//获取坐标所在城市
	@RequestMapping("isCity")
	@ResponseBody
	public String isCity(String itude)  {
		String arr[]=itude.split(",");
		String city = getLogLatByCity(arr[0], arr[1]);
		return  city;
	}
}