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

import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
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.workinvoicedetail.entity.WorkInvoiceDetail;
import com.jeeplus.modules.workinvoicedetail.service.WorkInvoiceDetailService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workreceiptssettle.entity.WorkReceiptsSettle;
import com.jeeplus.modules.workreceiptssettle.entity.WorkReceiptsSettleDetail;
import com.jeeplus.modules.workreceiptssettle.service.WorkReceiptsSettleDetailService;
import com.jeeplus.modules.workreceiptssettle.service.WorkReceiptsSettleService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringEscapeUtils;
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.WebDataBinder;
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;

/**
 * 收入结算Controller
 * @author ssrh
 * @version 2018-06-28
 */
@Controller
@RequestMapping(value = "${adminPath}/workreceipts/workReceiptsSettle")
public class WorkReceiptsSettleController extends BaseController {

	@Autowired
	private WorkReceiptsSettleService workReceiptsSettleService;
    @Autowired
    private WorkInvoiceDetailService invoiceService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private WorkReceiptsSettleDetailService settleDetailService;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
        // 数字类型转换
        binder.registerCustomEditor(Double.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                DecimalFormat df =   new DecimalFormat("###,##0.00");
                try {
                    setValue(df.parse(text).doubleValue());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
    }
	
	@ModelAttribute
	public WorkReceiptsSettle get(@RequestParam(required=false) String id) {
		WorkReceiptsSettle entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workReceiptsSettleService.get(id);
		}
		if (entity == null){
			entity = new WorkReceiptsSettle();
		}
		return entity;
	}
	
	/**
	 * 收入结算列表页面
	 */
	@RequiresPermissions("workreceipts:workReceiptsSettle:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkReceiptsSettle workReceiptsSettle, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkReceiptsSettle> page = workReceiptsSettleService.findPage(new Page<WorkReceiptsSettle>(request, response), workReceiptsSettle); 
		model.addAttribute("page", page);
		return "modules/workreceiptssettle/workReceiptsSettleList";
	}

	/**
	 * 查看，增加，编辑收入结算表单页面
	 */
	@RequiresPermissions(value={"workreceipts:workReceiptsSettle:add","workreceipts:workReceiptsSettle:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkReceiptsSettle workReceiptsSettle, Model model) {
	    if(workReceiptsSettle.getIsNewRecord()){
	        workReceiptsSettle.setOffice(UserUtils.getSelectOffice());
	        workReceiptsSettle.setCompany(UserUtils.getSelectCompany());
	        workReceiptsSettle.setCreateBy(UserUtils.getUser());
	        workReceiptsSettle.setCreateDate(new Date());
        }else {
            workReceiptsSettle = workReceiptsSettleService.get(workReceiptsSettle.getId());
        }
		model.addAttribute("workReceiptsSettle", workReceiptsSettle);
		return "modules/workreceiptssettle/workReceiptsSettleForm";
	}

	@RequiresPermissions(value={"workreceipts:workReceiptsSettle:list"},logical=Logical.OR)
	@RequestMapping(value = "view")
	public String view(WorkReceiptsSettle workReceiptsSettle, Model model) {
        workReceiptsSettle = workReceiptsSettleService.get(workReceiptsSettle.getId());
		model.addAttribute("workReceiptsSettle", workReceiptsSettle);
		return "modules/workreceiptssettle/workReceiptsSettleView";
	}

	/**
	 * 保存收入结算
	 */
	@RequiresPermissions(value={"workreceipts:workReceiptsSettle:add","workreceipts:workReceiptsSettle:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkReceiptsSettle workReceiptsSettle, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workReceiptsSettle)){
			return form(workReceiptsSettle, model);
		}
		workReceiptsSettle.setState(ProjectStatusEnum.IN_APRL.getValue());
        String str = "";
        if(!workReceiptsSettle.getIsNewRecord()){//编辑表单保存
			WorkReceiptsSettle t = workReceiptsSettleService.get(workReceiptsSettle.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workReceiptsSettle, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            str = workReceiptsSettleService.saveSettle(t);//保存
		}else{//新增表单保存
            str = workReceiptsSettleService.saveSettle(workReceiptsSettle);//保存
		}

        if (StringUtils.isNotBlank(str)){
            addMessage(redirectAttributes, "保存收入结算失败:"+str);
        }else {
            addMessage(redirectAttributes, "保存收入结算成功");
        }
		return "redirect:"+Global.getAdminPath()+"/workreceipts/workReceiptsSettle/?repage";
	}
	
	/**
	 * 删除收入结算
	 */
	@RequiresPermissions("workreceipts:workReceiptsSettle:del")
	@RequestMapping(value = "delete")
	public String delete(WorkReceiptsSettle workReceiptsSettle, RedirectAttributes redirectAttributes) {
        if(5==workReceiptsSettle.getState()|| 2==workReceiptsSettle.getState()){
            if(5==workReceiptsSettle.getState()){
                addMessage(redirectAttributes, "收入结算已审批通过，无法删除");
                return "redirect:"+Global.getAdminPath()+"/workreceipts/workReceiptsSettle/?repage";
            }else{
                addMessage(redirectAttributes, "收入结算正在审核中，无法删除");
                return "redirect:"+Global.getAdminPath()+"/workreceipts/workReceiptsSettle/?repage";
            }
        }
		workReceiptsSettleService.delete(workReceiptsSettle);
		addMessage(redirectAttributes, "删除收入结算成功");
		return "redirect:"+Global.getAdminPath()+"/workreceipts/workReceiptsSettle/?repage";
	}
	
	/**
	 * 批量删除收入结算
	 */
	@RequiresPermissions("workreceipts:workReceiptsSettle:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workReceiptsSettleService.delete(workReceiptsSettleService.get(id));
		}
		addMessage(redirectAttributes, "删除收入结算成功");
		return "redirect:"+Global.getAdminPath()+"/workreceipts/workReceiptsSettle/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workreceipts:workReceiptsSettle:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkReceiptsSettle workReceiptsSettle, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "收入结算"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkReceiptsSettle> page = workReceiptsSettleService.findPage(new Page<WorkReceiptsSettle>(request, response, -1), workReceiptsSettle);
    		new ExportExcel("收入结算", WorkReceiptsSettle.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出收入结算记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workreceipts/workReceiptsSettle/?repage";
    }

	/**
	 * 导入Excel数据

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

    /**
     * 选择发票
     */
    @RequestMapping(value = "selectinvoice")
    public String selectcontractId(WorkInvoiceDetail invoice, String invoiceIds, String url, String type, String isTotal, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
        Office selectCompany = UserUtils.getSelectCompany();
        if(!"1".equals(selectCompany.getId())){
            if(StringUtils.isNotBlank(selectCompany.getParentIds())){
                String[] split = selectCompany.getParentIds().split(",");
                if(split.length>1) {
                    invoice.setComId(split[1]);
                }else {
                    invoice.setComId(selectCompany.getId());
                }
            }
        }
        if (StringUtils.isNotBlank(invoiceIds)){
            String[] split = invoiceIds.split(",");
            invoice.setExclusiveIds(split);
        }
        Page<WorkInvoiceDetail> page = invoiceService.findPageByCompany(new Page<WorkInvoiceDetail>(request, response),  invoice);
        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+"?invoiceIds="+invoiceIds);
        model.addAttribute("searchLabel", searchLabel);
        model.addAttribute("searchKey", searchKey);
        model.addAttribute("type", type);
        model.addAttribute("isTotal", isTotal);
        model.addAttribute("obj", invoice);
        model.addAttribute("page", page);
        return "modules/sys/gridselectInvoiceDetail";
    }

    /**
     * 工单执行（完成任务）
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(WorkReceiptsSettle workReceiptsSettle, Model model,
                            RedirectAttributes redirectAttributes) {
        try {
            // 对不同环节的业务逻辑进行操作
            String taskDefKey = workReceiptsSettle.getAct().getTaskDefKey();
            List<User> users = null;
            if ("scfgld".equals(taskDefKey)){
                users = UserUtils.getByProssType(workReceiptsSettle.getProcessInstanceId(),2);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("fpgly",3,workReceiptsSettle.getOffice().getId(),"7",workReceiptsSettle.getCreateBy());
            }else  if ("fpgly".equals(taskDefKey)){
                users = UserUtils.getByProssType(workReceiptsSettle.getProcessInstanceId(),3);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("cwzg", 1, workReceiptsSettle.getOffice().getId(), "7", workReceiptsSettle.getCreateBy());
            }else  if ("cwzg".equals(taskDefKey)){
                users = UserUtils.getByProssType(workReceiptsSettle.getProcessInstanceId(),4);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("zjl",1,workReceiptsSettle.getOffice().getId(),"7",workReceiptsSettle.getCreateBy());
            }else  if ("zjl".equals(taskDefKey)){
                users = UserUtils.getByProssType(workReceiptsSettle.getProcessInstanceId(),5);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("cwfgld",1,workReceiptsSettle.getOffice().getId(),"7",workReceiptsSettle.getCreateBy());
            }else  if ("cwfgld".equals(taskDefKey)){
                users = UserUtils.getByProssType(workReceiptsSettle.getProcessInstanceId(),6);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("cn",1,workReceiptsSettle.getOffice().getId(),"7",workReceiptsSettle.getCreateBy());
            }else if ("cn".equals(taskDefKey)){
                users = UserUtils.getByProssType(workReceiptsSettle.getProcessInstanceId(),6);
            }else if ("modifyApply".equals(taskDefKey)){
                users = UserUtils.getByProssType(workReceiptsSettle.getProcessInstanceId(),1);
            }
            String flag = workReceiptsSettle.getAct().getFlag();
            if ("yes".equals(flag) && (users==null || users.size()==0)){
                addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
            }else {
                String str = workReceiptsSettleService.auditSave(workReceiptsSettle,users);
                addMessage(redirectAttributes, str);
            }
        }catch (Exception e){
            addMessage(redirectAttributes, "审批失败:"+e);
        }

        if (StringUtils.isNotBlank(workReceiptsSettle.getHome()) && "home".equals(workReceiptsSettle.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/workreceipts/workReceiptsSettle/?repage";
        }
    }

    //	审批页面
    @RequestMapping(value = "projectRecordsAudit")
    public String workContractInfoAudit(Act act, WorkReceiptsSettle workReceiptsSettle, Model model) {

        if (act.getProcInsId() != null) {
            if (actTaskService.getProcIns(act.getProcInsId()) != null) {
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            } else {
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }
        if (act != null && StringUtils.isNotBlank(act.getTaskId())) {
            workReceiptsSettle.setAct(act);
            model.addAttribute("processInstanceId", workReceiptsSettle.getProcessInstanceId());
        }
        model.addAttribute("workReceiptsSettle", workReceiptsSettle);
        if("fpgly".equals(act.getTaskDefKey())){
            return "modules/workreceiptssettle/workReceiptsSettleKPAudit";
        }else if("cn".equals(act.getTaskDefKey())){
            return "modules/workreceiptssettle/workReceiptsSettleCNAudit";
        }else {
            return "modules/workreceiptssettle/workReceiptsSettleAudit";
        }
    }

    @RequestMapping(value = "getProcess")
    public String getProcess(WorkReceiptsSettle workReceiptsSettle, Model model,HttpServletRequest request){
        model.addAttribute("processInstanceId", workReceiptsSettle.getProcessInstanceId());
        return "modules/workreceiptssettle/workReceiptsSettleTask";
    }

    @ResponseBody
    @RequestMapping(value = "confirmPay")
    public AjaxJson confirmPay(String invoiceId, String settleId, String status){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            WorkInvoiceDetail invoiceDetail = invoiceService.get(invoiceId);
            if(invoiceDetail==null||StringUtils.isBlank(invoiceDetail.getTotalMoney())||StringUtils.isBlank(invoiceDetail.getIncomeMoney())||!Double.valueOf(invoiceDetail.getTotalMoney()).equals(Double.valueOf(invoiceDetail.getIncomeMoney()))){
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("更新付款状态失败：累计登记金额不等于价税合计");
                return  ajaxJson;
            }
            WorkReceiptsSettleDetail settleDetail = new WorkReceiptsSettleDetail();
            settleDetail.setSettleId(settleId);
            settleDetail.setStatus(status);
            if("1".equals(status)){
                settleDetail.setSettleDate(new Date());
            }
            settleDetail.setInvoice(new WorkInvoiceDetail(invoiceId));
            settleDetailService.updatePayStatus(settleDetail);
        }catch (Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("更新付款状态异常："+e.getMessage());
        }
        return ajaxJson;
    }

    @RequestMapping(value = "revoke")
    public String revoke(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        HashMap<String, String> requestMap = findRequestMap(request);
        String processInstanceId = requestMap.get("processInstanceId");
        String id = requestMap.get("id");
        try {
            WorkReceiptsSettle workReceiptsSettle = workReceiptsSettleService.get(id);
            if(5==workReceiptsSettle.getState()){
                addMessage(redirectAttributes, "收入结算已审批通过，无法撤回");
                return "redirect:"+Global.getAdminPath()+"/workreceipts/workReceiptsSettle/?repage";
            }
            workReceiptsSettleService.cancelProcess(workReceiptsSettle);

            addMessage(redirectAttributes, "撤回该收入结算成功");
        }catch (Exception e){
            logger.info(e.getMessage());
            addMessage(redirectAttributes, "撤回该收入结算失败");
        }
        return "redirect:" + Global.getAdminPath() + "/workreceipts/workReceiptsSettle/?repage";
    }

    @RequiresPermissions(value={"project:projectRecords:edit"},logical=Logical.OR)
    @RequestMapping(value = "modify")
    public String modify(WorkReceiptsSettle workReceiptsSettle, Model model,RedirectAttributes redirectAttributes) {
        workReceiptsSettle=workReceiptsSettleService.get(workReceiptsSettle.getId());
        ProcessInstance processInstance = actTaskService.getProcIns(workReceiptsSettle.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);
            workReceiptsSettle.setAct(act);
        }

        model.addAttribute("workReceiptsSettle", workReceiptsSettle);
        return "modules/workreceiptssettle/workReceiptsSettleModifyApply";
    }

    @RequestMapping("invoiceNum")
    @ResponseBody
    public AjaxJson invoiceNum(String invoiceNum,String comId,String id){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            boolean flag = workReceiptsSettleService.validateInvoiceNum(invoiceNum, comId,id);
            ajaxJson.getBody().put("isUsed",flag);
        }catch (Exception e){
            logger.error("校验发票号异常：",e);
            ajaxJson.setSuccess(false);
        }
        return ajaxJson;
    }
}