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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
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.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.worksalaryitem.entity.WorkSalaryItem;
import com.jeeplus.modules.worksalaryitem.service.WorkSalaryItemService;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
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.worksinglewage.entity.WorkSingleWage;
import com.jeeplus.modules.worksinglewage.service.WorkSingleWageService;

/**
 * 单笔工资项Controller
 * @author 杨帆
 * @version 2018-09-26
 */
@Controller
@RequestMapping(value = "${adminPath}/worksinglewage/workSingleWage")
public class WorkSingleWageController extends BaseController {

	@Autowired
	private WorkSingleWageService workSingleWageService;
	@Autowired
	private WorkSalaryItemService workSalaryItemService;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ActTaskService actTaskService;
	
	@ModelAttribute
	public WorkSingleWage get(@RequestParam(required=false) String id) {
		WorkSingleWage entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workSingleWageService.get(id);
		}
		if (entity == null){
			entity = new WorkSingleWage();
		}
		return entity;
	}
	
	/**
	 * 单笔工资项列表页面
	 */
	@RequiresPermissions("worksinglewage:workSingleWage:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkSingleWage workSingleWage, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (StringUtils.isNotBlank(workSingleWage.getMinmoney() )|| StringUtils.isNotBlank(workSingleWage.getMaxmoney())){
			try {
				Double minMoney = Double.parseDouble(workSingleWage.getMinmoney());
				Double maxMoney = Double.parseDouble(workSingleWage.getMaxmoney());
			}catch (Exception e){
				Page<WorkSingleWage> page = workSingleWageService.findPage(new Page<WorkSingleWage>(request, response), workSingleWage);
				model.addAttribute("page", page);
				model.addAttribute("message", "发放金额请输入数字");
				return "modules/worksinglewage/workSingleWageList";
			}
		}
		Page<WorkSingleWage> page = workSingleWageService.findPage(new Page<WorkSingleWage>(request, response), workSingleWage); 
		model.addAttribute("page", page);
		return "modules/worksinglewage/workSingleWageList";
	}

	/**
	 * 查看，增加，编辑单笔工资项表单页面
	 */
	@RequiresPermissions(value={"worksinglewage:workSingleWage:view","worksinglewage:workSingleWage:add","worksinglewage:workSingleWage:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkSingleWage workSingleWage, Model model) {
		Map<String,String> map = StringUtils.getMonth();
		if (workSingleWage==null || StringUtils.isBlank(workSingleWage.getId())){
			workSingleWage.setNowMonth("1");
			workSingleWage.setMonth(map.get(workSingleWage.getNowMonth()));
			workSingleWage.setCreateBy(UserUtils.getUser());
			workSingleWage.setCreateDate(new Date());
			WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
			workStaffBasicInfo.setBranchOffice(new Office(UserUtils.getSelectBranchOffice()));
			workSingleWage.setBranchCount(workStaffAchivesDao.getByBranchCompany(workStaffBasicInfo));
			workSingleWage.setGrantCount(0);
		}
		String view = "workSingleWageForm";
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workSingleWageView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workSingleWage.getProcessInstanceId());
			if (processInstance!=null) {
				Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
				Act act = new Act();
				act.setTaskId(taskInfok.getId());
				act.setTaskName(taskInfok.getName());
				act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
				act.setProcDefId(taskInfok.getProcessDefinitionId());
				act.setProcInsId(taskInfok.getProcessInstanceId());
				act.setTask(taskInfok);
				workSingleWage.setAct(act);
				view = "workSingleWageModifyApply";
			}
		}
		// 环节编号
		String taskDefKey = workSingleWage.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && "".equals(taskDefKey)){
			view = "workSingleWageAudit";
		}
		model.addAttribute("workSingleWage", workSingleWage);
		model.addAttribute("nowm", map.get("1"));
		model.addAttribute("oldm", map.get("2"));
		return "modules/worksinglewage/"+view;
	}

	/**
	 * 保存单笔工资项
	 */
	@RequiresPermissions(value={"worksinglewage:workSingleWage:add","worksinglewage:workSingleWage:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkSingleWage workSingleWage, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workSingleWage)){
			return form(workSingleWage, model);
		}
		String processInstanceId ="";
		User user = workSingleWage.getCreateBy();
		String sta = workSingleWage.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/worksinglewage/workSingleWage/?repage";
		}
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workSingleWageService.get(workSingleWage.getId()).getProcessInstanceId();
		}
		workSingleWage.setStatus("2");
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workSingleWage.setCompanyId(UserUtils.getSelectCompany().getId());
			String str = workSingleWageService.save(workSingleWage, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "单笔工资项提交:"+str);
			}else {
				addMessage(redirectAttributes, "单笔工资项已经提交");
			}

		} catch (Exception e) {
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "单笔工资项提交失败!");
		}
		return "redirect:"+Global.getAdminPath()+"/worksinglewage/workSingleWage/?repage";
	}
	/**
	 * 保存单笔工资项
	 */
	@RequiresPermissions(value={"worksinglewage:workSingleWage:add","worksinglewage:workSingleWage:edit"},logical=Logical.OR)
	@RequestMapping(value = "store")
	public String store(WorkSingleWage workSingleWage, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workSingleWage)){
			return form(workSingleWage, model);
		}
		workSingleWage.setStatus("1");
		if (StringUtils.isNotBlank(workSingleWage.getProcessInstanceId()) && workSingleWage.getProcessInstanceId().equals("NULL")){
			workSingleWage.setProcessInstanceId("");
		}
		workSingleWageService.save(workSingleWage);//保存
		addMessage(redirectAttributes, "保存单笔工资项成功");
		return "redirect:"+Global.getAdminPath()+"/worksinglewage/workSingleWage/?repage";
	}

	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkSingleWage workSingleWage, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workSingleWage.getAct().getTaskDefKey();
			List<User> users = null;
			if ("bmzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workSingleWage.getProcessInstanceId(),1);
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workSingleWage.getProcessInstanceId(),1);
			}
			String flag = workSingleWage.getAct().getFlag();
			if ("yes".equals(flag) &&(users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workSingleWageService.auditSave(workSingleWage,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workSingleWage.getHome()) && "home".equals(workSingleWage.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:"+Global.getAdminPath()+"/worksinglewage/workSingleWage/?repage";
		}
	}

	/**
	 * 删除单笔工资项
	 */
	@RequiresPermissions("worksinglewage:workSingleWage:del")
	@RequestMapping(value = "delete")
	public String delete(WorkSingleWage workSingleWage, RedirectAttributes redirectAttributes) {
		workSingleWageService.delete(workSingleWage);
		addMessage(redirectAttributes, "删除单笔工资项成功");
		return "redirect:"+Global.getAdminPath()+"/worksinglewage/workSingleWage/?repage";
	}
	
	/**
	 * 批量删除单笔工资项
	 */
	@RequiresPermissions("worksinglewage:workSingleWage:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workSingleWageService.delete(workSingleWageService.get(id));
		}
		addMessage(redirectAttributes, "删除单笔工资项成功");
		return "redirect:"+Global.getAdminPath()+"/worksinglewage/workSingleWage/?repage";
	}


	/**
	 * 合同作废：强制撤回
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkSingleWage workSingleWage,RedirectAttributes redirectAttributes){
		try {
			WorkSingleWage singleWage = workSingleWageService.get(workSingleWage.getId());
			if(singleWage.getStatus().equals("5")){
				addMessage(redirectAttributes, "单笔工资项已审批通过，无法撤回");
			}else{
				workSingleWageService.cancelInvalidate(singleWage);
				addMessage(redirectAttributes, "单笔工资项撤回成功");
			}
		}catch (Exception e){
			logger.error("Exception e"+e);
			addMessage(redirectAttributes, "单笔工资项撤回失败");
		}
		return "redirect:"+Global.getAdminPath()+"/worksinglewage/workSingleWage/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("worksinglewage:workSingleWage:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkSingleWage workSingleWage, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "单笔工资项"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkSingleWage> page = workSingleWageService.findPage(new Page<WorkSingleWage>(request, response, -1), workSingleWage);
    		new ExportExcel("单笔工资项", WorkSingleWage.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出单笔工资项记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/worksinglewage/workSingleWage/?repage";
    }

	/**
	 * 导入Excel数据

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

	/**
	 * 选择报销项目
	 */
	@RequestMapping(value = "selectWage")
	public String selectWage(WorkSingleWage workSingleWage, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		WorkSalaryItem workSalaryItem = workSingleWage.getWorkSalaryItem();
		if (workSalaryItem == null){
			workSalaryItem = new WorkSalaryItem();
		}
		workSalaryItem.setCompanyId(UserUtils.getSelectCompany().getId());
		workSalaryItem.setState("2");
		Page<WorkSalaryItem> page = workSalaryItemService.findPage(new Page<WorkSalaryItem>(request, response), workSalaryItem);
		try {
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "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", workSingleWage);
		model.addAttribute("allowInput", true);
		model.addAttribute("page", page);
		return "modules/sys/gridselectcallwage";
		//return "modules/sys/gridselect";
	}

	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkSingleWage workSingleWage,Model model) {
		model.addAttribute("processInstanceId", workSingleWage.getProcessInstanceId());
		return "modules/workreimbursement/workReimbursementTrack";
	}

}