package com.ssj.sys.controller;

import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.service.sys.finance.service.IFinanceService;
import com.ssj.service.sys.fx.service.DeviceBalanceService;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.sys.util.thirdparty.excel.CustomizeToExcel;
import com.ssj.sys.util.thirdparty.excel.ExcelColumn;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("sys/finance")
public class FinanceReportController extends BaseController {

    @Autowired
    private IFinanceService financeService;

    @Autowired
    private MerchantService merchantService;
    
    @Autowired
    private DeviceBalanceService deviceBalanceService;

    //小塾使用情况总表
    @RequestMapping("/littleShuAllList")
    public String littleShuAllList(Model model) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("month", DateHelper.format(new Date(),"yyyy-MM"));
        addPostcodes(params);
        List<Map<String,Object>> list = financeService.findLittleShuAllList(params);
        model.addAttribute("list", list);
        return "sys/finance/allList";
    }

    //小塾某月使用情况总表
    @RequestMapping("/littleMonthDetailList")
    public String littleMonthDetailList(Model model,
                                   @RequestParam(required = false, defaultValue = "10") int pageSize,
                                   @RequestParam(required = false, defaultValue = "1") int pageNo) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("month", request.getParameter("month")==null?DateHelper.format(new Date(),"yyyy-MM"):request.getParameter("month"));
        addPostcodes(params);
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = financeService.littleMonthDetailList(params, initPage(pageNo, pageSize));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/finance/allList2";
    }

    //小塾使用情况总表
    @RequestMapping("/littleDetailList")
    public String littleDetailList(Model model,
                                        @RequestParam(required = false, defaultValue = "10") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("startMonth", request.getParameter("startMonth")==null?"":request.getParameter("startMonth"));
        params.put("endMonth", request.getParameter("endMonth")==null?"":request.getParameter("endMonth"));
        params.put("level", request.getParameter("level")==null?"":request.getParameter("level"));
        params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
        addPostcodes(params);
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = financeService.littleDetailList(params, initPage(pageNo, pageSize));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/finance/allList3";
    }

    @RequestMapping(value = "/export1", method = RequestMethod.POST)
    @ResponseBody
    public void export1(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="小塾币使用情况表-各月";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("month", DateHelper.format(new Date(),"yyyy-MM"));
            addPostcodes(params);
            List<Map<String,Object>> list = financeService.findLittleShuAllList(params);
            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("月份", "months", 20));
            myColumns3.add(new ExcelColumn("上月结存", "last_left", 20));
            myColumns3.add(new ExcelColumn("本月新增", "add_total", 20));
            myColumns3.add(new ExcelColumn("本月消耗", "cost_count", 20));
            myColumns3.add(new ExcelColumn("本月结存", "this_left", 20));
            CustomizeToExcel.downFile(myColumns3, list, os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }

    @RequestMapping(value = "/export2", method = RequestMethod.POST)
    @ResponseBody
    public void export2( HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="小塾币使用情况表-各馆";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
//          response.setContentType("application/msexcel"); //定义输出类型
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("month", request.getParameter("month")==null?DateHelper.format(new Date(),"yyyy-MM"):request.getParameter("month"));
            addPostcodes(params);
            Page<Map<String,Object>> page = financeService.littleMonthDetailList(params, initPage(1, 100000));
            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            HttpSession session = request.getSession();
            Admin admin =(Admin) session.getAttribute("admin");
            Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
            if("SSJ-FX".equals(merchant.getOrgCode())){
                myColumns3.add(new ExcelColumn("商户账号", "pos_code", 20));
                myColumns3.add(new ExcelColumn("商户编码", "org_code", 20));
                myColumns3.add(new ExcelColumn("商户类别", "type", 20));
                myColumns3.add(new ExcelColumn("商户级别", "level", 20));
                myColumns3.add(new ExcelColumn("单位名称", "unit_name2", 20));
            }
            myColumns3.add(new ExcelColumn("馆/机构名称", "unit_name", 20));
            myColumns3.add(new ExcelColumn("上月结存", "last_left", 20));
            myColumns3.add(new ExcelColumn("本月新增", "add_total", 20));
            myColumns3.add(new ExcelColumn("本月总消耗", "cost_count", 20));
            myColumns3.add(new ExcelColumn("本月消耗：有小塾消费", "cost_count0", 20));
            myColumns3.add(new ExcelColumn("本月消耗：无小塾消费", "cost_count1", 20));
            myColumns3.add(new ExcelColumn("本月消耗：服务扣除", "cost_count2", 20));
            myColumns3.add(new ExcelColumn("本月消耗：分配下级", "cost_count3", 20));
            myColumns3.add(new ExcelColumn("本月结存", "this_left", 20));
            CustomizeToExcel.downFile(myColumns3, page.getContent(), os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }

    @RequestMapping(value = "/export3", method = RequestMethod.POST)
    @ResponseBody
    public void export3( HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="小塾币使用情况表-各馆各月";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
//          response.setContentType("application/msexcel"); //定义输出类型
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("startMonth", request.getParameter("startMonth")==null?"":request.getParameter("startMonth"));
            params.put("endMonth", request.getParameter("endMonth")==null?"":request.getParameter("endMonth"));
            params.put("level", request.getParameter("level")==null?"":request.getParameter("level"));
            params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
            addPostcodes(params);
            Page<Map<String,Object>> page = financeService.littleDetailList(params, initPage(1, 100000));
            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("月份", "months", 20));
            HttpSession session = request.getSession();
            Admin admin =(Admin) session.getAttribute("admin");
            Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
            if("SSJ-FX".equals(merchant.getOrgCode())){
                myColumns3.add(new ExcelColumn("商户账号", "pos_code", 20));
                myColumns3.add(new ExcelColumn("商户编码", "org_code", 20));
                myColumns3.add(new ExcelColumn("商户类别", "type", 20));
                myColumns3.add(new ExcelColumn("单位名称", "unit_name2", 20));
            }
            myColumns3.add(new ExcelColumn("商户级别", "level", 20));
            myColumns3.add(new ExcelColumn("馆/机构名称", "unit_name", 20));
            myColumns3.add(new ExcelColumn("上月结存", "last_left", 20));
            myColumns3.add(new ExcelColumn("本月新增", "add_total", 20));
            myColumns3.add(new ExcelColumn("本月总消耗", "cost_count", 20));
            myColumns3.add(new ExcelColumn("本月消耗：有小塾消费", "cost_count0", 20));
            myColumns3.add(new ExcelColumn("本月消耗：无小塾消费", "cost_count1", 20));
            myColumns3.add(new ExcelColumn("本月消耗：服务扣除", "cost_count2", 20));
            myColumns3.add(new ExcelColumn("本月消耗：分配下级", "cost_count3", 20));
            myColumns3.add(new ExcelColumn("本月结存", "this_left", 20));
            CustomizeToExcel.downFile(myColumns3, page.getContent(), os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }

    private void addPostcodes(Map<String, Object> params){
        HttpSession session = request.getSession();
        Admin admin =(Admin) session.getAttribute("admin");
        Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
        if(merchant!=null && !merchant.getOrgCode().equals("SSJ-FX")){
            params.put("posCode", merchant.getOrgCode());
        }else{
            params.put("posCode", "");
        }
    }
    
    
    
    
    
    
    //小塾使用情况总表
    @RequestMapping("/balanceLossDetailList")
    public String balanceLossDetailList(Model model,
                                        @RequestParam(required = false, defaultValue = "10") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo) {

        Map<String, Object> params = new HashMap<String, Object>();
            
        params.put("startMonth", request.getParameter("startMonth")==null? new SimpleDateFormat("yyyy-MM").format(new Date()):request.getParameter("startMonth"));
        params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
        addPostcodes(params);
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = financeService.findDeviceBalanceList(params, initPage(pageNo, pageSize));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/finance/allList5";
    }
    
    
    
    //生成旧月份数据
  	@RequestMapping("/runBalanceLoss")
  	@ResponseBody
  	public Response allot(Model model,String balanceMonth)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(balanceMonth)){
			deviceBalanceService.runCountDeviceBalance(balanceMonth);
			response.success("生成成功");
		}else{
			response.failure("balanceMonth不合法");
		}
	    return response;
	 }

    @RequestMapping(value = "/export4", method = RequestMethod.POST)
    @ResponseBody
    public void export4( HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="小塾流动情况-各馆结存/流失";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("startMonth", request.getParameter("startMonth")==null? new SimpleDateFormat("yyyy-MM").format(new Date()):request.getParameter("startMonth"));
            params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
            addPostcodes(params);
            Page<Map<String,Object>> page = financeService.findDeviceBalanceList(params, initPage(1, 100000));
            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("月份", "balance_month", 20));
            /**
             * 商户账号、商户编码、单位名称、商户级别
             */
            myColumns3.add(new ExcelColumn("馆/机构名称", "league_name", 20));
            myColumns3.add(new ExcelColumn("商户账号", "pos_code", 20));
            myColumns3.add(new ExcelColumn("商户编码", "org_code", 20));
            myColumns3.add(new ExcelColumn("商户级别", "level", 20));
            myColumns3.add(new ExcelColumn("单位名称", "unit_name2", 20));
            myColumns3.add(new ExcelColumn("上月有小塾结存", "last_have_balance", 20));
            myColumns3.add(new ExcelColumn("上月无小塾结存", "last_not_balance", 20));
            myColumns3.add(new ExcelColumn("本月有小塾流失", "cur_have_loss", 20));
            myColumns3.add(new ExcelColumn("本月无小塾流失", "cur_not_loss", 20));
            myColumns3.add(new ExcelColumn("有小塾本月新增", "cur_have_add", 20));
            myColumns3.add(new ExcelColumn("无小塾本月新增", "cur_not_add", 20));
            myColumns3.add(new ExcelColumn("有小塾本月合计", "cur_have_count", 20));
            myColumns3.add(new ExcelColumn("无小塾本月合计", "cur_not_count", 20));
            CustomizeToExcel.downFile(myColumns3, page.getContent(), os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }
    
    
    
    
    
    //小塾币情况表-结算,按月进行筛选
    @RequestMapping("/balanceConsumeDetailList")
    public String balanceConsumeDetailList(Model model,
                                        @RequestParam(required = false, defaultValue = "30") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo) {

        Map<String, Object> params = new HashMap<String, Object>();
            
        params.put("startMonth", request.getParameter("startMonth")==null? new SimpleDateFormat("yyyy-MM").format(new Date()):request.getParameter("startMonth"));
        params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
        addPostcodes(params);
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = financeService.balanceConsumeDetailList(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
        for (Map<String, Object> map : list) {
        	if(map.containsKey("type")) {
        		if(map.get("type")==null || (Integer.parseInt(map.get("type").toString())!=1 && Integer.parseInt(map.get("type").toString())!=5)){
        			map.put("external_unit_name", map.get("unit_name"));
        			map.put("unit_name", "");
        			map.put("external_cons_count", map.get("cons_count"));
        			map.put("cons_count", "");
        		}
        	}
		}
        
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/finance/allList4";
    }
    
    

    //小塾币情况表-结算,按月进行筛选
    @RequestMapping("/balanceConsumeDetailList_New")
    public String balanceConsumeDetailList_New(Model model,
                                        @RequestParam(required = false, defaultValue = "30") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo) {

        Map<String, Object> params = new HashMap<String, Object>();
            
        params.put("startMonth", request.getParameter("startMonth")==null? new SimpleDateFormat("yyyy-MM").format(new Date()):request.getParameter("startMonth"));
        params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
        addPostcodes(params);
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = financeService.balanceConsumeDetailList_New(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
        for (Map<String, Object> map : list) {
        	if(Integer.parseInt(map.get("meal_type").toString())==4) {
        		map.put("price_1", "0");
        	}else {
        		map.put("price_1", "350");
        	}
          	map.put("sum_price_1", "0");
        	map.put("sum_price_2", "0");
        	map.put("sum_price_3", "0");
        	
        	if(map.containsKey("type")) {
        		if(map.get("type")==null || Integer.parseInt(map.get("type").toString())!=5){
        			map.put("external_unit_name", map.get("unit_name"));
        			map.put("unit_name", "");
        		}
        	}
        	
        	map.put("count_1_m", "");
        	map.put("count_2_m", "");
        	
        	if(map.containsKey("count_1")) {
        		if(Integer.parseInt(map.get("count_1").toString())>0) {
        			map.put("count_1_m", map.get("balance_month") );
        			map.put("sum_price_1", map.get("price")!=null && StringUtils.isNotEmpty(map.get("price").toString()) ? 
        					new BigDecimal(map.get("price").toString()).doubleValue()*
        					0.4  
        					: 0);
        		}
        	}
        	
        	if(map.containsKey("count_2")) {
        		if(Integer.parseInt(map.get("count_2").toString())>0) {
        			map.put("count_2_m", map.get("balance_month") );
        			map.put("sum_price_2", map.get("price_1")!=null && StringUtils.isNotEmpty(map.get("price_1").toString()) ? 
        					new BigDecimal(map.get("price_1").toString()).doubleValue()*
        					new BigDecimal(map.get("count_2").toString()).intValue()
        					*0.4 
        					: 0);
        		}else {
        			map.put("price_1", "0");
        		}
        	}
        	
        	map.put("sum_price_3", new BigDecimal(map.get("sum_price_1").toString()).doubleValue()+new BigDecimal(map.get("sum_price_2").toString()).doubleValue());

		}
        
        
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/finance/allList6";
    }
    
    
    
    
    @RequestMapping(value = "/export5", method = RequestMethod.POST)
    @ResponseBody
    public void export5( HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="小塾币使用情况-结算(旧模式)";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("startMonth", request.getParameter("startMonth")==null? new SimpleDateFormat("yyyy-MM").format(new Date()):request.getParameter("startMonth"));
            params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
            addPostcodes(params);
            Page<Map<String,Object>> page = financeService.balanceConsumeDetailList(params, initPage(1, 100000));
            
            List<Map<String,Object>> list=page.getContent();
            for (Map<String, Object> map : list) {
            	if(map.containsKey("type")) {
            		if(map.get("type")==null || (Integer.parseInt(map.get("type").toString())!=1 && Integer.parseInt(map.get("type").toString())!=5)){
            			map.put("external_unit_name", map.get("unit_name"));
            			map.put("unit_name", "");
            			map.put("external_cons_count", map.get("cons_count"));
            			map.put("cons_count", "");
            		}
            	}
    		}
            
            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("月份", "balance_month", 20));
            /**
             * 商户账号、商户编码、单位名称、商户级别
             */
            myColumns3.add(new ExcelColumn("商户账号", "pos_code", 20));
            myColumns3.add(new ExcelColumn("商户编码", "org_code", 20));
            myColumns3.add(new ExcelColumn("商户级别", "level_name", 20));
            myColumns3.add(new ExcelColumn("端口数量", "port_num", 20));
            myColumns3.add(new ExcelColumn("签约商户", "unit_name", 20));
            myColumns3.add(new ExcelColumn("非签约商户", "external_unit_name", 20));
            //myColumns3.add(new ExcelColumn("商户绑定机构", "league_name", 20));
           
            myColumns3.add(new ExcelColumn("签约消耗塾币", "cons_count", 20));
            myColumns3.add(new ExcelColumn("非签约消耗塾币", "external_cons_count", 20));
            
            myColumns3.add(new ExcelColumn("最低消费塾币", "deduct_count", 20));
            myColumns3.add(new ExcelColumn("服务：签约单价", "unit_price", 20));
           
            myColumns3.add(new ExcelColumn("总消费塾币数量", "port_count", 20));
//            myColumns3.add(new ExcelColumn("硬件数量", "derver_count", 20));
            myColumns3.add(new ExcelColumn("收入合计", "unit_price_count", 20));
            myColumns3.add(new ExcelColumn("成本合计", "cost_count", 20));
            
            CustomizeToExcel.downFile(myColumns3, list, os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }
    
    
    
    @RequestMapping(value = "/export6", method = RequestMethod.POST)
    @ResponseBody
    public void export6( HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="小塾币使用情况-结算(新模式)";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("startMonth", request.getParameter("startMonth")==null? new SimpleDateFormat("yyyy-MM").format(new Date()):request.getParameter("startMonth"));
            params.put("unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
            addPostcodes(params);
            Page<Map<String,Object>> page = financeService.balanceConsumeDetailList_New(params, initPage(1, 100000));
            
            List<Map<String,Object>> list=page.getContent();
            for (Map<String, Object> map : list) {
            	if(Integer.parseInt(map.get("meal_type").toString())==4) {
            		map.put("price_1", "0");
            	}else {
            		map.put("price_1", "350");
            	}
              	map.put("sum_price_1", "0");
            	map.put("sum_price_2", "0");
            	map.put("sum_price_3", "0");
            	
            	if(map.containsKey("type")) {
            		if(map.get("type")==null || Integer.parseInt(map.get("type").toString())!=5){
            			map.put("external_unit_name", map.get("unit_name"));
            			map.put("unit_name", "");
            		}
            	}
            	
            	if(map.containsKey("meal_type")) {
            		if(map.get("meal_type")!=null){
            			if(Integer.parseInt(map.get("meal_type").toString())==1){
            				map.put("meal_type", "优选套餐");
            			}else if(Integer.parseInt(map.get("meal_type").toString())==2){
            				map.put("meal_type", "VIP套餐");
            			}else if(Integer.parseInt(map.get("meal_type").toString())==3){
            				map.put("meal_type", "尊享套餐");
            			}else if(Integer.parseInt(map.get("meal_type").toString())==4){
            				map.put("meal_type", "校园服务");
            			}else {
            				map.put("meal_type", "");
            			}
            		
            		}
            	}
            	
            	if(map.containsKey("sign_type")) {
            		if(map.get("sign_type")!=null){
            			if(Integer.parseInt(map.get("sign_type").toString())==1){
            				map.put("sign_type", "服务包1");
            			}else if(Integer.parseInt(map.get("sign_type").toString())==2){
            				map.put("sign_type", "服务包2");
            			}else if(Integer.parseInt(map.get("sign_type").toString())==3){
            				map.put("sign_type", "服务包3");
            			}else if(Integer.parseInt(map.get("sign_type").toString())==4){
            				map.put("sign_type", "服务包4");
            			}else if(Integer.parseInt(map.get("sign_type").toString())==5){
            				map.put("sign_type", "服务包5");
            			}else {
            				map.put("sign_type", "");
            			}
            		
            		}
            	}
            	
            	map.put("count_1_m", "");
            	map.put("count_2_m", "");
            	
            	if(map.containsKey("count_1")) {
            		if(Integer.parseInt(map.get("count_1").toString())>0) {
            			map.put("count_1_m", map.get("balance_month") );
            			map.put("sum_price_1", map.get("price")!=null && StringUtils.isNotEmpty(map.get("price").toString()) ? 
            					new BigDecimal(map.get("price").toString()).doubleValue()*
            					0.4  
            					: 0);
            		}else {
            			map.put("price", "0");
            		}
            	}
            	
            	if(map.containsKey("count_2")) {
            		if(Integer.parseInt(map.get("count_2").toString())>0) {
            			map.put("count_2_m", map.get("balance_month") );
            			map.put("sum_price_2", map.get("price_1")!=null && StringUtils.isNotEmpty(map.get("price_1").toString()) ? 
            					new BigDecimal(map.get("price_1").toString()).doubleValue()*
            					new BigDecimal(map.get("count_2").toString()).intValue()
            					*0.4 
            					: 0);
            		}else {
            			map.put("price_1", "0");
            		}
            	}
            	
            	map.put("sum_price_3", new BigDecimal(map.get("sum_price_1").toString()).doubleValue()+new BigDecimal(map.get("sum_price_2").toString()).doubleValue());
    		}
            
            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("月份", "balance_month", 20));
            myColumns3.add(new ExcelColumn("商户账号", "pos_code", 20));
            myColumns3.add(new ExcelColumn("商户编码", "org_code", 20));
            myColumns3.add(new ExcelColumn("签约商户", "unit_name", 20));
           
            myColumns3.add(new ExcelColumn("套餐名称", "meal_type", 20));
            myColumns3.add(new ExcelColumn("服务包名称", "sign_type", 20));
            
            myColumns3.add(new ExcelColumn("服务包/月金额", "price", 20));
//            myColumns3.add(new ExcelColumn("总有效服务数", "sum_1", 20));
//            myColumns3.add(new ExcelColumn("总结束服务数", "sum_2", 20));
            myColumns3.add(new ExcelColumn("服务包/结算月份", "count_1_m", 20));
            
            myColumns3.add(new ExcelColumn("服务包应结算金额", "sum_price_1", 20));
            
            myColumns3.add(new ExcelColumn("加油包/月金额", "price_1", 20));
//            myColumns3.add(new ExcelColumn("加油包/有效服务数", "sum_3", 20));
//            myColumns3.add(new ExcelColumn("加油包/结束服务数", "sum_4", 20));
            myColumns3.add(new ExcelColumn("加油包/结算月份", "count_2_m", 20));
            myColumns3.add(new ExcelColumn("加油包/结算数量", "count_2", 20));
            
            myColumns3.add(new ExcelColumn("加油包应结算金额", "sum_price_2", 20));
            myColumns3.add(new ExcelColumn("总应结算金额", "sum_price_3", 20));
            
            CustomizeToExcel.downFile(myColumns3, list, os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }
    
    
    
    
    
}
