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

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.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workloan.entity.WorkLoan;
import com.jeeplus.modules.workloan.service.WorkLoanService;
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.workrepay.entity.WorkRepay;
import com.jeeplus.modules.workrepay.service.WorkRepayService;

/**
 * 还款Controller
 * @author ssrh
 * @version 2018-10-17
 */
@Controller
@RequestMapping(value = "${adminPath}/workrepay/workRepay")
public class WorkRepayController extends BaseController {

	@Autowired
	private WorkRepayService workRepayService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkLoanService workLoanService;

	@ModelAttribute
	public WorkRepay get(@RequestParam(required=false) String id) {
		WorkRepay entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workRepayService.get(id);
		}
		if (entity == null){
			entity = new WorkRepay();
		}
		return entity;
	}
	
	/**
	 * 还款列表页面
	 */
	//@RequiresPermissions("workrepay:workRepay:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkRepay workRepay, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkRepay> page = workRepayService.findPage(new Page<WorkRepay>(request, response), workRepay); 
		model.addAttribute("page", page);
		return "modules/workrepay/workRepayList";
	}

	/**
	 * 查看，增加，编辑还款表单页面
	 */
	//@RequiresPermissions(value={"workrepay:workRepay:view","workrepay:workRepay:add","workrepay:workRepay:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkRepay workRepay, Model model) {
		if(StringUtils.isBlank(workRepay.getId())){
			String loanId = request.getParameter("loanId");
			WorkLoan workLoan = workLoanService.get(loanId);
			workRepay.setWorkLoan(workLoan);
			workRepay.setCreateBy(UserUtils.getUser());
			workRepay.setRepayDate(new Date());
			workRepay.setSource("2");//直接还款
			if(workLoan!=null && StringUtils.isNotBlank(workLoan.getMoney()) && StringUtils.isNotBlank(workLoan.getRepay())){
				Double notRepay = Double.parseDouble(workLoan.getMoney()) - Double.parseDouble(workLoan.getRepay());
				workRepay.setNotRepay(notRepay+"");
			}else{
				workRepay.setNotRepay("0");
			}
		}
		model.addAttribute("workRepay", workRepay);
		return "modules/workrepay/workRepayForm";
	}

	/**
	 * 保存还款
	 */
	//@RequiresPermissions(value={"workrepay:workRepay:add","workrepay:workRepay:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkRepay workRepay, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workRepay)){
			return form(workRepay, model);
		}
		WorkLoan workLoan = workRepay.getWorkLoan();
		WorkRepay w = new WorkRepay();
		w.setWorkLoan(workLoan);
		w.setStatus("2");
		List<WorkRepay> list = workRepayService.findList(w);
		if(list!=null && list.size()>0){
			addMessage(redirectAttributes, "目前尚有还款正在处理，请结束后再操作");
			return "redirect:"+Global.getAdminPath()+"/workloan/workLoan/?repage";
		}
		User user = workRepay.getCreateBy();
		//状态设置为审核中
		workRepay.setStatus("2");
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workRepay.setCompanyId(UserUtils.getSelectCompany().getId());
			workRepay.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workRepayService.save(workRepay, variables,"");
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "申请已经提交");
			}

		} catch (Exception e) {
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		addMessage(redirectAttributes, "保存还款成功");
		return "redirect:"+Global.getAdminPath()+"/workloan/workLoan/?repage";
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkRepay workRepay, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			List<User> users = UserUtils.getByProssType(workRepay.getProcessInstanceId(),1);
			String flag = workRepay.getAct().getFlag();
			if ("yes".equals(flag) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workRepayService.auditSave(workRepay,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败");
		}

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

	/**
	 * 导入Excel数据

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

}