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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

import com.jeeplus.modules.projectcontentinfo.entity.ProjectContentData;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workmonthlyplan.entity.WorkMonthlyPlanThis;
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.workmonthlyplan.entity.WorkMonthlyPlan;
import com.jeeplus.modules.workmonthlyplan.service.WorkMonthlyPlanService;

/**
 * 月计划管理Controller
 * @author cyp
 * @version 2018-06-27
 */
@Controller
@RequestMapping(value = "${adminPath}/workmonthlyplan/workMonthlyPlan")
public class WorkMonthlyPlanController extends BaseController {

	@Autowired
	private WorkMonthlyPlanService workMonthlyPlanService;
	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private HttpServletRequest request;
	@ModelAttribute
	public WorkMonthlyPlan get(@RequestParam(required=false) String id) {
		WorkMonthlyPlan entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workMonthlyPlanService.get(id);
		}
		if (entity == null){
			entity = new WorkMonthlyPlan();
		}
		return entity;
	}
	
	/**
	 * 月计划管理列表页面
	 */
	@RequiresPermissions("workmonthlyplan:workMonthlyPlan:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkMonthlyPlan workMonthlyPlan, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkMonthlyPlan> page = workMonthlyPlanService.findPage(new Page<WorkMonthlyPlan>(request, response), workMonthlyPlan); 
		model.addAttribute("page", page);
		return "modules/workmonthlyplan/workMonthlyPlanList";
	}

	/**
	 * 查看，增加，编辑月计划管理表单页面
	 */
	@RequiresPermissions(value={"workmonthlyplan:workMonthlyPlan:view","workmonthlyplan:workMonthlyPlan:add","workmonthlyplan:workMonthlyPlan:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkMonthlyPlan workMonthlyPlan, Model model) {
		String view = "workMonthlyPlanFormAdd";
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workMonthlyPlanFormView";
		}
		//新增默认回显数据
		if("2".equals(tabId)){
			Office office = UserUtils.getSelectOffice();
			workMonthlyPlan.setOfficeId(office.getId());
			workMonthlyPlan.setOfficeName(office.getTopCompany());
			workMonthlyPlan.setName(UserUtils.getUser().getName());
			workMonthlyPlan.setCompanyId(UserUtils.getSelectCompany().getId());
		}
		//查询子表数据
		List<WorkMonthlyPlanThis> workMonthlyPlanThisList = workMonthlyPlanService.findWorkMonthlyPlanThisList(workMonthlyPlan.getId());
		workMonthlyPlan.setWorkMonthlyPlanThisList(workMonthlyPlanThisList);
		model.addAttribute("workMonthlyPlan", workMonthlyPlan);
		return "modules/workmonthlyplan/"+view;
	}

	/**
	 * 保存月计划管理
	 */
	@RequiresPermissions(value={"workmonthlyplan:workMonthlyPlan:add","workmonthlyplan:workMonthlyPlan:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkMonthlyPlan workMonthlyPlan, Model model, RedirectAttributes redirectAttributes) throws Exception{
		System.out.println(workMonthlyPlan.getWorkMonthlyPlanThisList());
		if (!beanValidator(model, workMonthlyPlan)){
			return form(workMonthlyPlan, model);
		}
		//判断本部门本月份是否已审定过计划
		boolean flag=workMonthlyPlanService.getMonthly(workMonthlyPlan);
		if(flag){
            addMessage(redirectAttributes, "本部门该月份已制定计划，请选择其它月份！");
            return "redirect:"+Global.getAdminPath()+"/workmonthlyplan/workMonthlyPlan/?repage";
        }
		workMonthlyPlan.setPlanStatus("0");
		if(!workMonthlyPlan.getIsNewRecord()){//编辑表单保存
			System.out.println(workMonthlyPlan.getWorkMonthlyPlanThisList());
			WorkMonthlyPlan t = workMonthlyPlanService.get(workMonthlyPlan.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workMonthlyPlan, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workMonthlyPlanService.save(t);//保存
		}else{//新增表单保存
			workMonthlyPlanService.save(workMonthlyPlan);//保存
		}
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/workmonthlyplan/workMonthlyPlan/?repage";
	}
	/**
	 * 保存月计划管理
	 */
	@RequiresPermissions(value={"workmonthlyplan:workMonthlyPlan:review"},logical=Logical.OR)
	@RequestMapping(value = "review")
	public String review(WorkMonthlyPlan workMonthlyPlan, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workMonthlyPlan)){
			return form(workMonthlyPlan, model);
		}
        //判断本部门本月份是否已审定过计划
       /* boolean flag=workMonthlyPlanService.getMonthlyRew(workMonthlyPlan);
        if(flag){
            addMessage(redirectAttributes, "本部门该月份已制定计划，请选择其它月份！");
            return "redirect:"+Global.getAdminPath()+"/workmonthlyplan/workMonthlyPlan/?repage";
        }*/
		workMonthlyPlan.setPlanStatus("1");
		if(!workMonthlyPlan.getIsNewRecord()){//编辑表单保存
			WorkMonthlyPlan t = workMonthlyPlanService.get(workMonthlyPlan.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workMonthlyPlan, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workMonthlyPlanService.save(t);//保存
		}else{//新增表单保存
			workMonthlyPlanService.save(workMonthlyPlan);//保存
		}
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/workmonthlyplan/workMonthlyPlan/?repage";
	}
	
	/**
	 * 删除月计划管理
	 */
	@RequiresPermissions("workmonthlyplan:workMonthlyPlan:del")
	@RequestMapping(value = "delete")
	public String delete(WorkMonthlyPlan workMonthlyPlan, RedirectAttributes redirectAttributes) {
		workMonthlyPlanService.delete(workMonthlyPlan);
		addMessage(redirectAttributes, "删除月计划管理成功");
		return "redirect:"+Global.getAdminPath()+"/workmonthlyplan/workMonthlyPlan/?repage";
	}
	
	/**
	 * 批量删除月计划管理
	 */
	@RequiresPermissions("workmonthlyplan:workMonthlyPlan:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workMonthlyPlanService.delete(workMonthlyPlanService.get(id));
		}
		addMessage(redirectAttributes, "删除月计划管理成功");
		return "redirect:"+Global.getAdminPath()+"/workmonthlyplan/workMonthlyPlan/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	//@RequiresPermissions("workmonthlyplan:workMonthlyPlan:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkMonthlyPlan workMonthlyPlan, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "月计划管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkMonthlyPlan> page = workMonthlyPlanService.findPage(new Page<WorkMonthlyPlan>(request, response, -1), workMonthlyPlan);
            List<WorkMonthlyPlanThis> list =new ArrayList<>();
            for (WorkMonthlyPlan w:page.getList()){
                List<WorkMonthlyPlanThis> workMonthlyPlanThisList = workMonthlyPlanService.findWorkMonthlyPlanThisList(w.getId());
                list.addAll(workMonthlyPlanThisList);
            }
    		new ExportExcel("月计划管理", WorkMonthlyPlanThis.class).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出月计划管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workmonthlyplan/workMonthlyPlan/?repage";
    }

	/**
	 * 导入Excel数据

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

	@RequestMapping("selectcontentData")
	public String gridSelectData(WorkMonthlyPlan workMonthlyPlan, String searchLabel , HttpServletRequest request, HttpServletResponse response, Model model){
		List<WorkMonthlyPlan> list = workMonthlyPlanService.findHisList();
		//model.addAttribute("obj", workMonthlyPlan);
		model.addAttribute("list", list);
		//model.addAttribute("searchLabel",searchLabel);
		return "modules/workmonthlyplan/workMonthlyPlanQuote";
	}

	@RequestMapping("getWorkMonthlyPlanThis")
	@ResponseBody
	public List<WorkMonthlyPlanThis> getWorkMonthlyPlanThis(String  id){
		List<WorkMonthlyPlanThis> workMonthlyPlanThisList = workMonthlyPlanService.findWorkMonthlyPlanThis(id);
		return  workMonthlyPlanThisList;
	}
	//获取本部门计划最大月份
	@RequestMapping("getThisMaxMonthly")
	@ResponseBody
	public Date getThisMaxMonthly() throws ParseException {
		Date maxThisMonthly = workMonthlyPlanService.getThisMaxMonthly();
		return  maxThisMonthly;
	}
	@RequestMapping("linkmanList")
	public String queryLinkmanListByClientId(WorkClientLinkman linkman, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String searchLabel1, String searchKey1, HttpServletRequest request, HttpServletResponse response, Model model){
		Page<WorkClientLinkman> page = workClientInfoService.findLinkmanPage(new Page<WorkClientLinkman>(request, response), linkman);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", linkman);
		model.addAttribute("page", page);
		return  "modules/workmonthlyplan/gridselect";
	}

	//获取所选客户本月前已收款
	@RequestMapping("getBeforeThisMonthMoney")
	@ResponseBody
	public WorkMonthlyPlanThis getBeforeThisMonthMoney(String clientId,String planMonthly) throws ParseException {
		WorkMonthlyPlanThis workMonthlyPlanThis = workMonthlyPlanService.getBeforeThisMonthMoney(clientId,planMonthly);
		return  workMonthlyPlanThis;
	}

	/**
	 * 合同管理列表页面
	 */
	@RequestMapping(value = {"clientInfoList"})
	public String list(WorkContractInfo workContractInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		workContractInfo.setOfficeId(user.getOffice().getId());
		Page<WorkContractInfo> page = workMonthlyPlanService.findWorkContractInfoPage(new Page<WorkContractInfo>(request, response), workContractInfo);
		model.addAttribute("page", page);
		return "modules/workmonthlyplan/gridselect";
	}


/*	@RequestMapping("getHisThis")
	@ResponseBody
	public String getHisThis(String  planMonthly){
		//判断本部门本月份是否已审定过计划
		WorkMonthlyPlan workMonthlyPlan=new WorkMonthlyPlan();
		workMonthlyPlan.setOfficeId(UserUtils.getSelectOffice().getId());
		boolean flag=workMonthlyPlanService.getMonthly(workMonthlyPlan);
		if(flag){
			return "no";
		}else{
			return  "yes";
		}

	}*/
}