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

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.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workeffect.entity.WorkEffectExcel;
import com.jeeplus.modules.workeffectdetail.entity.WorkEffectDetail;
import com.jeeplus.modules.workeffectdetail.service.WorkEffectDetailService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
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.workeffect.entity.WorkEffect;
import com.jeeplus.modules.workeffect.service.WorkEffectService;

/**
 * 绩效Controller
 * @author ssrh
 * @version 2018-09-11
 */
@Controller
@RequestMapping(value = "${adminPath}/workeffect/workEffect")
public class WorkEffectController extends BaseController {

	@Autowired
	private WorkEffectService workEffectService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkEffectDetailService workEffectDetailService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@Autowired
	private UserService userService;

	@ModelAttribute
	public WorkEffect get(@RequestParam(required=false) String id) {
		WorkEffect entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workEffectService.get(id);
		}
		if (entity == null){
			entity = new WorkEffect();
		}
		return entity;
	}
	
	/**
	 * 绩效列表页面
	 */
	@RequiresPermissions("workeffect:workEffect:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkEffect workEffect, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkEffect> page = workEffectService.findPage(new Page<WorkEffect>(request, response), workEffect); 
		model.addAttribute("page", page);
		return "modules/workeffect/workEffectList";
	}

	/**
	 * 查看，增加，编辑绩效表单页面
	 */
	@RequiresPermissions(value={"workeffect:workEffect:view","workeffect:workEffect:add","workeffect:workEffect:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkEffect workEffect, Model model) {
		model.addAttribute("workEffect", workEffect);
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			return "modules/workeffect/workEffectView";
		}
		return "modules/workeffect/workEffectForm";
	}

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

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workeffect:workEffect:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(WorkEffectExcel workEffectExcel,@RequestParam(value = "file",required = false) MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			Date month = null;
			Office office = null;
			if(workEffectExcel != null){
				month = workEffectExcel.getMonth();
				office = workEffectExcel.getOffice();
			}
			if(month == null ){
				addMessage(redirectAttributes, "导入绩效失败！失败信息：月份信息未获取");
				return "redirect:"+Global.getAdminPath()+"/workeffect/workEffect/?repage";
			}
			if(office == null || (office!=null && StringUtils.isBlank(office.getId()))){
				addMessage(redirectAttributes, "导入绩效失败！失败信息：部门信息未获取");
				return "redirect:"+Global.getAdminPath()+"/workeffect/workEffect/?repage";
			}
			WorkEffect workEffect = new WorkEffect();
			workEffect.setMonth(month);
			workEffect.setOffice(office);
			//绩效数据
			List<WorkEffect> list = workEffectService.findList(workEffect);
			if(list == null || list.size() == 0){
				workEffect.setId("");
				workEffect.setCompanyId(UserUtils.getSelectCompany().getId());
				workEffect.setStatus("1");
				Integer count = userService.userCount(office.getId());
				workEffect.setOfficeNum(count+"");
				workEffectService.save(workEffect);
			}else{
				workEffect = list.get(0);
			}
			//绩效明细数据
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkEffectDetail> dataList = ei.getDataList(WorkEffectDetail.class);
			for (WorkEffectDetail workEffectDetail : dataList){
				try{
					//根据工号  姓名找人
					if(StringUtils.isNotBlank(workEffectDetail.getNo()) && StringUtils.isNotBlank(workEffectDetail.getName())){
						WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
						workStaffBasicInfo.setNo(workEffectDetail.getNo());
						workStaffBasicInfo.setName(workEffectDetail.getName());
						workStaffBasicInfo.setCompany(UserUtils.getSelectCompany());
						workStaffBasicInfo = workStaffBasicInfoService.getByNoName(workStaffBasicInfo);
						if(workStaffBasicInfo!=null && StringUtils.isNotBlank(workStaffBasicInfo.getId())){
							workEffectDetail.setEffectId(workEffect.getId());
							workEffectDetail.setWorkStaffBasicInfo(workStaffBasicInfo);
							workEffectDetail.setJobGrade(workStaffBasicInfo.getJobGrade().getName());
							Integer count = workEffectDetailService.effectCount(workEffectDetail);
							if (count == null || count==0){
								workEffectDetailService.save(workEffectDetail);
								successNum++;
							}else {
								failureNum++;
							}

						}else{
							failureNum++;
						}
					}
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			//绩效人数
			if(StringUtils.isNotBlank(workEffect.getId())){
				WorkEffectDetail workEffectDetail2 = new WorkEffectDetail();
				workEffectDetail2.setEffectId(workEffect.getId());
				List<WorkEffectDetail> workEffectDetailList = workEffectDetailService.findList(workEffectDetail2);
				if(workEffectDetailList!=null){
					workEffect.setEffectNum(workEffectDetailList.size()+"");
					workEffect.preUpdate();
					workEffectService.updateEffectNum(workEffect);
					Double money = 0.00;
					//绩效总金额
					for (WorkEffectDetail WorkEffectDetail:
							workEffectDetailList) {
						if(StringUtils.isNotBlank(WorkEffectDetail.getMoney())){
							money += new Double(WorkEffectDetail.getMoney());
						}
					}
					workEffect.setEffectMoney(money+"");
					workEffect.preUpdate();
					workEffectService.updateMoney(workEffect);
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条绩效记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条绩效记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入绩效失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workeffect/workEffect/?repage";
    }
	
	/**
	 * 下载导入绩效数据模板
	 */
	@RequiresPermissions("workeffect:workEffect:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "绩效数据导入模板.xlsx";
    		List<WorkEffect> list = Lists.newArrayList(); 
    		new ExportExcel("绩效数据", WorkEffect.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workeffect/workEffect/?repage";
    }

	@RequestMapping(value = "importDialogre")
	public String form(WorkEffectExcel workEffectExcel, Model model) {
		model.addAttribute("workEffectExcel", workEffectExcel);
		return "modules/workeffect/workEffectExcel";
	}
	

}