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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
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.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmtree.service.SysMtreeService;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import com.jeeplus.modules.worksupplier.service.WorkSupplierService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
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.*;
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.workloan.entity.WorkLoan;
import com.jeeplus.modules.workloan.service.WorkLoanService;

/**
 * 借款Controller
 * @author ssrh
 * @version 2018-10-16
 */
@Controller
@RequestMapping(value = "${adminPath}/workloan/workLoan")
public class WorkLoanController extends BaseController {

	@Autowired
	private WorkLoanService workLoanService;

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private WorkFullManageService workFullManageService;

	@Autowired
	private WorkBidProjectService workBidProjectService;

	@Autowired
	private SysMtreeService sysMtreeService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;

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

	/**
	 * 查看，增加，编辑借款表单页面
	 */
	//@RequiresPermissions(value={"workloan:workLoan:view","workloan:workLoan:add","workloan:workLoan:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkLoan workLoan, Model model) {
		String view = "workLoanForm";
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workLoanView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workLoan.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);
				workLoan.setAct(act);
				view = "workLoanModify";
			}
		}
		// 环节编号
		String taskDefKey = workLoan.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && !taskDefKey.equals("modifyApply")){
			view = "workLoanAudit";
		}
		if(StringUtils.isBlank(workLoan.getId())){
			WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
			workStaffBasicInfo.setUserId(UserUtils.getUser().getId());
			workStaffBasicInfo.setOffice(UserUtils.getSelectOffice());
			workStaffBasicInfo = workStaffBasicInfoService.getByUserOffice(workStaffBasicInfo);
			workLoan.setWorkStaffBasicInfo(workStaffBasicInfo);
			workLoan.setRepayState("3");
			workLoan.setCreateBy(UserUtils.getUser());
			workLoan.setLoanDate(new Date());
			workLoan.setRepay("0");
			if(workStaffBasicInfo!=null && StringUtils.isNotBlank(workStaffBasicInfo.getUserId())){
				/*//未还款
				List<WorkLoan> list1 = workLoanService.findListByUser(workStaffBasicInfo.getUserId(),"3");
				double moneyCount= 0.00;//借款
				for(int i=0;i<list1.size();i++){
					WorkLoan workLoans = list1.get(i);
					if(StringUtils.isNotBlank(workLoans.getMoney())){
						moneyCount = moneyCount + Double.parseDouble(workLoans.getMoney());
					}
				}
				//部分还款
				List<WorkLoan> list2 = workLoanService.findListByContract(workStaffBasicInfo.getUserId(),"2");
				for(int i=0;i<list2.size();i++){
					WorkLoan workLoans = list2.get(i);
					if(StringUtils.isNotBlank(workLoans.getMoney()) && StringUtils.isNotBlank(workLoans.getRepay())){
						moneyCount = moneyCount + (Double.parseDouble(workLoans.getMoney()) - Double.parseDouble(workLoans.getRepay()));
					}
				}*/
				Double notRepay = workLoanService.getnotRepay(workStaffBasicInfo);
				workLoan.setNotRepay(notRepay+"");
			}
		}
		model.addAttribute("workLoan", workLoan);
		return "modules/workloan/"+view;
	}
	/**
	 * 暂存报销单
	 */
	@RequestMapping(value = "store")
	public String store(WorkLoan workLoan,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workLoan)){
			return form(workLoan, model);
		}
		User user = workLoan.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workLoan.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workloan/workLoan/?repage";
		}
		workLoan.setStatus("1"); //暂存状态
		workLoan.setCompanyId(UserUtils.getSelectCompany().getId());
		workLoan.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workLoan.getProcessInstanceId()) && workLoan.getProcessInstanceId().equals("NULL")){
			workLoan.setProcessInstanceId("");
		}
		if(!workLoan.getIsNewRecord()){//编辑表单保存
			WorkLoan t = workLoanService.get(workLoan.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workLoan, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workLoanService.save(t);//保存
		}else{//新增表单保存
			workLoanService.save(workLoan);//保存
		}
		addMessage(redirectAttributes, "保存成功");
		return "redirect:" + adminPath +"/workloan/workLoan/?repage";
	}

	/**
	 * 保存提交报销单
	 * 启动流程
	 */
	@RequestMapping(value = "save")
	public String save(WorkLoan workLoan,
					   Model model,
					   RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workLoan)){
			return form(workLoan, model);
		}
		User user = workLoan.getCreateBy();
		String sta = workLoan.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workloan/workLoan/?repage";
		}
		//状态设置为审核中
		workLoan.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workLoanService.get(workLoan.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workLoan.setCompanyId(UserUtils.getSelectCompany().getId());
			workLoan.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workLoanService.save(workLoan, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "申请已经提交");
			}

		} catch (Exception e) {
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:" + adminPath +"/workloan/workLoan/?repage";
	}

	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkLoan workLoan, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workLoan.getAct().getTaskDefKey();
			List<User> users = null;
			Office office = null;
			if(workLoan!=null && workLoan.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workLoan.getWorkStaffBasicInfo().getId())){
				WorkStaffBasicInfo workStaffBasicInfo=workStaffBasicInfoService.getAchives(workLoan.getWorkStaffBasicInfo().getId());
				if(workStaffBasicInfo!=null){
					office = workStaffBasicInfo.getOffice();
				}
			}
			if(office == null || StringUtils.isBlank(office.getId())){
				addMessage(redirectAttributes, "审批失败,借款人档案信息有误,请确认!");
				if (StringUtils.isNotBlank(workLoan.getHome()) && "home".equals(workLoan.getHome())) {
					return "redirect:" + Global.getAdminPath() + "/home/?repage";
				} else {
					return "redirect:" + Global.getAdminPath() + "/workloan/workLoan/?repage";
				}
			}
			if ("bmzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workLoan.getProcessInstanceId(),2);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("fgld",2,office.getId(),"29",workLoan.getCreateBy());
			}else  if ("fgld".equals(taskDefKey)){
				users = UserUtils.getByProssType(workLoan.getProcessInstanceId(),3);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("cwzg", 3, office.getId(), "29", workLoan.getCreateBy());
			}else  if ("cw".equals(taskDefKey)){
				users = UserUtils.getByProssType(workLoan.getProcessInstanceId(),4);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("zjl",3,office.getId(),"29",workLoan.getCreateBy());
			}else  if ("zjl".equals(taskDefKey)){
				users = UserUtils.getByProssType(workLoan.getProcessInstanceId(),5);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("cwfgld",3,office.getId(),"29",workLoan.getCreateBy());
			}else  if ("cwzj".equals(taskDefKey)){
				users = UserUtils.getByProssType(workLoan.getProcessInstanceId(),6);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("cn",3,office.getId(),"29",workLoan.getCreateBy());
			}else if ("cn".equals(taskDefKey)){
				users = UserUtils.getByProssType(workLoan.getProcessInstanceId(),6);
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workLoan.getProcessInstanceId(),1);
			}
			String flag = workLoan.getAct().getFlag();
			if ("yes".equals(flag) &&(users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str =workLoanService.auditSave(workLoan,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workLoan.getHome()) && "home".equals(workLoan.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workloan/workLoan/?repage";
		}
	}

	/**
	 * 删除借款
	 */
	@RequiresPermissions("workloan:workLoan:del")
	@RequestMapping(value = "delete")
	public String delete(WorkLoan workLoan, RedirectAttributes redirectAttributes) {
		workLoanService.delete(workLoan);
		addMessage(redirectAttributes, "删除借款成功");
		return "redirect:"+Global.getAdminPath()+"/workloan/workLoan/?repage";
	}
	
	/**
	 * 批量删除借款
	 */
	@RequiresPermissions("workloan:workLoan:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workLoanService.delete(workLoanService.get(id));
		}
		addMessage(redirectAttributes, "删除借款成功");
		return "redirect:"+Global.getAdminPath()+"/workloan/workLoan/?repage";
	}
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkLoan workLoan,Model model) {
		model.addAttribute("processInstanceId", workLoan.getProcessInstanceId());
		return "modules/workloan/workTrack";
	}
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkLoan workLoan,RedirectAttributes redirectAttributes){
		try {
			WorkLoan reportData =workLoanService.get(workLoan.getId());
			if(reportData.getStatus().equals("5")){
				addMessage(redirectAttributes, "申请已审批通过，无法撤回");
			}else{
				workLoanService.cancelInvalidate(workLoan);
				addMessage(redirectAttributes, "申请撤回成功");
			}
		}catch (Exception e){
			logger.error("Exception e"+e);
			addMessage(redirectAttributes, "申请撤回失败");
		}
		return "redirect:"+Global.getAdminPath()+"/workloan/workLoan/?repage";
	}
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workloan:workLoan:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkLoan workLoan, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "借款"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkLoan> page = workLoanService.findPage(new Page<WorkLoan>(request, response, -1), workLoan);
    		new ExportExcel("借款", WorkLoan.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出借款记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workloan/workLoan/?repage";
    }

	/**
	 * 导入Excel数据

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

	/**
	 * 选择项目
	 */
	@RequestMapping(value = "selectproject")
	public String selectReproject(String userId,ProjectRecords projectId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectId.setCompany(UserUtils.getSelectCompany());
		WorkStaffBasicInfo workStaffBasicInfo=workStaffBasicInfoService.getAchives(userId);
		Page<ProjectRecords> page = projectRecordsService.findPageByRe(new Page<ProjectRecords>(request, response), projectId,workStaffBasicInfo.getUserId());
		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", projectId);
		model.addAttribute("allowInput", true);
		model.addAttribute("page", page);
		return "modules/sys/gridselectcallproject";
	}

	/**
	 * 获取项目信息
	 * @return
	 */
	@RequestMapping(value = "getProjectInfo")
	@ResponseBody
	public String getProjectInfo() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		ProjectRecords projectRecords = projectRecordsService.getQueryProjectUsers(obj);
		if(projectRecords != null){
			WorkContractInfo workContractInfo = projectRecords.getWorkContractInfo();
			if(workContractInfo!=null){
				map.put("contractPrice",workContractInfo.getContractPrice()==null?"":workContractInfo.getContractPrice());
				//合同未还款累计
				if(StringUtils.isNotBlank(workContractInfo.getId())){
					//未还款
					List<WorkLoan> list1 = workLoanService.findListByContract(workContractInfo.getId(),"3");
					double moneyCount= 0.00;//借款
					for(int i=0;i<list1.size();i++){
						WorkLoan workLoan = list1.get(i);
						if(StringUtils.isNotBlank(workLoan.getMoney())){
							moneyCount = moneyCount + Double.parseDouble(workLoan.getMoney());
						}
					}
					//部分还款
					List<WorkLoan> list2 = workLoanService.findListByContract(workContractInfo.getId(),"2");
					for(int i=0;i<list2.size();i++){
						WorkLoan workLoan = list2.get(i);
						if(StringUtils.isNotBlank(workLoan.getMoney()) && StringUtils.isNotBlank(workLoan.getRepay())){
							moneyCount = moneyCount + (Double.parseDouble(workLoan.getMoney()) - Double.parseDouble(workLoan.getRepay()));
						}
					}
					map.put("contractNotRepay",moneyCount+"");
				}else{
					map.put("contractNotRepay","");
				}
			}
		}
		return JsonMapper.toJsonString(map);
	}

	/**
	 * 获取项目信息
	 * @return
	 */
	@RequestMapping(value = "userInfo")
	@ResponseBody
	public String userInfo() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String id = request.getParameter("id");
		WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.getAchives(id);
		if(workStaffBasicInfo!=null && StringUtils.isNotBlank(workStaffBasicInfo.getUserId())){
			double moneyCount= workLoanService.getnotRepay(workStaffBasicInfo);
			map.put("notRepay",moneyCount+"");
		}else {
			map.put("notRepay", "");
		}
		return JsonMapper.toJsonString(map);
	}
}