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

import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;

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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workinvoice.entity.WorkInvoice;
import com.jeeplus.modules.workinvoice.service.WorkInvoiceService;
import com.jeeplus.modules.workinvoicedetail.entity.WorkInvoiceDetail;
import com.jeeplus.modules.workinvoicedetail.service.WorkInvoiceDetailService;
import com.jeeplus.modules.workreceiptsregister.entity.*;
import com.jeeplus.modules.workreceiptsregister.service.WorkReceiptsRegisterDetailService;
import com.jeeplus.modules.workreceiptssettle.entity.WorkReceiptsSettleDetail;
import com.jeeplus.modules.workreceiptssettle.service.WorkReceiptsSettleDetailService;
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;
import com.jeeplus.modules.workreceiptsregister.service.WorkReceiptsRegisterService;

/**
 * 收入登记Controller
 * @author ssrh
 * @version 2018-05-21
 */
@Controller
@RequestMapping(value = "${adminPath}/workreceiptsregister/workReceiptsRegister")
public class WorkReceiptsRegisterController extends BaseController {
	@Autowired
	private WorkReceiptsRegisterService workReceiptsRegisterService;
	@Autowired
	private WorkReceiptsRegisterDetailService registerDetailService;
	@Autowired
    private WorkInvoiceDetailService invoiceService;
	@Autowired
    private WorkReceiptsSettleDetailService workReceiptsSettleDetailService;
    @Autowired
    private OfficeDao officeDao;

    @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 {
                    if(StringUtils.isNotBlank(text)) {
                        setValue(df.parse(text).doubleValue());
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
    }
	
	@ModelAttribute
	public WorkReceiptsRegister get(@RequestParam(required=false) String id) {
		WorkReceiptsRegister entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workReceiptsRegisterService.get(id);
		}
		if (entity == null){
			entity = new WorkReceiptsRegister();
		}
		return entity;
	}
	
	/**
	 * 收入登记列表页面
	 */
	@RequiresPermissions("workreceiptsregister:workReceiptsRegister:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkReceiptsRegister workReceiptsRegister, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkReceiptsRegister> page = workReceiptsRegisterService.findPage(new Page<WorkReceiptsRegister>(request, response), workReceiptsRegister);
		model.addAttribute("page", page);
		return "modules/workreceiptsregister/workReceiptsRegisterList";
	}

	/**
	 * 查看，增加，编辑收入登记表单页面
	 */
	@RequiresPermissions(value={"workreceiptsregister:workReceiptsRegister:add","workreceiptsregister:workReceiptsRegister:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkReceiptsRegister workReceiptsRegister, Model model) {
	    if (workReceiptsRegister !=null && workReceiptsRegister.getCompany()==null){
	        Office office = UserUtils.getSelectOffice();
	        Office company = null;
	        if(StringUtils.isNotBlank(office.getBranchOffice())){
                company = UserUtils.getBranchOfficeById(office.getBranchOffice());
            }else {
                company = UserUtils.getSelectCompany();
            }
            workReceiptsRegister.setCompany(company);
        }
        if(workReceiptsRegister !=null && workReceiptsRegister.getIsNewRecord()){
	        workReceiptsRegister.setStatus("0");
        }
		model.addAttribute("workReceiptsRegister", workReceiptsRegister);
		return "modules/workreceiptsregister/workReceiptsRegisterForm";
	}

    @RequiresPermissions(value={"workreceiptsregister:workReceiptsRegister:list"},logical=Logical.OR)
    @RequestMapping(value = "view")
    public String view(WorkReceiptsRegister workReceiptsRegister, Model model) {
        if (workReceiptsRegister !=null && workReceiptsRegister.getCompany()==null){
            workReceiptsRegister.setCompany(UserUtils.getSelectCompany());
        }
        if(workReceiptsRegister!=null&&StringUtils.isNotBlank(workReceiptsRegister.getId())){
            WorkReceiptsRegisterDetail registerDetail = new WorkReceiptsRegisterDetail();
            registerDetail.setRegisterId(workReceiptsRegister.getId());
            List<WorkReceiptsRegisterDetail> registerDetails = registerDetailService.findList(registerDetail);
            workReceiptsRegister.setRegisterDetailList(registerDetails);
        }
        model.addAttribute("workReceiptsRegister", workReceiptsRegister);
        return "modules/workreceiptsregister/workReceiptsDetailView";
    }

	/**
	 * 查看，增加，编辑收入登记表单页面
	 */
	@RequiresPermissions(value={"workreceiptsregister:workReceiptsRegister:edit"},logical=Logical.OR)
	@RequestMapping(value = "regist")
	public String regist(WorkReceiptsRegister workReceiptsRegister, Model model) {
	    if (workReceiptsRegister !=null && workReceiptsRegister.getCompany()==null){
	        workReceiptsRegister.setCompany(UserUtils.getSelectCompany());
        }
        if(workReceiptsRegister!=null&&StringUtils.isNotBlank(workReceiptsRegister.getId())){
            WorkReceiptsRegisterDetail registerDetail = new WorkReceiptsRegisterDetail();
            registerDetail.setRegisterId(workReceiptsRegister.getId());
            List<WorkReceiptsRegisterDetail> registerDetails = registerDetailService.findList(registerDetail);
            workReceiptsRegister.setRegisterDetailList(registerDetails);
        }
		model.addAttribute("workReceiptsRegister", workReceiptsRegister);
		return "modules/workreceiptsregister/workReceiptsDetailForm";
	}

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

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workreceiptsregister:workReceiptsRegister:edit")
    @RequestMapping(value = "ajaxImport", method=RequestMethod.POST)
    @ResponseBody
    public Object ajaxImportFile(MultipartFile file, RedirectAttributes redirectAttributes, Model model) {
        ResponseEntity<WorkReceiptsRegister> responseEntity = new ResponseEntity<>();
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkReceiptsRegister> list = ei.getDataList(WorkReceiptsRegister.class);
            Iterator<WorkReceiptsRegister> iterator = list.iterator();
            while (iterator.hasNext()){
                try{
                    WorkReceiptsRegister register = iterator.next();
                    if (!beanValidator(model, register)){
                        iterator.remove();
                        continue;
                    }
                    Double arrivalAmt = Double.valueOf(register.getArrivalAmt());
                    if(arrivalAmt==null||arrivalAmt==0){
                        iterator.remove();
                    }
                }catch (Exception e){
                    iterator.remove();
                    logger.error("解析导入文件异常。",e);
                }
            }
            responseEntity.setData(list);
		} catch (Exception e) {
		    logger.error("导入收入登记失败！",e);
			responseEntity.setCode(400);
			responseEntity.setMessage("导入收入登记失败！失败信息："+e.getMessage());
		}
		return responseEntity;
    }

    @RequiresPermissions("workreceiptsregister:workReceiptsRegister:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, Model model) {
        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<WorkReceiptsRegister> list = ei.getDataList(WorkReceiptsRegister.class);
            Iterator<WorkReceiptsRegister> iterator = list.iterator();
            while (iterator.hasNext()){
                try{
                    WorkReceiptsRegister register = iterator.next();
                    if (!beanValidator(model, register)){
                        iterator.remove();
                        continue;
                    }
                    Double arrivalAmt = Double.valueOf(register.getArrivalAmt());
                    if(arrivalAmt==null||arrivalAmt==0){
                        iterator.remove();
                    }
                }catch (Exception e){
                    iterator.remove();
                    logger.error("解析导入文件异常。",e);
                }
            }
            model.addAttribute("registers",list);
        } catch (Exception e) {
            logger.error("导入收入登记失败！",e);
        }
        return "modules/workreceiptsregister/workReceiptsImportView";
    }
    /**
	 * 保存导入Excel数据
	 */
	@RequiresPermissions("workreceiptsregister:workReceiptsRegister:edit")
    @RequestMapping(value = "saveImport", method=RequestMethod.POST)
    public String saveImport(ReceipterRequestEntity requestEntity, RedirectAttributes redirectAttributes) {
	    int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (WorkReceiptsRegister workReceiptsRegister : requestEntity.getRegisters()){
            if (StringUtils.isBlank(workReceiptsRegister.getClientAccno())){
                continue;
            }
            workReceiptsRegister.setStatus("0");
            try{
                workReceiptsRegisterService.save(workReceiptsRegister);
                successNum++;
            }catch(ConstraintViolationException ex){
                failureNum++;
            }catch (Exception ex) {
                failureNum++;
            }
        }
        if (failureNum>0){
            failureMsg.insert(0, "，失败 "+failureNum+" 条收入登记记录。");
        }
        addMessage(redirectAttributes, "已成功导入 "+successNum+" 条收入登记记录"+failureMsg);
		return "redirect:"+Global.getAdminPath()+"/workreceiptsregister/workReceiptsRegister/?repage";
    }
	
	/**
	 * 下载导入收入登记数据模板
	 */
	@RequiresPermissions("workreceiptsregister:workReceiptsRegister:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "收入登记数据导入模板.xlsx";
    		List<WorkReceiptsRegister> list = Lists.newArrayList(); 
    		new ExportExcel("收入登记数据", WorkReceiptsRegister.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workreceiptsregister/workReceiptsRegister/?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) {
        if(!"1".equals(UserUtils.getSelectCompany().getId())){
            invoice.setComId(UserUtils.getSelectCompany().getId());
        }
        if (StringUtils.isNotBlank(invoiceIds)){
            String[] split = invoiceIds.split(",");
            invoice.setExclusiveIds(split);
        }
        invoice.setState("正常");
        invoice.setBackSign("正常");
        Page<WorkInvoiceDetail> page = invoiceService.findPageWithDept(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";
    }


    /**
     * 保存收入登记信息
     */
    @RequiresPermissions(value={"workreceiptsregister:workReceiptsRegister:edit"},logical=Logical.OR)
    @RequestMapping(value = "saveDetail")
    public String saveDetail(WorkReceiptsRegister workReceiptsRegister, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, workReceiptsRegister)){
            return form(workReceiptsRegister, model);
        }
        if (workReceiptsRegister.getRegisterDetailList()!=null&&!workReceiptsRegister.getRegisterDetailList().isEmpty()){
            workReceiptsRegisterService.saveDetail(workReceiptsRegister);//保存登记明细信息
        }
        addMessage(redirectAttributes, "保存收入登记成功");
        return "redirect:"+Global.getAdminPath()+"/workreceiptsregister/workReceiptsRegister/?repage";
    }

    @ResponseBody
    @RequestMapping(value = "checkpaystatus")
    public AjaxJson checkPayStatus(String invoiceId){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            boolean flag = workReceiptsSettleDetailService.checkPayStatus(invoiceId);
            ajaxJson.getBody().put("payFlag",flag);
        }catch (Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("检测发票支付状态异常："+e.getMessage());
        }
        return ajaxJson;
    }
    @RequiresPermissions("workreceiptsregister:workReceiptsRegister:companylist")
    @RequestMapping(value = "companyList")
    public String companyList(WorkReceiptsRegisterCompany workReceiptsRegisterCompany, Model model,HttpServletRequest request,HttpServletResponse response){
        int roleMax = UserUtils.getSelectRoleMax();
        String view = "";
        switch (roleMax){
            case 4:
                Map<String,Object> orientData = new HashMap<String,Object>();
                List<String> xAxisData = new ArrayList<String>();
                Map<String,List<Double>> yAxisData = new HashMap<String,List<Double>>();
                if(StringUtils.isBlank(workReceiptsRegisterCompany.getExt())||"0".equals(workReceiptsRegisterCompany.getExt())) {
                    if(StringUtils.isNotBlank(workReceiptsRegisterCompany.getCompanyId())){
                        request.setAttribute("backState",1);
                    }
                    List<WorkReceiptsRegisterCompany> list = workReceiptsRegisterService.findCompanyList(workReceiptsRegisterCompany, orientData, xAxisData, yAxisData);
                    model.addAttribute("list", list);
                    model.addAttribute("colName", "分公司");
                }else {
                    List<WorkReceiptsRegisterMonth> list = workReceiptsRegisterService.findCompMonthList(workReceiptsRegisterCompany, orientData, xAxisData, yAxisData);
                    model.addAttribute("list", list);
                    model.addAttribute("colName", "月度");
                }
                model.addAttribute("orientData", orientData);
                model.addAttribute("xAxisData", xAxisData);
                model.addAttribute("yAxisData", yAxisData);
                break;
            case 3:
                if(isOffice()){//如果所在分公司下没有子公司
                    return "redirect:"+Global.getAdminPath()+"/workreceiptsregister/workReceiptsRegister/officelist?repage";
                }
                Map<String,Object> orientData1 = new HashMap<String,Object>();
                List<String> xAxisData1 = new ArrayList<String>();
                Map<String,List<Double>> yAxisData1 = new HashMap<String,List<Double>>();
                if(StringUtils.isBlank(workReceiptsRegisterCompany.getExt())||"0".equals(workReceiptsRegisterCompany.getExt())) {
                    if(StringUtils.isNotBlank(workReceiptsRegisterCompany.getCompanyId())){
                        request.setAttribute("backState",1);
                    }
                    List<WorkReceiptsRegisterCompany> list = workReceiptsRegisterService.findBranchList(workReceiptsRegisterCompany, orientData1, xAxisData1, yAxisData1);
                    model.addAttribute("list", list);
                    model.addAttribute("colName", "分公司");
                }else {
                    List<WorkReceiptsRegisterMonth> list = workReceiptsRegisterService.findCompMonthList(workReceiptsRegisterCompany, orientData1, xAxisData1, yAxisData1);
                    model.addAttribute("list", list);
                    model.addAttribute("colName", "月度");
                }
                model.addAttribute("orientData", orientData1);
                model.addAttribute("xAxisData", xAxisData1);
                model.addAttribute("yAxisData", yAxisData1);
                return "modules/workreceiptsregister/workReceiptsRegisterCompany";
            case 2:
                return "redirect:"+Global.getAdminPath()+"/workreceiptsregister/workReceiptsRegister/infolist?repage";
            default:
                model.addAttribute("list", new ArrayList<>());
                model.addAttribute("orientData", new HashMap<String,Object>());
                model.addAttribute("xAxisData", new ArrayList<String>());
                model.addAttribute("yAxisData", new HashMap<String,List<Double>>());
                break;
        }

        return "modules/workreceiptsregister/workReceiptsRegisterCompany";
    }

    @RequiresPermissions("workreceiptsregister:workReceiptsRegister:companylist")
    @RequestMapping(value = "officelist")
    public String officelist(WorkReceiptsRegisterOffice workReceiptsRegisterOffice, Model model,HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> orientData = new HashMap<String,Object>();
        List<String> xAxisData = new ArrayList<String>();
        Map<String,List<Double>> yAxisData = new HashMap<String,List<Double>>();
        if(StringUtils.isBlank(workReceiptsRegisterOffice.getExt())||"0".equals(workReceiptsRegisterOffice.getExt())) {
            if(StringUtils.isNotBlank(workReceiptsRegisterOffice.getCompanyId())){
                request.setAttribute("backState",1);
            }
            List<WorkReceiptsRegisterOffice> list = workReceiptsRegisterService.findOfficeList(workReceiptsRegisterOffice, orientData, xAxisData, yAxisData);
            model.addAttribute("list", list);
            model.addAttribute("colName", "部门");
        }else {
            List<WorkReceiptsRegisterMonth> list = workReceiptsRegisterService.findOfficeMonthList(workReceiptsRegisterOffice, orientData, xAxisData, yAxisData);
            model.addAttribute("list", list);
            model.addAttribute("colName", "月度");
        }
        model.addAttribute("orientData", orientData);
        model.addAttribute("xAxisData", xAxisData);
        model.addAttribute("yAxisData", yAxisData);
        return "modules/workreceiptsregister/workReceiptsRegisterOffice";
    }

    @RequiresPermissions("workreceiptsregister:workReceiptsRegister:companylist")
    @RequestMapping(value = "infolist")
    public String infolist(WorkReceiptsRegisterInfo workReceiptsRegisterInfo, Model model,HttpServletRequest request,HttpServletResponse response){
        Page<WorkReceiptsRegisterInfo> page = workReceiptsRegisterService.findInfoPage(new Page<WorkReceiptsRegisterInfo>(request,response),workReceiptsRegisterInfo);
        model.addAttribute("page", page);
        if(StringUtils.isNotBlank(workReceiptsRegisterInfo.getOfficeId())){
            request.setAttribute("backState",1);
        }
        return "modules/workreceiptsregister/workReceiptsRegisterInfo";
    }

    @RequiresPermissions("workreceiptsregister:workReceiptsRegister:companylist")
    @RequestMapping(value = "monthlist")
    public String monthlist(WorkReceiptsRegisterInfo workReceiptsRegisterInfo, Model model,HttpServletRequest request,HttpServletResponse response){
        Page<WorkReceiptsRegisterInfo> page = workReceiptsRegisterService.findInfoPage(new Page<WorkReceiptsRegisterInfo>(request,response),workReceiptsRegisterInfo);
        model.addAttribute("page", page);
        model.addAttribute("roleMax", UserUtils.getSelectRoleMax());
        return "modules/workreceiptsregister/workReceiptsRegisterInfo";
    }

    /**
     * 导出excel文件
     */
    @RequiresPermissions("workreceiptsregister:workReceiptsRegister:countExport")
    @RequestMapping(value = "exportCompany", method=RequestMethod.POST)
    public String exportCompany(WorkReceiptsRegisterCompany workReceiptsRegisterCompany, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "收入统计"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            if(StringUtils.isBlank(workReceiptsRegisterCompany.getExt())||"0".equals(workReceiptsRegisterCompany.getExt())) {
                List<WorkReceiptsRegisterCompany> list = workReceiptsRegisterService.findCompanyList(workReceiptsRegisterCompany, null, null, null);
                new ExportExcel("收入统计", WorkReceiptsRegisterCompany.class).setDataList(list).write(response, fileName).dispose();
            }else {
                List<WorkReceiptsRegisterMonth> list = workReceiptsRegisterService.findCompMonthList(workReceiptsRegisterCompany, null, null, null);
                new ExportExcel("收入统计", WorkReceiptsRegisterMonth.class).setDataList(list).write(response, fileName).dispose();
            }

            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出收入统计记录失败！失败信息："+e.getMessage());
        }
        return "redirect:"+Global.getAdminPath()+"/workreceiptsregister/workReceiptsRegister/companyList?repage";
    }
    /**
     * 导出excel文件
     */
    @RequiresPermissions("workreceiptsregister:workReceiptsRegister:countExport")
    @RequestMapping(value = "exportOffice", method=RequestMethod.POST)
    public String exportOffice(WorkReceiptsRegisterOffice workReceiptsRegisterOffice, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "收入统计"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            if(StringUtils.isBlank(workReceiptsRegisterOffice.getExt())||"0".equals(workReceiptsRegisterOffice.getExt())) {
                List<WorkReceiptsRegisterOffice> list = workReceiptsRegisterService.findOfficeList(workReceiptsRegisterOffice, null, null, null);
                new ExportExcel("收入统计", WorkReceiptsRegisterCompany.class).setDataList(list).write(response, fileName).dispose();
            }else {
                List<WorkReceiptsRegisterMonth> list = workReceiptsRegisterService.findOfficeMonthList(workReceiptsRegisterOffice, null, null, null);
                new ExportExcel("收入统计", WorkReceiptsRegisterMonth.class).setDataList(list).write(response, fileName).dispose();
            }

            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出收入统计记录失败！失败信息："+e.getMessage());
        }
        return "redirect:"+Global.getAdminPath()+"/workreceiptsregister/workReceiptsRegister/officelist?repage";
    }
    /**
     * 导出excel文件
     */
    @RequiresPermissions("workreceiptsregister:workReceiptsRegister:countExport")
    @RequestMapping(value = "exportInfo", method=RequestMethod.POST)
    public String exportInfo(WorkReceiptsRegisterInfo workReceiptsRegisterInfo, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "收入统计"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkReceiptsRegisterInfo> page = workReceiptsRegisterService.findInfoPage(new Page<WorkReceiptsRegisterInfo>(request,response,-1),workReceiptsRegisterInfo);
            new ExportExcel("收入统计", WorkReceiptsRegisterInfo.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出收入统计记录失败！失败信息："+e.getMessage());
        }
        return "redirect:"+Global.getAdminPath()+"/workreceiptsregister/workReceiptsRegister/infolist?repage";
    }
    //分公司下是否存在子公司
    public Boolean isOffice(){
        String companyId= UserUtils.getSelectBranchOffice();
        List<Office>office=	officeDao.getAllBranch(companyId);
        if(office!=null&&office.size()>0){
            return false;
        }else{
            return true;
        }
    }
}