package com.ssj.sys.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson.JSON;
import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.fx.domain.*;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.sys.role.domain.Role;
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.framework.core.util.ResponseEntity;
import com.ssj.service.sys.fx.service.*;
import com.ssj.service.sys.role.service.AdminService;
import com.ssj.service.sys.role.service.RoleService;
import com.ssj.service.sys.sort.service.SortService;
import com.ssj.service.weixin.library.service.LibBookLockingService;
import com.ssj.service.weixin.sales.service.LibStaffingService;
import com.ssj.sys.util.thirdparty.excel.CustomizeToExcel;
import com.ssj.sys.util.thirdparty.excel.ExcelColumn;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
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 java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

@RequestMapping("sys/bookList")
@Controller
public class BookListController extends BaseController {

    @Autowired
    private LibBookLockingService lockingService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private LibStaffingService libStaffingService;

    @Autowired
    private DevicePartsService devicePartsService;

    @Autowired
    private MaterielService materielService;

    @Autowired
    private MaterielTemplateService materielTemplateService;

    @Autowired
    private SortService sortService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private MaterielOffService materielOffService;

    @Autowired
    private MaterielOffDetailService materielOffDetailService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MaterielHomeService materielHomeService;

    @RequestMapping("/salseCountList")
    public String pageList(Model model,@RequestParam(required = false, defaultValue = "10") int pageSize,
                           @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("saleName",request.getParameter("saleName")==null?"":request.getParameter("saleName"));//图书馆
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= devicePartsService.findSaleCountList(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/fx/salecount";
    }


    @RequestMapping("/salsetList")
    /**
     * 订单明细
     */
    public String salsetList(Model model,@RequestParam(required = false, defaultValue = "10") int pageSize,
                             @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderNo",request.getParameter("orderNo")==null?"":request.getParameter("orderNo"));//客户
        params.put("startDate",request.getParameter("startDate")==null?"":request.getParameter("startDate")); //月份
        params.put("endDate",request.getParameter("endDate")==null?"":request.getParameter("endDate")); //月份
        Merchant merchant=merchantService.getMerchantByPosCode(loginName());
        if(merchant.getOrgCode().equals("SSJ-FX")){
            params.put("showType","1");
            model.addAttribute("admin", 1);
            model.addAttribute("unitList", merchantService.findMerchantByPage());
            params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
        }else{
            List<Merchant> listMerchant = merchantService.getMerchantByParentPosCode(merchant.getPosCode());
            //看是否有下级
            if(listMerchant == null || listMerchant.size()==0){ //无下级看自身数据
                params.put("showType","1");
                model.addAttribute("unitList", new ArrayList<Merchant>().add(merchant));
                params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
            }else{
                if(merchant.getLevel()==null){
                    params.put("showType","2"); //只看下级
                    params.put("LIKE_orgCode",merchant==null ?"": merchant.getPosCode());
                }else{
                    params.put("showType","1"); //有下级就只看下级和自身数据
                    params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
                }
                model.addAttribute("unitList", listMerchant);
            }

            model.addAttribute("admin", 2);
        }


        params.put("order_type",request.getParameter("order_type")==null?"":request.getParameter("order_type"));
        params.put("unit_name",request.getParameter("unit_name")==null?"":request.getParameter("unit_name"));
        params.put("seachDerver",request.getParameter("seachDerver")==null?"":request.getParameter("seachDerver"));

        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= devicePartsService.salsetList(params, initPage(pageNo,pageSize));
        sp.setRowCnt((int)page.getTotalElements());
        List<Map<String, Object>> list = page.getContent();
        model.addAttribute("list", list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

        return "sys/fx/salemouth";
    }

    @RequestMapping("/salseAreatList")
    /**
     *区域
     */
    public String salseAreatList(Model model,@RequestParam(required = false, defaultValue = "10") int pageSize,
                                 @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("name",request.getParameter("name")==null?"":request.getParameter("name"));//客户
//        params.put("product",request.getParameter("product")==null?"":request.getParameter("product")); //到馆还是离馆
        params.put("area",request.getParameter("area")==null?"":request.getParameter("area")); //到馆还是离馆
        params.put("startDate",request.getParameter("startDate")==null?"":request.getParameter("startDate")); //月份
//        params.put("endDate",request.getParameter("endDate")==null?"":request.getParameter("endDate")); //月份
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= devicePartsService.salseMouthMoneytList(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/fx/salearea";
    }

    /**
     *销售月份维度
     */
    @RequestMapping("/salseMouthtList")
    public String salseMouthtList(Model model,@RequestParam(required = false, defaultValue = "10") int pageSize,
                                  @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name",request.getParameter("name")==null?"":request.getParameter("name"));//客户
//        params.put("product",request.getParameter("product")==null?"":request.getParameter("product")); //到馆还是离馆
//        params.put("area",request.getParameter("area")==null?"":request.getParameter("area")); //到馆还是离馆
        params.put("startDate",request.getParameter("startDate")==null?"":request.getParameter("startDate")); //月份
//        params.put("endDate",request.getParameter("endDate")==null?"":request.getParameter("endDate")); //月份
        Merchant merchant=merchantService.getMerchantByPosCode(loginName());
        if(merchant.getOrgCode().equals("SSJ-FX")){
            params.put("showType","1");
            model.addAttribute("admin", 1);
            params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
        }else{
            List<Merchant> listMerchant = merchantService.getMerchantByParentPosCode(merchant.getPosCode());
            //看是否有下级
            if(listMerchant == null || listMerchant.size()==0){ //无下级看自身数据
                params.put("showType","1");
                params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
            }else{
                if(merchant.getLevel()==null){
                    params.put("showType","2"); //只看下级
                    params.put("LIKE_orgCode",merchant==null ?"": merchant.getPosCode());
                }else{
                    params.put("showType","1"); //有下级就只看下级和自身数据
                    params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
                }

            }
            model.addAttribute("admin", 2);
        }

        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= devicePartsService.salseMouthtList(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/fx/salemouth2";
    }

    @RequestMapping("/saleList")
    /**
     * 销售查看
     */
    public String saleList(Model model,@RequestParam(required = false, defaultValue = "10") int pageSize,
                           @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name",request.getParameter("name")==null?"":request.getParameter("name"));//图书馆
        params.put("type",request.getParameter("type")==null?"":request.getParameter("type")); //到馆还是离馆
        params.put("month",request.getParameter("month")==null?"":request.getParameter("month")); //月份
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= libStaffingService.findBylist(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/fx/salelist";
    }

    @RequestMapping("/adminlist")
    public String adminlist(Model model,
                            @RequestParam(required = false, defaultValue = "10") int pageSize,
                            @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("nickName",  request.getParameter("nickName")==null?"":request.getParameter("nickName"));
        // params.put("orgCode", orgCode());
        // params.put("operId", adminId());

        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= adminService.findByPageMap(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/fx/adminlist";
    }

    /**
     * 物料进销存
     * @param model
     * @param pageSize
     * @param pageNo
     * @return
     * @throws Exception
     */
    @RequestMapping("/materielList")
    public String materielList(Model model,
                               @RequestParam(required = false, defaultValue = "10") int pageSize,
                               @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("materielName",  request.getParameter("materielName")==null?"":request.getParameter("materielName"));
        // params.put("orgCode", orgCode());
        // params.put("operId", adminId());

        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= materielService.findByPageMap(params, initPage(pageNo,pageSize));
        sp.setRowCnt((int)page.getTotalElements());
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        //查询用户角色
        int isManager = 0; //默认0 不是
        if("admin".equals(admin.getLoginName())){
            isManager = 1;
        }else{
            List<String> authorities =admin.getAuthorities();
            if(authorities!=null&&authorities.contains("物料管理员")){
                isManager = 1;
            }
        }


        model.addAttribute("isManager",isManager);
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);


        return "sys/fx/materielList";
    }

    @RequestMapping("/materielAdd")
    public String materielAdd(Model model,@RequestParam(required = false, defaultValue = "1") String id ) throws Exception {

        Materiel materiel = materielService.getById(id);
        if(materiel == null){
            materiel = new Materiel();
        }
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        //查询用户角色
        int isManager = 0; //默认0 不是
        if("admin".equals(admin.getLoginName())){
            isManager = 1;
        }else{
            List<String> authorities =admin.getAuthorities();
            if(authorities!=null&&authorities.contains("物料管理员")){
                isManager = 1;
            }
        }
        model.addAttribute("isManager",isManager);
        model.addAttribute("materiel",materiel);
        model.addAttribute("materielList",sortService.getParamValByCode("materiel_list"));
        model.addAttribute("materielSale",sortService.getParamValByCode("materiel_sales"));
        return "sys/fx/materielAdd";
    }

    @RequestMapping("/materielDel")
    public String materielDel(Model model,@RequestParam(required = false, defaultValue = "1") String id ) throws Exception {
        return "sys/fx/materielDel";
    }

    @RequestMapping(value="/saveMaterieDel",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity saveMaterieDel(@RequestParam String templateId,@RequestParam int delNum,@RequestParam(required = false, defaultValue = "0") int lostNum,@RequestParam(required = false, defaultValue = "0") int isNew){
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            MaterielTemplate template = materielTemplateService.getById(templateId);
            if(template == null ){
                responseEntity.failure("找不到物料模板");
            }else{
                responseEntity = materielService.saveMaterieDel(template,delNum,loginName(),lostNum,isNew,loginName());

            }


        }catch (Exception e){
            logger.error("学霸提交反馈异常", e);
            responseEntity.failure("系统出现异常，保存失败");
        }

        return responseEntity;
    }

    @RequestMapping(value="/saveMaterie",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity saveMaterie(Materiel materiel){
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            BigDecimal totalMoney = materiel.getTotalSum();
            int materielTotal = materiel.getInCount();
            BigDecimal avgPrice = materiel.getPrice();
            if(materiel.getPrice() !=null){
                List<Materiel> materielList = materielService.findMaterielByCode(materiel.getMaterieCode());
                if(materielList !=null && materielList.size()>0){
                    for(Materiel vo:materielList){
                        // if(materiel.getId().equals(vo.getId())){
                        if(vo.getId().equals(materiel.getId())){
                            materielTotal+=materiel.getInCount()-vo.getInCount()+vo.getUserdCount();
                            totalMoney=totalMoney.add(materiel.getPrice().multiply(new BigDecimal(materiel.getInCount()-vo.getInCount()+vo.getUserdCount())));
                        }else{
                            materielTotal+=vo.getUserdCount();
                            totalMoney=totalMoney.add(vo.getPrice().multiply(new BigDecimal(vo.getUserdCount())));
                        }

                    }
                    avgPrice = totalMoney.divide(new BigDecimal(materielTotal),4,ROUND_HALF_DOWN);
                    for(Materiel vo:materielList){
                        vo.setLeafPrice(avgPrice);
                    }
                    materielService.save(materielList);
                }
                materiel.setLeafPrice(avgPrice);
            }else {
                materiel.setLeafPrice(new BigDecimal(0));
                materiel.setTotalSum(new BigDecimal(0));
            }

            Materiel  materiel2 = null;
            if(materiel.getId()!=null){
                materiel2 = materielService.getById(materiel.getId());
            }
            materiel.setCreateTime(new Date());
            materiel.setCreateUser(loginName());
            materiel.setState(1);

            materiel.setUserdCount(materiel2==null?materiel.getInCount():materiel.getInCount()-materiel2.getInCount()+materiel2.getUserdCount());
            materielService.save(materiel);

            responseEntity.success("保存成功！");
        }catch (Exception e){
            responseEntity.failure("系统出现异常，保存失败");
            logger.error("异常", e);
        }

        return responseEntity;
    }

    @RequestMapping("/materielTemplateList")
    public String materielTemplateList(Model model,
                                       @RequestParam(required = false, defaultValue = "10") int pageSize,
                                       @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("LIKE_templateName",  request.getParameter("templateName")==null?"":request.getParameter("templateName"));
        // params.put("orgCode", orgCode());
        // params.put("operId", adminId());
        params.put("EQ_state",1);
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<MaterielTemplate> page= materielTemplateService.findTemplateByPageMap(params, initPage(pageNo,pageSize, Sort.Direction.DESC, new String[] { "createTime" }));
        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/fx/templateList";
    }

    @RequestMapping("/materielTemplateList2")
    public String materielTemplateList2(Model model,
                                        @RequestParam(required = false, defaultValue = "10") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("LIKE_templateName",  request.getParameter("templateName")==null?"":request.getParameter("templateName"));
        // params.put("orgCode", orgCode());
        // params.put("operId", adminId());
        params.put("EQ_state",1);
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<MaterielTemplate> page= materielTemplateService.findTemplateByPageMap(params, initPage(pageNo,pageSize, Sort.Direction.DESC, new String[] { "createTime" }));
        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/fx/templateList2";
    }

    @RequestMapping("/materielTemplateAdd")
    public String materielTemplateAdd(Model model,@RequestParam(required = false, defaultValue = "1") String id ) throws Exception {

        MaterielTemplate template = materielTemplateService.getById(id);
        if(template == null){
            template = new MaterielTemplate();
        }
        model.addAttribute("template",template);
        model.addAttribute("materielList",sortService.getParamValByCode("materiel_list"));
        return "sys/fx/materielTemplateAdd";
    }

    @RequestMapping("/materielTemplateEdit")
    public String materielTemplateEdit(Model model,@RequestParam(required = false, defaultValue = "1") String id ) throws Exception {

        MaterielTemplate template = materielTemplateService.getById(id);
        if(template == null){
            template = new MaterielTemplate();
        }
        model.addAttribute("template",template);
        model.addAttribute("materielList",sortService.getParamValByCode("materiel_list"));
        return "sys/fx/materielTemplateEdit";
    }

    @RequestMapping(value="/delTemplate",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity delTemplate(@RequestParam(required = false,defaultValue = "1") String id){
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            MaterielTemplate template = materielTemplateService.getById(id);
            template.setState(2);
            materielTemplateService.save(template);
            responseEntity.success("保存成功！");
        }catch (Exception e){
            responseEntity.failure("系统出现异常，保存失败");
            logger.error("异常", e);
        }

        return responseEntity;
    }

    @RequestMapping(value="/saveTemplate",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity saveTemplate(@RequestParam String templateName,@RequestParam(required = false,defaultValue = "1") String id){
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            MaterielTemplate template = materielTemplateService.getById(id);
            if(template == null){
                template = new MaterielTemplate();
            }
            template.setTemplateName(templateName);
            template.setCreateTime(new Date());
            template.setCreateUser(loginName());
            template.setState(1);
            //String materielName = request.getParameter("materielName");
            String[] names =  request.getParameterValues("materielName");
            String[] codes = request.getParameterValues("materielCode");
            String[] counts = request.getParameterValues("materielCount");
            String[] costNums = request.getParameterValues("costCount");
            List<TemplateInfo> infoList = new ArrayList<TemplateInfo>();
            if(names.length>0){
                for (int i = 0; i < names.length; i++) {
                    TemplateInfo info = new TemplateInfo();
                    info.setMaterielName(names[i]);
                    info.setMaterielCode(codes[i]);
                    info.setMaterielCount(Integer.parseInt(counts[i]));
                    info.setCostCount(Integer.parseInt(costNums[i]));
                    infoList.add(info);
                }
            }
            template.setMaterielJson(JSON.toJSONString(infoList));
            materielTemplateService.save(template);
            responseEntity.success("保存成功！");
        }catch (Exception e){
            responseEntity.failure("系统出现异常，保存失败");
            logger.error("异常", e);
        }

        return responseEntity;
    }

    @RequestMapping(value = "/exportDetail", method = RequestMethod.POST)
    @ResponseBody
    public void exportDetail(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String type = request.getParameter("type");
            String libName="";
            if("1".equals(type)){
                libName="订单明细";
            }else if("2".equals(type)){
                libName="区域信息";
            }else if ("3".equals(type)){
                libName="销售数据";
            }else if ("4".equals(type)){
                libName="剩余物料数据";
            }else if ("5".equals(type)){
                libName="物料数据";
            }else if ("6".equals(type)){
                libName="核销物料明细数据";
            }else if ("7".equals(type)){
                libName="核销物料数据";
            }else{
                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>();
            if ("1".equals(type)) {
                params.put("orderNo",request.getParameter("orderNo")==null?"":request.getParameter("orderNo"));//客户
                params.put("startDate",request.getParameter("startDate")==null?"":request.getParameter("startDate")); //月份
                params.put("endDate",request.getParameter("endDate")==null?"":request.getParameter("endDate")); //月份
                Merchant merchant=merchantService.getMerchantByPosCode(loginName());
                if(merchant.getOrgCode().equals("SSJ-FX")){
                    params.put("showType","1");
                    params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
                }else{
                    List<Merchant> listMerchant = merchantService.getMerchantByParentPosCode(merchant.getPosCode());
                    //看是否有下级
                    if(listMerchant == null || listMerchant.size()==0){ //无下级看自身数据
                        params.put("showType","1");
                        params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
                    }else{
                        if(merchant.getLevel()==null){
                            params.put("showType","2"); //只看下级
                            params.put("LIKE_orgCode",merchant==null ?"": merchant.getPosCode());
                        }else{
                            params.put("showType","1"); //有下级就只看下级和自身数据
                            params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
                        }

                    }
                }

                params.put("order_type",request.getParameter("order_type")==null?"":request.getParameter("order_type"));
                params.put("unit_name",request.getParameter("unit_name")==null?"":request.getParameter("unit_name"));
                params.put("seachDerver",request.getParameter("seachDerver")==null?"":request.getParameter("seachDerver"));
                Page<Map<String, Object>> page = devicePartsService.salsetList(params, initPage(1, 100000, org.springframework.data.domain.Sort.Direction.DESC, new String[]{"createTime"}));
                List<Map<String, Object>> list = page.getContent();
                List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
                list2.addAll(list);
                List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
//构造对象等同于@Excel
                ExcelExportEntity excelentity = new ExcelExportEntity("订单号", "order_no");
                excelentity.setNeedMerge(false);
                entity.add(excelentity);
                /**
                 * <td th:text="${item.get('unit_name')}"></td>
                 * 				<td th:text="${item.get('imei')}"></td>
                 * 				<td th:text="${item.get('pay_user')}"></td>
                 * 				<td th:text="${item.get('wx_name')}"></td>
                 * 				<td th:text="${item.get('child_name')}"></td>
                 * 				<td th:text="${item.get('is_close')}"></td>
                 * 				<td th:text="${item.get('derver')}"></td>
                 * 				<td th:text="${item.get('simcard')}"></td>
                 */
                ExcelExportEntity excelentity5 = new ExcelExportEntity("商户", "unit_name");
                excelentity5.setNeedMerge(false);
                entity.add(excelentity5);
                ExcelExportEntity excelentity6 = new ExcelExportEntity("imei", "imei");
                excelentity6.setNeedMerge(false);
                entity.add(excelentity6);
                ExcelExportEntity excelentity7 = new ExcelExportEntity("支付人", "pay_user");
                excelentity7.setNeedMerge(false);
                entity.add(excelentity7);
                ExcelExportEntity excelentity8 = new ExcelExportEntity("微信昵称", "wx_name");
                excelentity8.setNeedMerge(false);
                entity.add(excelentity8);
                ExcelExportEntity excelentity9 = new ExcelExportEntity("小孩", "child_name");
                excelentity9.setNeedMerge(false);
                entity.add(excelentity9);
                ExcelExportEntity excelentity10 = new ExcelExportEntity("是否结算", "is_close");
                excelentity10.setNeedMerge(false);
                entity.add(excelentity10);
                ExcelExportEntity excelentity11 = new ExcelExportEntity("小塾号", "derver");
                excelentity11.setNeedMerge(false);
                entity.add(excelentity11);
                ExcelExportEntity excelentity12 = new ExcelExportEntity("simcard", "simcard");
                excelentity12.setNeedMerge(false);
                entity.add(excelentity12);

                ExcelExportEntity excelentity2 = new ExcelExportEntity("产品类型", "details");
                excelentity2.setNeedMerge(false);
                entity.add(excelentity2);
                ExcelExportEntity excelentity3 = new ExcelExportEntity("金额", "price");
                excelentity3.setNeedMerge(false);
                entity.add(excelentity3);
                ExcelExportEntity excelentity4 = new ExcelExportEntity("开始时间", "create_time");
                excelentity4.setNeedMerge(false);
                entity.add(excelentity4);

                ExcelExportEntity excelentity13 = new ExcelExportEntity("结束时间", "end_time");
                excelentity13.setNeedMerge(false);
                entity.add(excelentity13);
//把我们构造好的bean对象放到params就可以了
                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("订单明细", "订单明细", ExcelType.XSSF), entity,
                        list2);
                workbook.write(os);
            }else if ("2".equals(type)){
                params.put("area",request.getParameter("area")==null?"":request.getParameter("area")); //到馆还是离馆
                params.put("startDate",request.getParameter("startDate")==null?"":request.getParameter("startDate")); //月份

                Page<Map<String, Object>> list = devicePartsService.salseMouthMoneytList(params, initPage(1, 100000, org.springframework.data.domain.Sort.Direction.DESC, new String[]{"createTime"}));

                List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
                myColumns3.add(new ExcelColumn("区域", "location", 20));
                myColumns3.add(new ExcelColumn("总金额", "price", 20));
                myColumns3.add(new ExcelColumn("数量", "dcount", 20));
                myColumns3.add(new ExcelColumn("月份", "mdate", 20));

                CustomizeToExcel.downFile(myColumns3, list.getContent(), os);
            }else if ("3".equals(type)){
                params.put("name",request.getParameter("name")==null?"":request.getParameter("name"));//客户
                params.put("startDate",request.getParameter("startDate")==null?"":request.getParameter("startDate")); //月份
                Merchant merchant=merchantService.getMerchantByPosCode(loginName());
                if(merchant.getOrgCode().equals("SSJ-FX")){
                    params.put("showType","1");
                    params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
                }else{
                    List<Merchant> listMerchant = merchantService.getMerchantByParentPosCode(merchant.getPosCode());
                    //看是否有下级
                    if(listMerchant == null || listMerchant.size()==0){ //无下级看自身数据
                        params.put("showType","1");
                        params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
                    }else{
                        if(merchant.getLevel()==null){
                            params.put("showType","2"); //只看下级
                            params.put("LIKE_orgCode",merchant==null ?"": merchant.getPosCode());
                        }else{
                            params.put("showType","1"); //有下级就只看下级和自身数据
                            params.put("LIKE_orgCode",merchant==null ?"": merchant.getOrgCode());
                        }

                    }
                }
                Page<Map<String, Object>> list = devicePartsService.salseMouthtList(params, initPage(1, 100000, Sort.Direction.DESC, new String[]{"createTime"}));

                List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
                myColumns3.add(new ExcelColumn("经销商", "unit_name", 20));
                myColumns3.add(new ExcelColumn("级别", "plevel", 20));
                myColumns3.add(new ExcelColumn("销售总额", "price", 20));
                myColumns3.add(new ExcelColumn("月份", "mdate", 20));
                myColumns3.add(new ExcelColumn("订单提成", "tc", 20));
                myColumns3.add(new ExcelColumn("返利提成", "fl", 20));
                myColumns3.add(new ExcelColumn("总提成", "total", 20));
                CustomizeToExcel.downFile(myColumns3, list.getContent(), os);
            }else if("4".equals(type)){
                params.put("materielName",  request.getParameter("materielName")==null?"":request.getParameter("materielName"));
                Page<Map<String, Object>> list= materielService.findMaterielLeafByPageMap(params, initPage(1,100000));

                List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
                myColumns3.add(new ExcelColumn("物料名称", "materiel_name", 20));
                myColumns3.add(new ExcelColumn("物料编码", "materie_code", 20));
                myColumns3.add(new ExcelColumn("剩余数量", "sum_count", 20));
                myColumns3.add(new ExcelColumn("单价", "leaf_price", 20));
                CustomizeToExcel.downFile(myColumns3, list.getContent(), os);
            }else if("5".equals(type)){
                params.put("materielName",  request.getParameter("materielName")==null?"":request.getParameter("materielName"));
                // params.put("orgCode", orgCode());
                // params.put("operId", adminId());

                Page<Map<String, Object>> list= materielService.findByPageMap(params, initPage(1,100000));
                String adminId = adminId();
                //查询用户角色
                List<String> rolelist = roleService.getAdminRole(adminId);
                int isManager = 0; //默认0 不是
                for (String str:rolelist){
                    Role role = roleService.getById(str);
                    if(role.getName().equals("物料管理员")){
                        isManager = 1;
                        break;
                    }
                }

                List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
                myColumns3.add(new ExcelColumn("入库编码", "materiel_flow", 20));
                myColumns3.add(new ExcelColumn("物料名称", "materiel_name", 20));
                myColumns3.add(new ExcelColumn("物料编码", "materie_code", 20));
                myColumns3.add(new ExcelColumn("已用数量", "leaf_count", 20));
                myColumns3.add(new ExcelColumn("入库数量", "in_count", 20));
                myColumns3.add(new ExcelColumn("剩余数量", "userd_count", 20));
                myColumns3.add(new ExcelColumn("供应商", "supplier", 20));
                myColumns3.add(new ExcelColumn("入库时间", "create_time", 20));
                if(isManager ==1){
                    myColumns3.add(new ExcelColumn("单价", "price", 20));
                    myColumns3.add(new ExcelColumn("金额", "total_sum", 20));
                }
                CustomizeToExcel.downFile(myColumns3, list.getContent(), os);
            }else if("6".equals(type)){
                params.put("EQ_offId", request.getParameter("EQ_offId")==null?"":request.getParameter("EQ_offId"));
                params.put("EQ_type", 1);
                List<Map<String, Object>> list = materielOffDetailService.findMapList(params);
                List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
                myColumns3.add(new ExcelColumn("物料入库流水号", "materiel_flow", 20));
                myColumns3.add(new ExcelColumn("物料名称", "materiel_name", 20));
                myColumns3.add(new ExcelColumn("物料编码", "materie_code", 20));
                myColumns3.add(new ExcelColumn("核销数量", "cost_num", 20));
                myColumns3.add(new ExcelColumn("价格", "price", 20));
                CustomizeToExcel.downFile(myColumns3, list, os);
            }else if("7".equals(type)){
                params.put("GT_offTime", request.getParameter("GT_offTime")==null?"":request.getParameter("GT_offTime"));
                params.put("LT_offTime", request.getParameter("LT_offTime")==null?"":request.getParameter("LT_offTime"));
                Page<MaterielOff> page = materielOffService.findOffByPage(params, initPage(1, 100000, Sort.Direction.DESC, new String[]{"offTime"}));
                List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
                if(page.getContent()!=null && page.getContent().size()>0){
                    for(MaterielOff off:page.getContent()){
                        Map<String,Object> newOff = new HashMap<String,Object>();
                        newOff.put("offNum",off.getOffNum());
                        newOff.put("offFlow",off.getOffFlow());
                        newOff.put("offTime",off.getOffTime());
                        // newOff.put("",off.getTemplateJson());
                        List<TemplateInfo> infoList = off.getTempInfoList();
                        List<Map<String,Object>> templateList = new ArrayList<Map<String,Object>>();
                        for (TemplateInfo info :infoList){
                            Map<String,Object> map = new HashMap<>();
                            map.put("materielName",info.getMaterielName());
                            map.put("materielCount",info.getMaterielCount());
                            templateList.add(map);
                        }
                        newOff.put("tempInfoList",templateList);
                        dataList.add(newOff);
                    }
                }
                //dataList.addAll(page.getContent());
                // System.out.println(page.getContent().get(0).getTempInfoList());
                List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
//构造对象等同于@Excel
                ExcelExportEntity excelentity = new ExcelExportEntity("核销流水号", "offFlow");
                excelentity.setNeedMerge(true);
                entity.add(excelentity);
                ExcelExportEntity excelentity2 = new ExcelExportEntity("核销时间", "offTime");
                excelentity2.setNeedMerge(true);
                entity.add(excelentity2);
                ExcelExportEntity excelentity3 = new ExcelExportEntity("核销数量", "offNum");
                excelentity3.setNeedMerge(true);
                entity.add(excelentity3);
                ExcelExportEntity excelentity5 = new ExcelExportEntity(null, "tempInfoList");
                List<ExcelExportEntity> temp = new ArrayList<ExcelExportEntity>();
                temp.add(new ExcelExportEntity("物料名称", "materielName"));
                temp.add(new ExcelExportEntity("物料数量", "materielCount"));
//构造List等同于@ExcelCollection
                excelentity5.setList(temp);
                entity.add(excelentity5);
//把我们构造好的bean对象放到params就可以了
                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(libName, libName, ExcelType.XSSF), entity,
                        dataList);
                workbook.write(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("/materielOffList")
    public String materielOffList(Model model,
                                  @RequestParam(required = false, defaultValue = "10") int pageSize,
                                  @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("GT_offTime", request.getParameter("GT_offTime")==null?"":request.getParameter("GT_offTime"));
        params.put("LT_offTime", request.getParameter("LT_offTime")==null?"":request.getParameter("LT_offTime"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<MaterielOff> page = materielOffService.findOffByPage(params, initPage(pageNo, pageSize, Sort.Direction.DESC, new String[]{"offTime"}));
        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/fx/materielOffList";
    }

    //核销明细
    @RequestMapping("/materielOffDetailList")
    public String materielOffDetailList(Model model,
                                        @RequestParam(required = false, defaultValue = "10") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("EQ_offId", request.getParameter("offId")==null?"":request.getParameter("offId"));
        params.put("EQ_type", 1);
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<MaterielOffDetail> page = materielOffDetailService.findOffDetailByPage(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/fx/materielOffDetailList";
    }

    //剩余物料平均单价列表
    @RequestMapping("/materielLeafList")
    public String materielLeafList(Model model,
                                   @RequestParam(required = false, defaultValue = "10") int pageSize,
                                   @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("materielName",  request.getParameter("materielName")==null?"":request.getParameter("materielName"));
        // params.put("orgCode", orgCode());
        // params.put("operId", adminId());

        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= materielService.findMaterielLeafByPageMap(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/fx/materielLeafList";
    }

    @RequestMapping("/materielOffLeafList")
    public String materielOffLeafList(Model model,
                                      @RequestParam(required = false, defaultValue = "10") int pageSize,
                                      @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        //params.put("materielName",  request.getParameter("materielName")==null?"":request.getParameter("materielName"));
        // params.put("orgCode", orgCode());
        // params.put("operId", adminId());
        params.put("startDate", request.getParameter("startDate")==null?"":request.getParameter("startDate"));
        params.put("endDate", request.getParameter("endDate")==null?"":request.getParameter("endDate"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= materielService.findMaterielOffLeafByPageMap(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/fx/materielOffLeafList";
    }

    @RequestMapping(value = "/exportMaterielOffDetail", method = RequestMethod.POST)
    @ResponseBody
    public void exportMaterielOffDetail(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("startDate", request.getParameter("startDate")==null?"":request.getParameter("startDate"));
            params.put("endDate", request.getParameter("endDate")==null?"":request.getParameter("endDate"));

            Page<Map<String, Object>> list = materielService.findMaterielOffLeafByPageMap(params, initPage(1, 100000));

            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("核销流水号", "off_flow", 20));
            myColumns3.add(new ExcelColumn("核销时间", "off_time", 20));
            myColumns3.add(new ExcelColumn("核销数量", "off_num", 20));
            myColumns3.add(new ExcelColumn("损耗数量", "loss_num", 20));
            myColumns3.add(new ExcelColumn("物料编码", "materie_code", 20));
            myColumns3.add(new ExcelColumn("物料名称", "materie_name", 20));
            myColumns3.add(new ExcelColumn("消耗物料", "cost_num", 20));
            myColumns3.add(new ExcelColumn("物料平均单价", "price", 20));
            CustomizeToExcel.downFile(myColumns3, list.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("/vipDerverList")
    public String vipDerverList(Model model,
                                @RequestParam(required = false, defaultValue = "10") int pageSize,
                                @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("vipFlow", request.getParameter("vipFlow")==null?"":request.getParameter("vipFlow")); //会员卡号
        params.put("derver", request.getParameter("derver")==null?"":request.getParameter("derver"));//设备号
        params.put("childName", request.getParameter("childName")==null?"":request.getParameter("childName"));//小孩姓名
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= materielService.vipDerverList(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/fx/vipDerverList";
    }

    @RequestMapping(value = "/vipDerverExport", method = RequestMethod.POST)
    @ResponseBody
    public void vipDerverExport(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("vipFlow", request.getParameter("vipFlow")==null?"":request.getParameter("vipFlow")); //会员卡号
            params.put("derver", request.getParameter("derver")==null?"":request.getParameter("derver"));//设备号
            params.put("childName", request.getParameter("childName")==null?"":request.getParameter("childName"));//小孩姓名

            Page<Map<String, Object>> list = materielService.vipDerverList(params, initPage(1, 100000));

            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("设备号", "derver", 20));
            myColumns3.add(new ExcelColumn("学生姓名", "child_name", 20));
            myColumns3.add(new ExcelColumn("学校", "school", 20));
            myColumns3.add(new ExcelColumn("年级", "grade", 20));
            myColumns3.add(new ExcelColumn("电话", "phone", 20));
            myColumns3.add(new ExcelColumn("卡号", "flow_id", 20));
            myColumns3.add(new ExcelColumn("imei号", "imei", 20));
            myColumns3.add(new ExcelColumn("sim卡", "simcard", 20));
            CustomizeToExcel.downFile(myColumns3, list.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("/monthInAndOutList")
    public String monthInAndOutList(Model model,
                                @RequestParam(required = false, defaultValue = "10") int pageSize,
                                @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("queryDate", request.getParameter("queryDate")==null?"":request.getParameter("queryDate")); //筛选月份
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= materielService.MonthInAndOutList(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/fx/monthInAndOut";
    }

    @RequestMapping(value = "/monthInAndOutExport", method = RequestMethod.POST)
    @ResponseBody
    public void monthInAndOutExport(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("queryDate", request.getParameter("queryDate")==null?"":request.getParameter("queryDate")); //筛选月份

            Page<Map<String, Object>> list = materielService.MonthInAndOutList(params, initPage(1, 100000));

            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("商户名", "unit_name", 20));
            myColumns3.add(new ExcelColumn("月份", "mdate", 20));
            myColumns3.add(new ExcelColumn("入库量", "ruku", 20));
            myColumns3.add(new ExcelColumn("出库量", "chuku", 20));
            myColumns3.add(new ExcelColumn("退换量", "tuiku", 20));
            CustomizeToExcel.downFile(myColumns3, list.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 = "/monthInAndOutDetailExport", method = RequestMethod.POST)
    @ResponseBody
    public void monthInAndOutDetailExport(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("queryDate", request.getParameter("queryDate")==null?"":request.getParameter("queryDate")); //筛选月份

            List<Map<String, Object>> list = materielService.monthInAndOutDetailList(params);

            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("出开发商", "p_unit", 20));
            myColumns3.add(new ExcelColumn("出库量", "remarks", 20));
            myColumns3.add(new ExcelColumn("入开发商", "c_unit", 20));
            myColumns3.add(new ExcelColumn("imei", "imei", 20));

            myColumns3.add(new ExcelColumn("时间", "create_time", 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("/monthLastList")
    public String monthLastList(Model model,
                                    @RequestParam(required = false, defaultValue = "10") int pageSize,
                                    @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("queryDate", request.getParameter("queryDate")==null?"":request.getParameter("queryDate")); //筛选月份
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= materielService.MonthInAndOutList(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/fx/monthInAndOut2";
    }

    @RequestMapping(value = "/monthLastExport", method = RequestMethod.POST)
    @ResponseBody
    public void monthLastExport(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("queryDate", request.getParameter("queryDate")==null?"":request.getParameter("queryDate")); //筛选月份

            Page<Map<String, Object>> list = materielService.MonthInAndOutList(params, initPage(1, 100000));

            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("商户名", "unit_name", 20));
            myColumns3.add(new ExcelColumn("月份", "mdate", 20));
            myColumns3.add(new ExcelColumn("入库量", "ruku", 20));
            myColumns3.add(new ExcelColumn("出库量", "chuku", 20));
            myColumns3.add(new ExcelColumn("结存量", "jiecun", 20));
            myColumns3.add(new ExcelColumn("入库总额", "ruku_total", 20));
            myColumns3.add(new ExcelColumn("出库总额", "chuku_total", 20));
            myColumns3.add(new ExcelColumn("结存总额", "jiecun_total", 20));
            CustomizeToExcel.downFile(myColumns3, list.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("/orderCloseList")
    public String orderCloseList(Model model,
                               @RequestParam(required = false, defaultValue = "10") int pageSize,
                               @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("order_type", request.getParameter("order_type")==null?"":request.getParameter("order_type"));
        params.put("beginDate", request.getParameter("beginDate")==null? DateHelper.format(DateHelper.getTheMonthFirstDay(), "yyyy-MM-dd"):request.getParameter("beginDate"));
        params.put("endDate", request.getParameter("endDate")==null?DateHelper.format(new Date(), "yyyy-MM-dd"):request.getParameter("endDate"));
        params.put("order_no", request.getParameter("order_no")==null?"":request.getParameter("order_no"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>>  page= materielService.findForPageList(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/fx/fxOrderList";
    }

    @RequestMapping(value = "/orderDetailClose", method = RequestMethod.POST)
    @ResponseBody
    public Response orderDetailClose(@RequestParam(value = "ids[]")String[] ids) {
        Response response = new Response();
        try {
            materielService.orderDetailClose(ids,2);
            response.success("添加成功");
        } catch (Exception e) {
            logger.error("异常", e);
            response.failure("添加失败：" + e.getMessage());
        }
        return response;
    }

    @RequestMapping(value = "/exportOrder", method = RequestMethod.POST)
    @ResponseBody
    public void exportOrder(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("order_type", request.getParameter("order_type")==null?"":request.getParameter("order_type"));
            params.put("beginDate", request.getParameter("beginDate")==null? DateHelper.format(DateHelper.getTheMonthFirstDay(), "yyyy-MM-dd"):request.getParameter("beginDate"));
            params.put("endDate", request.getParameter("endDate")==null?DateHelper.format(new Date(), "yyyy-MM-dd"):request.getParameter("endDate"));
            params.put("order_no", request.getParameter("order_no")==null?"":request.getParameter("order_no"));

            Page<Map<String, Object>> list = materielService.findForPageList(params, initPage(1, 100000));

            List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
            myColumns3.add(new ExcelColumn("下单人", "wx_name", 20));
            myColumns3.add(new ExcelColumn("订单编号", "order_no", 20));
            myColumns3.add(new ExcelColumn("订单类型", "price_type", 20));
            myColumns3.add(new ExcelColumn("订单金额", "order_money", 20));
            myColumns3.add(new ExcelColumn("下单时间", "create_time", 20));
            myColumns3.add(new ExcelColumn("支付成功时间", "pay_time", 20));
            myColumns3.add(new ExcelColumn("退款时间", "refund_time", 20));
            myColumns3.add(new ExcelColumn("是否结算", "is_close", 20));
            CustomizeToExcel.downFile(myColumns3, list.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("/selectMaterielList")
    public String selectMaterielList(Model model,
                                 @RequestParam(required = false, defaultValue = "10") int pageSize,
                                 @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("EQ_pid","93ff02f6-c3e9-4f40-bc8c-62559571ec1e");
        params.put("LIKE_name",request.getParameter("name")==null?"":request.getParameter("name"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<com.ssj.bean.sys.sort.domain.Sort> page= sortService.findByPage(params, initPage(pageNo,pageSize));
        sp.setRowCnt((int)page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        params.put("divIndex",request.getParameter("divIndex")==null?"0":request.getParameter("divIndex"));
        model.addAttribute("search", params);

        return "sys/fx/sortMaterielList";
    }


    @RequestMapping(value = "/materielDelete", method = RequestMethod.POST)
    @ResponseBody
    public Response materielDelete( String id){
        Response response = new  Response();
        Materiel materiel = materielService.getById(id);
        if(materiel.getLeafCount()==0){
            materielService.delete(id);
            response.success();
        }else {
            response.failure("物料有核销，不能删除！");
        }

        return response;
    }

    @RequestMapping("/list")
    public String list(Model model,
                       @RequestParam(required = false, defaultValue = "10") int pageSize,
                       @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("LIKE_name", request.getParameter("LIKE_name")==null?"":request.getParameter("LIKE_name"));
        params.put("LIKE_code", request.getParameter("LIKE_code")==null?"":request.getParameter("LIKE_code"));
        params.put("EQ_pid", request.getParameter("EQ_pid")==null?"0":request.getParameter("EQ_pid"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<MaterielHome> page= materielHomeService.findByPage(params, initPage(pageNo,pageSize, Sort.Direction.DESC,"sort"));
        List<MaterielHome> list = page.getContent();
        sp.setRowCnt((int)page.getTotalElements());
        model.addAttribute("list", list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

        return "sys/fx/list";
    }

    /**
     * 系统参数编辑页面
     * @param
     * @param
     * @return
     */
    @RequestMapping("/add")
    public String add(Model model, @RequestParam( defaultValue = "id")String id) throws Exception{
        MaterielHome materielHome= materielHomeService.getById(id);
        if(materielHome ==null) {
            materielHome = new MaterielHome();
        }
        model.addAttribute("sort", materielHome);
        return "sys/fx/add";
    }

    /**
     * 删除标签参数
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deleteSort", method = RequestMethod.POST)
    @ResponseBody
    public Response deleteSort(String id) throws Exception{
        deleteChildrenSort(id, 0);
        Response response = new  Response();
        response.success();
        return response;
    }

    //递归调用删除所有的子节点
    private void deleteChildrenSort(String  pid, int callCount) throws Exception {
        callCount ++;
        //判断递归深度
        if(callCount > 5){
            return ;
        }
        List<MaterielHome> childrenList= materielHomeService.findByPid(pid);
        for (MaterielHome sort : childrenList) {
            deleteChildrenSort(sort.getId(), callCount);
        }
        sortService.delete(pid);
    }


    @RequestMapping("/childrenAdd")
    public String childrenAdd(Model model, @RequestParam( defaultValue = "id")String id,
                              @RequestParam( defaultValue = "0")String edit,
                              @RequestParam( defaultValue = "pid")String pid) {
        MaterielHome parent = materielHomeService.getById(pid);
        if(parent == null ){
            parent = new MaterielHome();
        }
        MaterielHome sort = materielHomeService.getById(id);
        if(sort == null ){
            sort = new MaterielHome();
            if(parent.getLevel()!=null){
                sort.setLevel(parent.getLevel()+1);
            }
        }
        model.addAttribute("parent", parent);
        model.addAttribute("sort", sort);
        model.addAttribute("edit", edit);
        return "sys/sort/childrenAdd";
    }

    @RequestMapping(value = "/saveMateriel", method = RequestMethod.POST)
    @ResponseBody
    public Response saveMateriel(MaterielHome  sort) throws Exception{
        Response response = new  Response();
        sort=materielHomeService.save(sort);
        response.success(sort);
        return response;
    }

    @RequestMapping("/childList")
    public String childList(Model model,
                       @RequestParam(required = false, defaultValue = "10") int pageSize,
                       @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("EQ_pid", request.getParameter("EQ_pid")==null?"0":request.getParameter("EQ_pid"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<MaterielHome> page= materielHomeService.findByPage(params, initPage(pageNo,pageSize, Sort.Direction.DESC,"sort"));
        List<MaterielHome> list = page.getContent();
        sp.setRowCnt((int)page.getTotalElements());
        model.addAttribute("list", list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/fx/childlist";
    }
}
