package com.ssj.sys.controller;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ssj.bean.common.files.domain.FileInfo;
import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.conch.conch.domain.ConchDerver;
import com.ssj.bean.sys.fx.domain.Device;
import com.ssj.bean.sys.fx.domain.DeviceAct;
import com.ssj.bean.sys.fx.domain.DeviceParts;
import com.ssj.bean.sys.fx.domain.DevicePartsAct;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.fx.domain.MerchantBackup;
import com.ssj.bean.sys.fx.domain.MerchantMealOrder;
import com.ssj.bean.sys.fx.domain.MerchantPlatOrder;
import com.ssj.bean.sys.fx.domain.MerchantSignOrder;
import com.ssj.bean.sys.organization.domain.Organization;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.problem.domain.CnArea;
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.PropertiesUtil;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.WebUtil;
import com.ssj.framework.files.service.FileInfoService;
import com.ssj.framework.idworker.IdWorker;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.conch.parents.v1.dto.PositionSchoolV1Dto;
import com.ssj.service.sys.fx.service.DeviceActService;
import com.ssj.service.sys.fx.service.DevicePartsActService;
import com.ssj.service.sys.fx.service.DevicePartsService;
import com.ssj.service.sys.fx.service.DeviceService;
import com.ssj.service.sys.fx.service.MerchantAreaService;
import com.ssj.service.sys.fx.service.MerchantBackupService;
import com.ssj.service.sys.fx.service.MerchantMealOrderService;
import com.ssj.service.sys.fx.service.MerchantMealService;
import com.ssj.service.sys.fx.service.MerchantPlatOrderService;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.sys.fx.service.MerchantSignOrderService;
import com.ssj.service.sys.fx.service.MerchantSignService;
import com.ssj.service.sys.role.service.AdminService;
import com.ssj.service.weixin.library.service.ILibJoinConsumeService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.problem.service.CnAreaService;
import com.ssj.sys.util.thirdparty.excel.CustomizeToExcel;
import com.ssj.sys.util.thirdparty.excel.ExcelColumn;
import com.ssj.sys.utils.ExcelUtils;



@RequestMapping("sys/fx")
@Controller
public class FxController  extends BaseController {

	@Autowired
	private DevicePartsService devicePartsService;
	
	@Autowired
	private DeviceService deviceService;
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private MerchantMealService merchantMealService;
	
	@Autowired
	private MerchantMealOrderService merchantMealOrderService;
	
	@Autowired
	private MerchantPlatOrderService merchantPlatOrderService;
	
	@Autowired
	private MerchantBackupService merchantBackupService;
	
	@Autowired
	private MerchantSignOrderService merchantSignOrderService;
	
	@Autowired
	private MerchantSignService merchantSignService;
	
	@Autowired
	private ConchDerverService conchDerverService;
	
	@Autowired
	private AdminService adminService;
	
	@Autowired
    private FileInfoService fileInfoService;   
	
	@Autowired
	private DeviceActService deviceActService;
	
	@Autowired
	private DevicePartsActService devicePartsActService;
	
	@Autowired
	private CnAreaService cnAreaService;
	
	@Autowired
	private ILibJoinService libJoinService;
	
	@Autowired
	private ILibJoinConsumeService libJoinConsumeService;
	
	@Autowired
	private MerchantAreaService merchantAreaService;

	//库存管理员查询所有设备
	@RequestMapping("/deviceAllList")
    public String deviceAllList(Model model,
                              @RequestParam(required = false, defaultValue = "100") int pageSize,
                              @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("LIKE_imei", request.getParameter("LIKE_imei")==null?"":request.getParameter("LIKE_imei"));
        
        String inDeviceNumber=request.getParameter("LIKE_deviceNumber")==null?"":request.getParameter("LIKE_deviceNumber");
        String inDeviceRealNumber=request.getParameter("LIKE_deviceRealNumber")==null?"":request.getParameter("LIKE_deviceRealNumber");
        if(StringUtils.isNotEmpty(inDeviceNumber)) {
        	params.put("IN_deviceNumber", Arrays.asList(inDeviceNumber.split(" ")));
        }
        if(StringUtils.isNotEmpty(inDeviceRealNumber)) {
        	params.put("IN_deviceRealNumber", Arrays.asList(inDeviceRealNumber.split(" ")));
        }
        
        params.put("LIKE_deviceModel", request.getParameter("LIKE_deviceModel")==null?"":request.getParameter("LIKE_deviceModel"));
        params.put("LIKE_deviceCode", request.getParameter("LIKE_deviceCode")==null?"":request.getParameter("LIKE_deviceCode"));
        
        params.put("EQ_isSpan", request.getParameter("EQ_isSpan")==null?"":request.getParameter("EQ_isSpan"));
        params.put("EQ_status", request.getParameter("EQ_status")==null?"":request.getParameter("EQ_status"));
        
        if(StringUtils.isNotEmpty(request.getParameter("EQ_orgCode"))){
        	params.put("EQ_orgCode", request.getParameter("EQ_orgCode"));
        }
        params.put("EQ_batchCode", request.getParameter("EQ_batchCode")==null?"":request.getParameter("EQ_batchCode"));
        
        params.put("EQ_emsNumber", request.getParameter("EQ_emsNumber")==null?"":request.getParameter("EQ_emsNumber"));
        params.put("LIKE_remarks", request.getParameter("LIKE_remarks")==null?"":request.getParameter("LIKE_remarks"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Device> page = deviceService.findDeviceByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"updateTime"}));
        sp.setRowCnt((int) page.getTotalElements());
        
        params.put("LIKE_deviceNumber", request.getParameter("LIKE_deviceNumber")==null?"":request.getParameter("LIKE_deviceNumber"));
        params.put("LIKE_deviceRealNumber", request.getParameter("LIKE_deviceRealNumber")==null?"":request.getParameter("LIKE_deviceRealNumber"));
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
        return "sys/fx/deviceAllList";
    }
	
	//当前商户下的所有的设备，支持imei1范围，和批次号
	@RequestMapping("/deviceList")
    public String deviceList(Model model,
                              @RequestParam(required = false, defaultValue = "100") int pageSize,
                              @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("LIKE_imei", request.getParameter("LIKE_imei")==null?"":request.getParameter("LIKE_imei"));
        
        String inDeviceNumber=request.getParameter("LIKE_deviceNumber")==null?"":request.getParameter("LIKE_deviceNumber");
        String inDeviceRealNumber=request.getParameter("LIKE_deviceRealNumber")==null?"":request.getParameter("LIKE_deviceRealNumber");
        if(StringUtils.isNotEmpty(inDeviceNumber)) {
        	params.put("IN_deviceNumber", Arrays.asList(inDeviceNumber.split(" ")));
        }
        if(StringUtils.isNotEmpty(inDeviceRealNumber)) {
        	params.put("IN_deviceRealNumber", Arrays.asList(inDeviceRealNumber.split(" ")));
        }

        params.put("LIKE_deviceModel", request.getParameter("LIKE_deviceModel")==null?"":request.getParameter("LIKE_deviceModel"));
        params.put("LIKE_deviceCode", request.getParameter("LIKE_deviceCode")==null?"":request.getParameter("LIKE_deviceCode"));
        
        params.put("EQ_isSpan", request.getParameter("EQ_isSpan")==null?"":request.getParameter("EQ_isSpan"));
        params.put("EQ_status", request.getParameter("EQ_status")==null?"":request.getParameter("EQ_status"));
        
        params.put("EQ_batchCode", request.getParameter("EQ_batchCode")==null?"":request.getParameter("EQ_batchCode"));
        params.put("EQ_emsNumber", request.getParameter("EQ_emsNumber")==null?"":request.getParameter("EQ_emsNumber"));
        params.put("EQ_type", request.getParameter("EQ_type")==null?"":request.getParameter("EQ_type"));
        params.put("LIKE_remarks", request.getParameter("LIKE_remarks")==null?"":request.getParameter("LIKE_remarks"));
        
        if(StringUtils.isNotEmpty(request.getParameter("EQ_orgCode"))){
        	params.put("EQ_orgCode", request.getParameter("EQ_orgCode"));
        }else{
        	if("SSJ-FX".equals(merchant.getOrgCode())){
        		params.put("LIKE_orgCode",merchant.getOrgCode());
        	}else{
        		List<String> orgCodes=new ArrayList<String>();
	        	orgCodes.add(merchant.getOrgCode());
	        	List<Merchant> merchants=merchantService.getMerchantByParentPosCode(merchant.getPosCode());
	        	for (Merchant merchant2 : merchants) {
	        		orgCodes.add(merchant2.getOrgCode());
				}
	        	params.put("IN_orgCode",orgCodes);
        	}
        }
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Device> page = deviceService.findDeviceByPage(params, initPage(pageNo, pageSize, Direction.ASC, new String[]{"updateTime"}));
        sp.setRowCnt((int) page.getTotalElements());
        
        List<Device> orderList=new ArrayList<Device>();
        List<Device> deviceList= page.getContent();
	    for (Device device : deviceList) {
			if(device.getOrgCode().equals(merchant.getOrgCode())){
				orderList.add(0, device);
			}else{
				orderList.add(device);
			}
		}
	    
	    params.put("LIKE_deviceNumber", request.getParameter("LIKE_deviceNumber")==null?"":request.getParameter("LIKE_deviceNumber"));
        params.put("LIKE_deviceRealNumber", request.getParameter("LIKE_deviceRealNumber")==null?"":request.getParameter("LIKE_deviceRealNumber"));
        
        model.addAttribute("list",orderList);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        
        List<Merchant> list=new ArrayList<Merchant>();
        if("SSJ-FX".equals(merchant.getOrgCode())){
        	list=merchantService.getMerchantByLikeOrgCode(merchant.getOrgCode());
        }else{
        	list=merchantService.getMerchantByParentPosCode(merchant.getPosCode());
        	list.add(merchant);
        }
		model.addAttribute("poslist", list);
		model.addAttribute("merchant", merchant);
        return "sys/fx/deviceList";
    }
	
	
	
	
	//当前商户下的所有的设备，支持imei1范围，和批次号
	@RequestMapping("/deviceActivList")
    public String deviceActivationList(Model model,
                              @RequestParam(required = false, defaultValue = "100") int pageSize,
                              @RequestParam(required = false, defaultValue = "1") int pageNo)
            throws Exception {
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("GTE_imei", request.getParameter("GTE_imei")==null?"":request.getParameter("GTE_imei"));
        params.put("LTE_imei", request.getParameter("LTE_imei")==null?"":request.getParameter("LTE_imei"));
        
        params.put("EQ_isSpan", request.getParameter("EQ_isSpan")==null?"":request.getParameter("EQ_isSpan"));
        params.put("EQ_status", request.getParameter("EQ_status")==null?"":request.getParameter("EQ_status"));
        
        
        params.put("EQ_batchCode", request.getParameter("EQ_batchCode")==null?"":request.getParameter("EQ_batchCode"));
        params.put("EQ_emsNumber", request.getParameter("EQ_emsNumber")==null?"":request.getParameter("EQ_emsNumber"));
        params.put("EQ_type", request.getParameter("EQ_type")==null?"":request.getParameter("EQ_type"));
        params.put("LIKE_remarks", request.getParameter("LIKE_remarks")==null?"":request.getParameter("LIKE_remarks"));
		params.put("seachDerver", request.getParameter("seachDerver")==null?"":request.getParameter("seachDerver"));

        if(StringUtils.isNotEmpty(request.getParameter("EQ_orgCode"))){
        	params.put("EQ_orgCode", request.getParameter("EQ_orgCode"));
        }else{
        	if("SSJ-FX".equals(merchant.getOrgCode())){
        		params.put("LIKE_orgCode",merchant.getOrgCode());
        	}else{
        		List<String> orgCodes=new ArrayList<String>();
	        	orgCodes.add(merchant.getOrgCode());
	        	List<Merchant> merchants=merchantService.getMerchantByParentPosCode(merchant.getPosCode());
	        	for (Merchant merchant2 : merchants) {
	        		orgCodes.add(merchant2.getOrgCode());
				}
	        	params.put("IN_orgCode",orgCodes);
        	}
        }
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = deviceService.findDeviceActivationList(params, initPage(pageNo, pageSize));
        sp.setRowCnt((int) page.getTotalElements());
        
        List<Map<String, Object>> orderList=new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> deviceList= page.getContent();
	    for (Map<String, Object> device : deviceList) {
			if(device.get("org_code").equals(merchant.getOrgCode())){
				orderList.add(0, device);
			}else{
				orderList.add(device);
			}
		}
        model.addAttribute("list",orderList);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        
        List<Merchant> list=new ArrayList<Merchant>();
        if("SSJ-FX".equals(merchant.getOrgCode())){
        	list=merchantService.getMerchantByLikeOrgCode(merchant.getOrgCode());
        }else{
        	list=merchantService.getMerchantByParentPosCode(merchant.getPosCode());
        	list.add(merchant);
        }
		model.addAttribute("poslist", list);
		model.addAttribute("merchant", merchant);
        return "sys/fx/deviceActivList";
    }
	
	
	
	
	@RequestMapping("/merchantAllList")
    public String merchantAllList(Model model,
            @RequestParam(required = false, defaultValue = "10") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
	 	Map<String, Object> params = new HashMap<String, Object>();
        params.put("LIKE_unitName", request.getParameter("LIKE_unitName")==null?"":request.getParameter("LIKE_unitName"));
        params.put("LIKE_posCode", request.getParameter("LIKE_posCode")==null?"":request.getParameter("LIKE_posCode"));
        if(request.getParameter("signType")!=null ) {
        	if("0".equals(request.getParameter("signType").toString())){
        		params.put("EQ_signType", 0);
        	}else if("1".equals(request.getParameter("signType").toString())){
        		params.put("GTE_signType", 1);
        	}
        }
        
        String orgCode=request.getParameter("LIKE_orgCode")==null?"":request.getParameter("LIKE_orgCode");
        if(StringUtils.isNotEmpty(orgCode)) {
        	params.put("LIKE_orgCode", orgCode);
        }else {
        	params.put("LIKE_orgCode", merchant.getOrgCode());
        }
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        Page<Merchant> page = merchantService.findMerchantByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"createTime"}));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        params.put("signType", request.getParameter("signType")==null?"":request.getParameter("signType"));
        sp.setParams(params);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        model.addAttribute("curMerchant", merchant);
        return "sys/fx/merchantAllList";
    }
	
	
	
	@RequestMapping("/merchantBackupList")
    public String merchantBackupList(Model model,
            @RequestParam(required = false, defaultValue = "10") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
	 	Map<String, Object> params = new HashMap<String, Object>();
        params.put("LIKE_unitName", request.getParameter("LIKE_unitName")==null?"":request.getParameter("LIKE_unitName"));
        params.put("LIKE_posCode", request.getParameter("LIKE_posCode")==null?"":request.getParameter("LIKE_posCode"));
        params.put("EQ_backupMonth", request.getParameter("EQ_backupMonth")==null||StringUtils.isEmpty(request.getParameter("EQ_backupMonth").toString())? DateHelper.format(DateHelper.getLastMonthFirstDay(new Date()),"yyyy-MM") :request.getParameter("EQ_backupMonth").toString());
        
        if(request.getParameter("signType")!=null ) {
        	if("0".equals(request.getParameter("signType").toString())){
        		params.put("EQ_signType", 0);
        	}else if("1".equals(request.getParameter("signType").toString())){
        		params.put("GTE_signType", 1);
        	}
        }
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<MerchantBackup> page = merchantBackupService.findMerchantBackupByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"createTime"}));
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        params.put("signType", request.getParameter("signType")==null?"":request.getParameter("signType"));
        model.addAttribute("search", params);
        model.addAttribute("curMerchant", merchant);
        return "sys/fx/merchantBackupList";
    }
	
	
	//得到下一级的商户
	private List<Merchant> findMerchantByNext(String orgCode){
		List<Merchant> list=new ArrayList<Merchant>();
		if(StringUtils.isNotEmpty(orgCode)) {
			List<Merchant> merchants=merchantService.getMerchantByLikeOrgCode(orgCode);
			if(merchants!=null) {
				for (Merchant merchant : merchants) {
					String curOrgCode=merchant.getOrgCode();
					if(curOrgCode.replaceAll(orgCode+"-", "").indexOf("-")==-1) {
						list.add(merchant);
					}
				}
			}
		}
		return list;
	}
	
	
	//批量分配设备商户下
	@RequestMapping("/merchantTree")
	@ResponseBody
    public List<Organization> merchantTree(Model model,String id)throws Exception {		
		List<Merchant> list=new ArrayList<Merchant>();
		List<Organization> orgList=new ArrayList<Organization>();
		
		if(StringUtils.isEmpty(id)) {
			HttpSession session = request.getSession();
			Admin admin =(Admin) session.getAttribute("admin");
			Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
			if(merchant!=null && merchant.getOrgCode().equals("SSJ-FX")) {
				list=findMerchantByNext("SSJ-FX");
			}else {
				list.add(merchant);
			}
		}else {
			list=findMerchantByNext(id);
		}
		
		for (Merchant merchant : list) {
			List<Merchant> ms=merchantService.getMerchantByLikeOrgCode(merchant.getOrgCode());
			Organization org=new Organization();
			org.setArea(merchant.getUnitName());
			org.setCity(merchant.getUnitName());
			org.setName(merchant.getUnitName());
			org.setCode(merchant.getOrgCode());
			org.setCreateTime(merchant.getCreateTime());
			org.setId(merchant.getOrgCode());
			org.setpId(id);
			org.setStatus(1);
			org.setIsParent((ms!=null && ms.size()>1) ? true : false);
			org.setSubCount(ms.size());
			orgList.add(org);
		}
        return orgList;
    }

	
	@RequestMapping("/merchantAllMain")
    public String merchantAllMain(Model model)throws Exception {
        return "sys/fx/merchantAllMain";
    }
	
	

	
	
	
	
	
	
	
	@RequestMapping("/partsAllList")
    public String partsAllList(Model model,
            @RequestParam(required = false, defaultValue = "100") 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("name")==null?"":request.getParameter("name"));
        //params.put("EQ_emsNumber", request.getParameter("emsNumber")==null?"":request.getParameter("emsNumber"));
        params.put("LIKE_remarks", request.getParameter("remarks")==null?"":request.getParameter("remarks"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<DeviceParts> page = devicePartsService.findDevicePartsByPage(params, initPage(pageNo, pageSize, 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);
        List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
        return "sys/fx/partsAllList";
    }
	
	
	@RequestMapping("/partsList")
    public String partsList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {	
        Map<String, Object> params = new HashMap<String, Object>();
        HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
        params.put("LIKE_name", request.getParameter("name")==null?"":request.getParameter("name"));
        //params.put("EQ_emsNumber", request.getParameter("emsNumber")==null?"":request.getParameter("emsNumber"));
        params.put("LIKE_remarks", request.getParameter("remarks")==null?"":request.getParameter("remarks"));
        
        if(StringUtils.isNotEmpty(request.getParameter("orgCode"))){
        	params.put("EQ_orgCode", request.getParameter("orgCode"));
        }else{
        	if("SSJ-FX".equals(merchant.getOrgCode())){
        		params.put("LIKE_orgCode",merchant.getOrgCode());
        	}else{
        		List<String> orgCodes=new ArrayList<String>();
	        	orgCodes.add(merchant.getOrgCode());
	        	List<Merchant> merchants=merchantService.getMerchantByParentPosCode(merchant.getPosCode());
	        	for (Merchant merchant2 : merchants) {
	        		orgCodes.add(merchant2.getOrgCode());
				}
	        	params.put("IN_orgCode",orgCodes);
        	}
        }
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<DeviceParts> page = devicePartsService.findDevicePartsByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"createTime"}));
        sp.setRowCnt((int) page.getTotalElements());
        
        List<DeviceParts> orderList=new ArrayList<DeviceParts>();
        List<DeviceParts> devicePartsList= page.getContent();
	    for (DeviceParts deviceParts : devicePartsList) {
			if(deviceParts.getOrgCode().equals(merchant.getOrgCode())){
				orderList.add(0, deviceParts);
			}else{
				orderList.add(deviceParts);
			}
		}
        model.addAttribute("list", orderList);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        
        List<Merchant> list=new ArrayList<Merchant>();
        if("SSJ-FX".equals(merchant.getOrgCode())){
        	list=merchantService.getMerchantByLikeOrgCode(merchant.getOrgCode());
        }else{
        	list=merchantService.getMerchantByParentPosCode(merchant.getPosCode());
        	list.add(merchant);
        }
		model.addAttribute("poslist", list);
		model.addAttribute("merchant", merchant);
        return "sys/fx/partsList";
    }

	@RequestMapping("/deviceAdd")
    public String deviceAdd(Model model){
		Device device=new Device();
		List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
		model.addAttribute("device", device);
		return "sys/fx/deviceAdd";
    }
	
	
	@RequestMapping("/partsAdd")
    public String partsAdd(Model model){
		Device device=new Device();
		List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
		model.addAttribute("device", device);
		return "sys/fx/partsAdd";
    }
	
	
	
	@RequestMapping("/saveDeviceParts")
	@ResponseBody
    public Response saveDeviceParts(Model model,DeviceParts deviceParts)throws Exception {
		Response response = new  Response();
		deviceParts.setCreateTime(new Date());
		deviceParts.setSellNum(0);
		deviceParts.setReturnWaitNum(0);
		deviceParts=devicePartsService.save(deviceParts);
		deviceParts.setPartsId(deviceParts.getId());
		devicePartsService.save(deviceParts);
		response.success("成功");
        return response;
    }
	
	
	
	@RequestMapping("/deviceEdit")
    public String deviceEdit(Model model,String id)
            throws Exception {
		Device device=new Device();
		if(StringUtils.isNotEmpty(id)){
			device=deviceService.getById(id);
		}
		List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
		model.addAttribute("device", device);
		return "sys/fx/deviceEdit";
    }
	
	
	
	@RequestMapping("/merchantAdd")
    public String merchantAdd(Model model,String id)throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		Merchant merchant=new Merchant();
		List<PositionSchoolV1Dto> positionSchoolV1Dtos=new ArrayList<PositionSchoolV1Dto>();
		String schoolText="";
		
		if(StringUtils.isNotEmpty(id)){
			merchant=merchantService.getById(id);
			
			if(merchant!=null && StringUtils.isNotEmpty(merchant.getLibId())) { 
				 positionSchoolV1Dtos= merchantAreaService.findSchoolList(merchant.getLibId());
				 if(positionSchoolV1Dtos!=null) {
					 for (PositionSchoolV1Dto positionSchoolV1Dto : positionSchoolV1Dtos) {
						 schoolText=schoolText+positionSchoolV1Dto.getSchoolName()+";";
					 }
					 if(schoolText.endsWith(";")) {
						 schoolText=schoolText.substring(0, schoolText.length()-1);
					 }
				 }
			}
			
		}
		List<Merchant> list=merchantService.findMerchantByPage();
		
		List<CnArea> areaList = cnAreaService.findByTypeList("1");
		model.addAttribute("areaList", areaList);
		
		List<TbLibJoin> joinList=libJoinService.findAll();
		
		model.addAttribute("positionSchoolV1Dtos", positionSchoolV1Dtos);
		model.addAttribute("schoolText", schoolText);
		model.addAttribute("joinList", joinList);
		model.addAttribute("poslist", list);
		model.addAttribute("merchant", merchant);
		model.addAttribute("minDate", merchant.getSignTime()!=null ? merchant.getSignTime() : new Date());
		model.addAttribute("curMerchant", curMerchant);
        return "sys/fx/merchantAdd";
    }
	
	
	
	@RequestMapping("/merchantOldAdd")
    public String merchantAddOld(Model model,String id)throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		Merchant merchant=new Merchant();
		List<PositionSchoolV1Dto> positionSchoolV1Dtos=new ArrayList<PositionSchoolV1Dto>();
		String schoolText="";
		
		if(StringUtils.isNotEmpty(id)){
			merchant=merchantService.getById(id);
			
			if(merchant!=null && StringUtils.isNotEmpty(merchant.getLibId())) { 
				 positionSchoolV1Dtos= merchantAreaService.findSchoolList(merchant.getLibId());
				 if(positionSchoolV1Dtos!=null) {
					 for (PositionSchoolV1Dto positionSchoolV1Dto : positionSchoolV1Dtos) {
						 schoolText=schoolText+positionSchoolV1Dto.getSchoolName()+";";
					 }
					 if(schoolText.endsWith(";")) {
						 schoolText=schoolText.substring(0, schoolText.length()-1);
					 }
				 }
			}
			
		}
		List<Merchant> list=merchantService.findMerchantByPage();
		
		List<CnArea> areaList = cnAreaService.findByTypeList("1");
		model.addAttribute("areaList", areaList);
		
		List<TbLibJoin> joinList=libJoinService.findAll();
		
		model.addAttribute("positionSchoolV1Dtos", positionSchoolV1Dtos);
		model.addAttribute("schoolText", schoolText);
		model.addAttribute("joinList", joinList);
		model.addAttribute("poslist", list);
		model.addAttribute("merchant", merchant);
		model.addAttribute("minDate", merchant.getSignTime()!=null ? merchant.getSignTime() : new Date());
		model.addAttribute("curMerchant", curMerchant);
        return "sys/fx/merchantOldAdd";
    }
	
	
	@RequestMapping("/merchantScAdd")
    public String merchantAddSchool(Model model,String id)throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		Merchant merchant=new Merchant();
		List<PositionSchoolV1Dto> positionSchoolV1Dtos=new ArrayList<PositionSchoolV1Dto>();
		String schoolText="";
		
		if(StringUtils.isNotEmpty(id)){
			merchant=merchantService.getById(id);
			
			if(merchant!=null && StringUtils.isNotEmpty(merchant.getLibId())) { 
				 positionSchoolV1Dtos= merchantAreaService.findSchoolList(merchant.getLibId());
				 if(positionSchoolV1Dtos!=null) {
					 for (PositionSchoolV1Dto positionSchoolV1Dto : positionSchoolV1Dtos) {
						 schoolText=schoolText+positionSchoolV1Dto.getSchoolName()+";";
					 }
					 if(schoolText.endsWith(";")) {
						 schoolText=schoolText.substring(0, schoolText.length()-1);
					 }
				 }
			}
			
		}
		List<Merchant> list=merchantService.findMerchantByPage();
		
		List<CnArea> areaList = cnAreaService.findByTypeList("1");
		model.addAttribute("areaList", areaList);
		
		List<TbLibJoin> joinList=libJoinService.findAll();
		
		model.addAttribute("positionSchoolV1Dtos", positionSchoolV1Dtos);
		model.addAttribute("schoolText", schoolText);
		model.addAttribute("joinList", joinList);
		model.addAttribute("poslist", list);
		model.addAttribute("merchant", merchant);
		model.addAttribute("minDate", merchant.getSignTime()!=null ? merchant.getSignTime() : new Date());
		model.addAttribute("curMerchant", curMerchant);
        return "sys/fx/merchantScAdd";
    }
	
	
	
	@RequestMapping("/merchantInfo")
    public String merchantInfo(Model model,String id)throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		Merchant merchant=new Merchant();
		List<PositionSchoolV1Dto> positionSchoolV1Dtos=new ArrayList<PositionSchoolV1Dto>();
		String schoolText="";
		
		if(StringUtils.isNotEmpty(id)){
			merchant=merchantService.getById(id);
			
			if(merchant!=null && StringUtils.isNotEmpty(merchant.getLibId())) { 
				 positionSchoolV1Dtos= merchantAreaService.findSchoolList(merchant.getLibId());
				 if(positionSchoolV1Dtos!=null) {
					 for (PositionSchoolV1Dto positionSchoolV1Dto : positionSchoolV1Dtos) {
						 schoolText=schoolText+positionSchoolV1Dto.getSchoolName()+";";
					 }
					 if(schoolText.endsWith(";")) {
						 schoolText=schoolText.substring(0, schoolText.length()-1);
					 }
				 }
			}
			
		}
		List<Merchant> list=merchantService.findMerchantByPage();
		
		List<CnArea> areaList = cnAreaService.findByTypeList("1");
		model.addAttribute("areaList", areaList);
		
		List<TbLibJoin> joinList=libJoinService.findAll();
		
		model.addAttribute("positionSchoolV1Dtos", positionSchoolV1Dtos);
		model.addAttribute("schoolText", schoolText);
		model.addAttribute("joinList", joinList);
		model.addAttribute("poslist", list);
		model.addAttribute("merchant", merchant);
		model.addAttribute("curMerchant", curMerchant);
        return "sys/fx/merchantInfo";
    }
	
	
	
	@RequestMapping("/merchantBackupInfo")
    public String merchantBackupInfo(Model model,String id)throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		MerchantBackup merchant=new MerchantBackup();
		List<PositionSchoolV1Dto> positionSchoolV1Dtos=new ArrayList<PositionSchoolV1Dto>();
		String schoolText="";
		
		if(StringUtils.isNotEmpty(id)){
			merchant=merchantBackupService.getById(id);
			
			if(merchant!=null && StringUtils.isNotEmpty(merchant.getLibId())) { 
				 positionSchoolV1Dtos= merchantAreaService.findSchoolList(merchant.getLibId());
				 if(positionSchoolV1Dtos!=null) {
					 for (PositionSchoolV1Dto positionSchoolV1Dto : positionSchoolV1Dtos) {
						 schoolText=schoolText+positionSchoolV1Dto.getSchoolName()+";";
					 }
					 if(schoolText.endsWith(";")) {
						 schoolText=schoolText.substring(0, schoolText.length()-1);
					 }
				 }
			}
			
		}
		List<Merchant> list=merchantService.findMerchantByPage();
		
		List<CnArea> areaList = cnAreaService.findByTypeList("1");
		model.addAttribute("areaList", areaList);
		
		List<TbLibJoin> joinList=libJoinService.findAll();
		
		model.addAttribute("positionSchoolV1Dtos", positionSchoolV1Dtos);
		model.addAttribute("schoolText", schoolText);
		model.addAttribute("joinList", joinList);
		model.addAttribute("poslist", list);
		model.addAttribute("merchant", merchant);
		model.addAttribute("curMerchant", curMerchant);
        return "sys/fx/merchantBackupInfo";
    }
	
	
	
	@RequestMapping("/merchantAllot")
    public String merchantAllot(Model model,String id)throws Exception {
		Merchant merchant=new Merchant();
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(StringUtils.isNotEmpty(id)){
			merchant=merchantService.getById(id);
			subMerchants=merchantService.getMerchantByParentPosCode(merchant.getPosCode());
		}
		model.addAttribute("merchant", merchant);
		model.addAttribute("subMerchants", subMerchants);
        return "sys/fx/merchantAllot";
    }
	
	
	

	//批量分配设备商户下
	@RequestMapping("/allot")
	@ResponseBody
    public Response allot(Model model,String fromMerchant,String toMerchant,Integer num,Integer type)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(toMerchant)){
			merchantService.allotByMerchant(fromMerchant, toMerchant, num,type);
			response.success("成功");
		}else{
			response.failure("toMerchant不合法");
		}
        return response;
    }

	
	
	
	//批量分配设备商户下
	@RequestMapping("/areaList")
	@ResponseBody
    public Response areaList(Model model,String type,String upId)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(type)){
			List<CnArea> areaList =new ArrayList<CnArea>();
			if(StringUtils.isNotEmpty(upId)) {
				 areaList = cnAreaService.findByTypeList(type,upId);
			}else {
				 areaList = cnAreaService.findByTypeList(type);
			}
			response.success(areaList, "成功");
		}else{
			response.failure("type不合法");
		}
        return response;
    }

	
	//批量分配设备商户下
	@RequestMapping("/matchDevice")
	@ResponseBody
    public Response deviceList(Model model,String ids,String poscode,
    		String emsNumber,String emsAddress,String emsUsername,String emsTelephone,String emsImg,String remarks)throws Exception {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		if(StringUtils.isNotEmpty(ids)){
			String[] ais=ids.split(";");
			List<String> list = Arrays.asList(ais);
			int isNum=deviceService.matchDeviceByMerchant(list, poscode,admin ,
					emsNumber, emsAddress, emsUsername, emsTelephone,emsImg,remarks);
			response.success(isNum, "成功");
		}else{
			response.failure("请选择imeis号");
		}
        return response;
    }

	@RequestMapping("/matchParts")
	@ResponseBody
    public Response matchparts(Model model,String id,Integer matchNum,String posCode,
    		String emsNumber,String emsAddress,String emsUsername,String emsTelephone)throws Exception {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		if(StringUtils.isNotEmpty(id)){
			devicePartsService.matchDevicePartsByMerchant(id, 
					matchNum, posCode, 
					emsNumber, emsAddress, emsUsername, emsTelephone, admin);
			response.success("成功");
		}else{
			response.failure("请选择分配配件");
		}
        return response;
    }
	
	
	@RequestMapping("/addParts")
	@ResponseBody
    public Response addParts(Model model,String id,Integer matchNum,
    		String emsNumber,String emsAddress,String emsUsername,String emsTelephone)throws Exception {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		if(StringUtils.isNotEmpty(id)){
			DeviceParts fromDeviceParts=devicePartsService.getById(id);
			if(fromDeviceParts!=null){
				Merchant merchant=merchantService.getMerchantByPosCode(fromDeviceParts.getPosCode());

				fromDeviceParts.setSellWaitNum(fromDeviceParts.getSellWaitNum()+matchNum);
				devicePartsService.save(fromDeviceParts);
				
				DevicePartsAct devicePartsAct=new DevicePartsAct();
				devicePartsAct.setEmsAddress(emsAddress);
				devicePartsAct.setEmsNumber(emsNumber);
				devicePartsAct.setEmsTelephone(emsTelephone);
				devicePartsAct.setEmsUsername(emsUsername);
				devicePartsAct.setMatchNum(matchNum);
				devicePartsAct.setFromMerchantId(null);
				devicePartsAct.setOperatorAdminId(admin.getId());
				devicePartsAct.setRemarks("上行增库");
				devicePartsAct.setToMerchantId(merchant.getId());
				devicePartsAct.setType(1);
				devicePartsActService.save(devicePartsAct);
			}	
			response.success("成功");
		}else{
			response.failure("请选择增库配件");
		}
        return response;
    }
	
	
	
	@RequestMapping("/cutParts")
	@ResponseBody
    public Response cutParts(Model model,String id,Integer matchNum,
    		String emsNumber,String emsAddress,String emsUsername,String emsTelephone)throws Exception {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		if(StringUtils.isNotEmpty(id)){
			DeviceParts fromDeviceParts=devicePartsService.getById(id);
			if(fromDeviceParts!=null){
				if(fromDeviceParts.getSellNum()>=matchNum){
					fromDeviceParts.setSellNum(fromDeviceParts.getSellNum()+matchNum);
					devicePartsService.save(fromDeviceParts);
					
					DevicePartsAct devicePartsAct=new DevicePartsAct();
					devicePartsAct.setEmsAddress(emsAddress);
					devicePartsAct.setEmsNumber(emsNumber);
					devicePartsAct.setEmsTelephone(emsTelephone);
					devicePartsAct.setEmsUsername(emsUsername);
					devicePartsAct.setMatchNum(matchNum);
					devicePartsAct.setFromMerchantId(fromDeviceParts.getPosCode());
					devicePartsAct.setOperatorAdminId(admin.getId());
					devicePartsAct.setRemarks("上行减库");
					devicePartsAct.setToMerchantId(null);
					devicePartsAct.setType(2);
					devicePartsActService.save(devicePartsAct);
				}else{
					response.failure("请减库数量不能超过已收货的数量");
				}
			}	
			response.success("成功");
		}else{
			response.failure("请选择减库配件");
		}
        return response;
    }
	
	

	@RequestMapping("/updateDevice")
	@ResponseBody
    public Response updateDevice(Model model,String id,Integer status,
    		String emsImg,String emsNumber,String emsAddress,String emsTelephone,String emsUsername,String remarks)throws Exception {
		Response response = new  Response();
		Map<String,Object> data=new HashMap<String, Object>();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		String batchCode=DateHelper.format(new Date(), "yyyyMMddHHmmssSS");
		int countNum=0;
		int successNum=0;
		if(StringUtils.isNotEmpty(id)){
			String[] ids=id.split(";");
			countNum=ids.length;
			for (String i : ids) {
				try {
					Device device=deviceService.getById(i);
					device.setStatus(status);
					
					if(device.getStatus()==1 && status==2){
//						PosterTemplate merchant=merchantService.getById(device.getMerchantId());
//						if(merchant!=null && StringUtils.isNotEmpty(merchant.getParentPosCode())){
//							PosterTemplate pmerchant=merchantService.getMerchantByPosCode(merchant.getParentPosCode());
//							DeviceAct deviceAct=new DeviceAct();
//							deviceAct.setFromMerchantId(pmerchant.getId());
//							deviceAct.setToMerchantId(device.getMerchantId());
//							deviceAct.setOperatorAdminId(admin.getId());
//							deviceAct.setDeviceId(device.getId());
//							deviceAct.setImei(device.getImei());
//							deviceAct.setIsUsed(device.getIsSpan());
//							deviceAct.setCreateTime(new Date());
//							deviceAct.setEmsNumber(emsNumber);
//							deviceAct.setEmsAddress(emsAddress);
//							deviceAct.setEmsTelephone(emsTelephone);
//							deviceAct.setEmsUsername(emsUsername);
//							deviceAct.setRemarks("设备入库:"+remarks);
//							deviceAct.setBatchCode(batchCode);
//							deviceAct.setType(3);
//							deviceActService.save(deviceAct);
//						}
					}

					//这些是针对上行的一个状态
					if(device.getStatus()==4 && status==1){
						device.setStatus(3);
					}
					if(device.getStatus()==3 && status==2){
						device.setStatus(4);
					}
					if(StringUtils.isNotEmpty(emsImg)){
						device.setEmsImg(device.getEmsImg()+";"+emsImg);
					}
					device.setUpdateTime(new Date());
					deviceService.save(device);
					successNum=successNum+1;
					
					deviceService.pushDeviceToAijia(device);
				} catch (Exception e) {
				}
			}
			data.put("countNum", countNum);
			data.put("successNum", successNum);
			response.success(data,"成功");
		}else{
			response.failure("请选择id");
		}
        return response;
    }
	
	
	
	
	/**
	 * 
	 * @param model
	 * @param id
	 * @param type   1 确认收货   2确认收货(退回)
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateDeviceParts")
	@ResponseBody
    public Response updateDeviceParts(Model model,String id,Integer type)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(id)){
			devicePartsService.updateDevicePartsNum(id, type);
			response.success("成功");
		}else{
			response.failure("请选择配件");
		}
        return response;
    }
	
	

	@RequestMapping("/returnDevice")
	@ResponseBody
    public Response returnDevice(Model model,String id,Integer status,
    		String emsNumber,String emsAddress,String emsTelephone,String emsUsername,String remarks)throws Exception {
		Response response = new  Response();
		Map<String,Object> data=new HashMap<String, Object>();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		int countNum=0;
		int successNum=0;
		String batchCode=DateHelper.format(new Date(), "yyyyMMddHHmmssSS");
		if(StringUtils.isNotEmpty(id)){
			String[] ids=id.split(";");
			countNum=ids.length;
			for (String i : ids) {
				try {
					Device device=deviceService.getById(i);
					if(3==status){
						Merchant merchant=merchantService.getById(device.getMerchantId());
						if(merchant!=null && StringUtils.isNotEmpty(merchant.getParentPosCode())){
							Merchant pmerchant=merchantService.getMerchantByPosCode(merchant.getParentPosCode());
							
							DeviceAct deviceAct=new DeviceAct();
							deviceAct.setFromMerchantId(device.getMerchantId());
							deviceAct.setToMerchantId(pmerchant.getId());
							deviceAct.setOperatorAdminId(admin.getId());
							deviceAct.setDeviceId(device.getId());
							deviceAct.setImei(device.getImei());
							deviceAct.setIsUsed(1);
							deviceAct.setCreateTime(new Date());
							deviceAct.setEmsNumber(emsNumber);
							deviceAct.setEmsAddress(emsAddress);
							deviceAct.setEmsTelephone(emsTelephone);
							deviceAct.setEmsUsername(emsUsername);
							deviceAct.setRemarks("设备出库:退回上级【"+remarks+"】");
							deviceAct.setBatchCode(batchCode);
							deviceAct.setType(2);
							deviceActService.save(deviceAct);
							device.setIsUsed(1);//标识为二手


							deviceAct=new DeviceAct();
							deviceAct.setFromMerchantId(device.getMerchantId());
							deviceAct.setToMerchantId(pmerchant.getId());
							deviceAct.setOperatorAdminId(admin.getId());
							deviceAct.setDeviceId(device.getId());
							deviceAct.setImei(device.getImei());
							deviceAct.setIsUsed(1);
							deviceAct.setCreateTime(new Date());
							deviceAct.setEmsNumber(emsNumber);
							deviceAct.setEmsAddress(emsAddress);
							deviceAct.setEmsTelephone(emsTelephone);
							deviceAct.setEmsUsername(emsUsername);
							deviceAct.setRemarks("设备入库:退回入库【"+remarks+"】");
							deviceAct.setBatchCode(batchCode);
							deviceAct.setType(4);
							deviceActService.save(deviceAct);
							device.setIsUsed(1);//标识为二手
							
							device.setDeviceAct(deviceAct);
							
							device.setLastMerchantId(device.getMerchantId());
							device.setMerchantId(pmerchant.getId());
							device.setPosCode(pmerchant.getPosCode());
							device.setOrgCode(pmerchant.getOrgCode());
							device.setUpdateTime(new Date());
							device.setStatus(status);
							deviceService.save(device);
						}	
					}else {
						device.setUpdateTime(new Date());
						device.setStatus(status);
						deviceService.save(device);
					}
					successNum=successNum+1;
				} catch (Exception e) {
				}
			}
			data.put("countNum", countNum);
			data.put("successNum", successNum);
			response.success(data,"成功");
		}else{
			response.failure("请选择id");
		}
        return response;
    }
	
	@RequestMapping("/returnParts")
	@ResponseBody
	 public Response returnParts(Model model,String id,Integer matchNum,String posCode,
	    		String emsNumber,String emsAddress,String emsUsername,String emsTelephone)throws Exception {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		if(StringUtils.isNotEmpty(id)){
			devicePartsService.returnDevicePartsByMerchant(id, matchNum, emsNumber, emsAddress, emsUsername, emsTelephone, admin);
			response.success("成功");
		}else{
			response.failure("请选择id");
		}
        return response;
    }
	
	
	@RequestMapping(value="/getMerchant/{id}")
	@ResponseBody
	public Response libIdjoin(Model model,@PathVariable String id) {
		Response response = new  Response();
		Map<String,Object> data=new LinkedHashMap<String, Object>();
		Merchant merchant=merchantService.getById(id);
		
		boolean isPortNum=true;
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		if(merchant.getOrgCode().equals(curMerchant.getOrgCode())) {
			//response.failure("不可设置自己的商户端口");
			isPortNum=false;
		}
		if(!"SSJ-FX".equals(curMerchant.getOrgCode()) && !merchant.getParentPosCode().equals(curMerchant.getPosCode())) {
			//response.failure("不可设置非子级的商户端口");
			isPortNum=false;
		}
		
		data.put("merchant", merchant);
		data.put("isPortNum", isPortNum);
		response.success(data, "查询成功");
		return response;
	}	
	
	
	@RequestMapping(value="/merchant/update/{id}")
	@ResponseBody
	public Response libIdjoin(Model model,@PathVariable String id,Integer type,Integer num) {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		
		if(num<=0) {
			response.failure("设置的数量不能少于1");
			return response;
		}
		Merchant merchant=merchantService.getById(id);
		if(merchant!=null) {
			if(type==1) {
				merchant.setLibService(merchant.getLibService()+num);
				if(merchant.getCurIsSummary()!=null && merchant.getCurIsSummary()>=0) {
					Integer incrementNum=merchant.getCurIsSummary()-num;
					merchant.setCurIsSummary(incrementNum<0?0:incrementNum);
				}
				merchantService.save(merchant);
				
				//记录通过商户添加币
				libJoinConsumeService.rechargeMerchantConsume(id, num, 0);
				
			}else if(type==3) {
				merchant.setPlatformService(merchant.getPlatformService()+num);
				merchantService.save(merchant);
				
				//记录通过商户添加币
				libJoinConsumeService.rechargeMerchantConsume(id, 0 , num);
				
			}else if(type==2) {
				Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
				if("SSJ-FX".equals(curMerchant.getOrgCode())) {
					
					merchant.setPortNum(merchant.getPortNum()+num);
					if(merchant.getPortNum()<10) {
						response.failure("设置的端口总量不能少于10");
						return response;
					}
					merchantService.save(merchant);	
					
				}else {
//					if(merchant.getOrgCode().equals(curMerchant.getOrgCode())) {
//						response.failure("不可设置自己的商户端口");
//						return response;
//					}
					if(!"SSJ-FX".equals(curMerchant.getOrgCode()) && !merchant.getParentPosCode().equals(curMerchant.getPosCode())) {
						response.failure("不可设置非子级的商户端口");
						return response;
					}
					Integer countPortNum=0;
					List<Merchant> subMerchants=merchantService.getMerchantByParentPosCode(curMerchant.getPosCode());
					for (Merchant merchant2 : subMerchants) {
						countPortNum=countPortNum+(merchant2.getPortNum()!=null?merchant2.getPortNum():0);
					}
					if(countPortNum+num > curMerchant.getPortNum()) {
						response.failure("您端口数量："+curMerchant.getPortNum()+ "  已设置子级端口数量："+countPortNum+"   设置的端口子级总量不能大于您的端口数量");
						return response;
					}
					merchant.setPortNum(merchant.getPortNum()+num);
					merchantService.save(merchant);	
				}
			}
			merchantService.syncRecordByMerchant(admin.getLoginName(), id,WebUtil.getRemoteAddr(request), "更新塾币/端口");
		}
		response.success("查询成功");
		return response;
	}	
	

	
	
	@RequestMapping("/updateMerchant")
	@ResponseBody
    public Response updateMerchant(Model model,String id,Integer status)throws Exception {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		if(StringUtils.isNotEmpty(id)){
			Merchant merchant=merchantService.getById(id);
			merchant.setStatus(status);
			merchantService.save(merchant);
			merchantService.syncRecordByMerchant(admin.getLoginName(), id,WebUtil.getRemoteAddr(request), "更新商户状态");
			response.success("成功");
		}else{
			response.failure("请选择id");
		}
        return response;
    }
	
	
	@RequestMapping("/saveDevice")
	@ResponseBody
    public Response saveDevice(Model model,Device device)throws Exception {
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Response response = new  Response();
		if(StringUtils.isNotEmpty(device.getId())){
			Device olddevice =deviceService.getById(device.getId());
			olddevice.setDeviceCode(device.getDeviceCode());
			olddevice.setDeviceColor(device.getDeviceColor());
			olddevice.setDeviceModel(device.getDeviceModel());
			olddevice.setDeviceName(device.getDeviceName());
			olddevice.setDeviceNumber(device.getDeviceNumber());
			olddevice.setDeviceRealNumber(device.getDeviceRealNumber());
			olddevice.setDeviceSn(device.getDeviceSn());
			olddevice.setImei(device.getImei());
			olddevice.setUpdateTime(new Date());
			olddevice.setBatchCode(device.getBatchCode());
			olddevice.setPrice(device.getPrice());
			olddevice.setEmsAddress(device.getEmsAddress());
			olddevice.setEmsNumber(device.getEmsNumber());
			olddevice.setEmsTelephone(device.getEmsTelephone());
			olddevice.setEmsUsername(device.getEmsUsername());
			olddevice.setRemarks(device.getRemarks());
			olddevice.setType(device.getType());
			deviceService.save(olddevice);
			
		}else{
			String batchCode=StringUtils.isNotEmpty(device.getEmsNumber())? device.getEmsNumber():DateHelper.format(new Date(), "yyyyMMddHHmmssSS");
			if(device.getType()==null){
				device.setType(1);
			}
			device.setIsSpan(1);
			device.setCreateTime(new Date());
			device.setId(IdWorker.generateId());
			deviceService.save(device);
			
		/*	DeviceAct deviceAct=new DeviceAct();
			deviceAct.setFromMerchantId(null);
			deviceAct.setToMerchantId(device.getMerchantId());
			deviceAct.setOperatorAdminId(admin.getId());
			deviceAct.setImei(device.getImei());
			deviceAct.setCreateTime(new Date());
			deviceAct.setType(1);
			deviceAct.setEmsNumber(device.getEmsNumber());
			deviceAct.setEmsAddress(device.getEmsAddress());
			deviceAct.setEmsTelephone(device.getEmsTelephone());
			deviceAct.setEmsUsername(device.getEmsUsername());
			deviceAct.setBatchCode(batchCode);
			deviceAct.setRemarks("库存分配");
			deviceActService.save(deviceAct);
			
			ConchDerver conchDerver=conchDerverService.getConchDerverByImei(device.getImei());
			if(conchDerver!=null){
				conchDerver.setLatitude(null);
				conchDerver.setLongitude(null);
				conchDerverService.save(conchDerver);
			}*/
		}
		response.success("成功");
        return response;
    }
	
	
	@RequestMapping("/checkMerchant")
	@ResponseBody
    public Response checkMerchant(Model model,String name)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(name)){
			Admin admin=adminService.getByLoginName(name);
			if(admin!=null){
				response.failure("账号已存在");
		        return response;
			}
		}
		response.success("成功");
        return response;
    }
	
	
	
	
	@RequestMapping("/merchant/untying")
	@ResponseBody
    public Response saveMerchant(Model model,String id)throws Exception {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		
		if(StringUtils.isNotEmpty(id)){
			Merchant merchant =merchantService.getById(id);
			if(merchant!=null) {
				if(StringUtils.isNotEmpty(merchant.getLibId())) {
					TbLibJoin libJoin=libJoinService.getById(merchant.getLibId());
					libJoin.setLibService(0);
					libJoin.setPlatformService(0);
					libJoin.setSignType(0);
					libJoin.setSignTime(null);
					libJoin.setEndSignTime(null);
					libJoinService.save(libJoin);
				}
				merchant.setLibId(null);
				merchantService.save(merchant);
				merchantService.syncRecordByMerchant(admin.getLoginName(), id,WebUtil.getRemoteAddr(request), "解绑机构");
			}
		}
		response.success("成功");
        return response;
    }
	
	
	
	@RequestMapping("/importDeviceData")
	@ResponseBody
    public ResponseEntity importDeviceData(HttpServletRequest request, HttpServletResponse response)throws Exception {
		ResponseEntity responseEntity = new ResponseEntity();
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileList = multipartRequest.getFileMap();
        if (fileList != null && fileList.size() > 0) {
            String filepath = "";
            //商户数据
            filepath = PropertiesUtil.getValue("file_save_path")+"/fx/device/";
            //文件信息入库
            List<FileInfo> fileInfos = fileInfoService.uploadFile(loginName(), fileList, filepath);
            if (fileList.size() == fileInfos.size()) {
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("pics", fileInfos);
                //-------------开始解析文件----------------
            	List<Device> devices=ExcelUtils.readDeviceFile(new File( PropertiesUtil.getValue("file_save_path")+fileInfos.get(0).getFilePath()));
            	String batchCode=DateHelper.format(new Date(), "yyyyMMddHHmmssSS");
            	for (Device device : devices) {
            		if(StringUtils.isNotEmpty(device.getPosCode())){
            			Merchant merchant=merchantService.getMerchantByPosCode(device.getPosCode());
            			device.setMerchantId(merchant.getId());
            			device.setOrgCode(merchant.getOrgCode());
            			device.setStatus(1);
            			device.setType(1);
            			device.setId(IdWorker.generateId());

            			DeviceAct deviceAct=new DeviceAct();
            			deviceAct.setFromMerchantId(null);
            			deviceAct.setToMerchantId(device.getMerchantId());
            			deviceAct.setOperatorAdminId(admin.getId());
            			deviceAct.setDeviceId(device.getId());
            			deviceAct.setImei(device.getImei());
            			deviceAct.setCreateTime(new Date());
						deviceAct.setRemarks("设备入库：导入入库");
						deviceAct.setBatchCode(batchCode);
						deviceAct.setType(3);
            			deviceActService.save(deviceAct);
            			
            			ConchDerver conchDerver=conchDerverService.getConchDerverByImei(device.getImei());
            			if(conchDerver!=null){
            				device.setDeviceSn(conchDerver.getSimcard());
//	            			conchDerver.setLatitude(null);
//	            			conchDerver.setLongitude(null);
	            			//conchDerverService.save(conchDerver);
            			}
            		}

				}

            	deviceService.save(devices);
                //-------------结束解析文件----------------
            	
                responseEntity.success(data, "上传文件成功 ");
            } else {
                responseEntity.failure(ResponseConstant.CODE_000, "上传文件失败");
            }
        } else {
            responseEntity.failure(ResponseConstant.CODE_000, "上传文件失败");
        }
        return responseEntity;
    }
	
	
	
	@RequestMapping(value = "/exportDevice", method = RequestMethod.POST)
    @ResponseBody
    public void exportDevice( 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");
    		
    		Admin admin =(Admin) request.getSession().getAttribute("admin");
    		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
    		Map<String, Object> params = new HashMap<String, Object>();
    		params.put("GTE_imei", request.getParameter("GTE_imei")==null?"":request.getParameter("GTE_imei"));
	        params.put("LTE_imei", request.getParameter("LTE_imei")==null?"":request.getParameter("LTE_imei"));
	        params.put("GTE_deviceCode", request.getParameter("GTE_deviceCode")==null?"":request.getParameter("GTE_deviceCode"));
	        params.put("LTE_deviceCode", request.getParameter("LTE_deviceCode")==null?"":request.getParameter("LTE_deviceCode"));
	        params.put("EQ_isSpan", request.getParameter("EQ_isSpan")==null?"":request.getParameter("EQ_isSpan"));
	        params.put("EQ_status", request.getParameter("EQ_status")==null?"":request.getParameter("EQ_status"));
	        if(StringUtils.isNotEmpty(request.getParameter("EQ_orgCode"))){
	        	params.put("EQ_orgCode", request.getParameter("EQ_orgCode"));
	        }else {
	        	 params.put("LIKE_orgCode", merchant.getOrgCode());
	        }
	        params.put("EQ_batchCode", request.getParameter("EQ_batchCode")==null?"":request.getParameter("EQ_batchCode"));
	        params.put("EQ_emsNumber", request.getParameter("EQ_emsNumber")==null?"":request.getParameter("EQ_emsNumber"));
	        params.put("LIKE_remarks", request.getParameter("LIKE_remarks")==null?"":request.getParameter("LIKE_remarks"));
	        
	        Page<Device> list = deviceService.findDeviceByPage(params, initPage(1, 10000, Direction.ASC, new String[]{"updateTime"}));
	        
	        
    		List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("imei号", "imei", 20));
    		myColumns3.add(new ExcelColumn("现商户", "posCode", 20));
    		myColumns3.add(new ExcelColumn("现商户名称", "unitName", 20));
    		myColumns3.add(new ExcelColumn("现状态", "status", 20));
    		
    		myColumns3.add(new ExcelColumn("设备名称", "deviceName", 20));
			myColumns3.add(new ExcelColumn("真实小塾编号", "deviceRealNumber", 20));
    		myColumns3.add(new ExcelColumn("小塾编号", "deviceNumber", 20));
    		myColumns3.add(new ExcelColumn("设备颜色", "deviceColor", 20));
    		myColumns3.add(new ExcelColumn("ICCID编号", "deviceModel", 20));
    		myColumns3.add(new ExcelColumn("SIM卡号", "deviceCode", 20));
    		myColumns3.add(new ExcelColumn("simcard", "deviceSn", 20));
    		
    	//	myColumns3.add(new ExcelColumn("是否跨区", "isSpan", 20));
    		myColumns3.add(new ExcelColumn("批次编号", "batchCode", 20));
    		myColumns3.add(new ExcelColumn("快递单号", "emsNumber", 20));
    		myColumns3.add(new ExcelColumn("快递地址", "emsAddress", 20));
    		myColumns3.add(new ExcelColumn("销售单价", "price", 20));
    		
    		myColumns3.add(new ExcelColumn("流通类型", "type", 20));
    		myColumns3.add(new ExcelColumn("更变时间", "updateTime", 20));
    		myColumns3.add(new ExcelColumn("创建时间", "createTime", 20));
    		
    		
    		CustomizeToExcel.downFile(myColumns3, objectToMap(list.getContent()), os);
    	}catch (IOException e) {  
    		e.printStackTrace();  
    	}catch (Exception e1){
    		e1.printStackTrace();
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
    				e.printStackTrace();
    			}  
    		}
    		
    	}
    }  
	
	
	   @RequestMapping(value = "/exportAllDevice", method = RequestMethod.POST)
	    @ResponseBody
	    public void exportAllDevice( 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("GTE_imei", request.getParameter("GTE_imei")==null?"":request.getParameter("GTE_imei"));
		        params.put("LTE_imei", request.getParameter("LTE_imei")==null?"":request.getParameter("LTE_imei"));
		        params.put("GTE_deviceCode", request.getParameter("GTE_deviceCode")==null?"":request.getParameter("GTE_deviceCode"));
		        params.put("LTE_deviceCode", request.getParameter("LTE_deviceCode")==null?"":request.getParameter("LTE_deviceCode"));
		        params.put("EQ_isSpan", request.getParameter("EQ_isSpan")==null?"":request.getParameter("EQ_isSpan"));
		        params.put("EQ_status", request.getParameter("EQ_status")==null?"":request.getParameter("EQ_status"));
		        params.put("EQ_batchCode", request.getParameter("EQ_batchCode")==null?"":request.getParameter("EQ_batchCode"));
		        params.put("EQ_emsNumber", request.getParameter("EQ_emsNumber")==null?"":request.getParameter("EQ_emsNumber"));
		        params.put("LIKE_remarks", request.getParameter("LIKE_remarks")==null?"":request.getParameter("LIKE_remarks"));
		      
		        Page<Device> list = deviceService.findDeviceByPage(params, initPage(1, 100000, Direction.DESC, new String[]{"createTime"}));

	    		List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
	    		myColumns3.add(new ExcelColumn("imei号", "imei", 20));
	    		myColumns3.add(new ExcelColumn("现商户", "posCode", 20));
	    		myColumns3.add(new ExcelColumn("现商户名称", "unitName", 20));
	    		myColumns3.add(new ExcelColumn("现状态", "status", 20));
	    		
	    		myColumns3.add(new ExcelColumn("设备名称", "deviceName", 20));
	    		myColumns3.add(new ExcelColumn("真实小塾编号", "deviceRealNumber", 20));
	    		myColumns3.add(new ExcelColumn("小塾编号", "deviceNumber", 20));
	    		myColumns3.add(new ExcelColumn("设备颜色", "deviceColor", 20));
	    		myColumns3.add(new ExcelColumn("ICCID编号", "deviceModel", 20));
	    		myColumns3.add(new ExcelColumn("SIM卡号", "deviceCode", 20));
	    		myColumns3.add(new ExcelColumn("simcard", "deviceSn", 20));
	    		
	    	//	myColumns3.add(new ExcelColumn("是否跨区", "isSpan", 20));
	    		myColumns3.add(new ExcelColumn("批次编号", "batchCode", 20));
	    		myColumns3.add(new ExcelColumn("快递单号", "emsNumber", 20));
	    		myColumns3.add(new ExcelColumn("快递地址", "emsAddress", 20));
	    		myColumns3.add(new ExcelColumn("销售单价", "price", 20));
	    		
	    		myColumns3.add(new ExcelColumn("流通类型", "type", 20));
	    		myColumns3.add(new ExcelColumn("更变时间", "updateTime", 20));
	    		myColumns3.add(new ExcelColumn("创建时间", "createTime", 20));
	    		
	    		CustomizeToExcel.downFile(myColumns3, objectToMap(list.getContent()), os);
	    	}catch (IOException e) {  
	    		e.printStackTrace();  
	    	}catch (Exception e1){
	    		e1.printStackTrace();
	    	}finally{
	    		if(os != null){
	    			try {
	    				os.flush();
	    				os.close(); 
	    			} catch (IOException e) {
	    				e.printStackTrace();
	    			}  
	    		}
	    		
	    	}
	    }  
	  
	  private static List<Map<String, Object>> objectToMap(List<?> list) throws Exception {
			if (list == null)
				return null;
			List<Map<String, Object>> maps=new ArrayList<Map<String,Object>>();
			Map<String, Object> map=null;
			for (Object obj : list) {
				map = new HashMap<String, Object>();
				BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
				PropertyDescriptor[] propertyDescriptors = beanInfo
						.getPropertyDescriptors();
				for (PropertyDescriptor property : propertyDescriptors) {
					String key = property.getName();
					if (key.compareToIgnoreCase("class") == 0) {
						continue;
					}
					Method getter = property.getReadMethod();
					Object value = getter != null ? getter.invoke(obj) : null;
					if("isSpan".equals(key)){
						map.put(key, "1".equals(value!=null ? value.toString(): "")?"无":"已跨");
					}else if("status".equals(key)){
						String str="";
						switch (value!=null ?value.toString():"") {
						case "1":
							str="待确认收货";
							break;
						case "2":
							str="已确认收货";
							break;
						case "3":
							str="退回待确认收货 ";
							break;
						case "4":
							str="退回已确认收货";
							break;
						default:
							str="删除";
							break;
						}
						map.put(key,  str);
					}else if("type".equals(key)){
						String str="";
						switch (value!=null ?value.toString():"") {
						case "1":
							str="出售";
							break;
						case "2":
							str="租赁";
							break;
						case "3":
							str="损坏 ";
							break;
						case "4":
							str="内部使用";
							break;
						default:
							str="";
							break;
						}
						map.put(key,  str);
					}else {
						map.put(key, value);
					} 
				}
				if(obj.getClass().equals(Device.class)){
					String unitName="";
					Device device=(Device)obj;
					if(device.getMerchant()!=null){
						unitName=device.getMerchant().getUnitName();
					}
					map.put("unitName", unitName);
				}
				maps.add(map);
			}
			return maps;
		}
	

    
    
    @RequestMapping(value = "/exportParts", method = RequestMethod.POST)
    @ResponseBody
    public void exportParts( 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>();
            HttpSession session = request.getSession();
    		Admin admin =(Admin) session.getAttribute("admin");
    		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
    		
            params.put("LIKE_name", request.getParameter("name")==null?"":request.getParameter("name"));
            params.put("LIKE_remarks", request.getParameter("remarks")==null?"":request.getParameter("remarks"));
            if(merchant!=null){
            	params.put("LIKE_orgCode", merchant.getOrgCode());
            }
            Page<DeviceParts> page = devicePartsService.findDevicePartsByPage(params, initPage(1, 10000, Direction.DESC, new String[]{"createTime"}));
            List<DeviceParts> orderList=new ArrayList<DeviceParts>();
            List<DeviceParts> devicePartsList= page.getContent();
            if(merchant!=null){
	    	    for (DeviceParts deviceParts : devicePartsList) {
	    			if(deviceParts.getOrgCode().equals(merchant.getOrgCode())){
	    				orderList.add(0, deviceParts);
	    			}else{
	    				orderList.add(deviceParts);
	    			}
	    		}
            }else{
            	orderList=devicePartsList;
            }
    		List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("现商户", "posCode", 20));
    		myColumns3.add(new ExcelColumn("现商户名称", "unitName", 20));
    		myColumns3.add(new ExcelColumn("配件名称", "name", 20));
    		myColumns3.add(new ExcelColumn("配件颜色", "partsColor", 20));
    		myColumns3.add(new ExcelColumn("已收货(现商户)", "sellNum", 20));
    		myColumns3.add(new ExcelColumn("待收货(现商户)", "sellWaitNum", 20));
    		myColumns3.add(new ExcelColumn("待收货(退回)", "returnWaitNum", 20));
    		myColumns3.add(new ExcelColumn("备注", "remarks", 20));
    		myColumns3.add(new ExcelColumn("更变时间", "updateTime", 20));
    		
    		CustomizeToExcel.downFile(myColumns3, objectToPartsMap(orderList), os);
    	}catch (IOException e) {  
    		e.printStackTrace();  
    	}catch (Exception e1){
    		e1.printStackTrace();
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
    				e.printStackTrace();
    			}  
    		}
    	}
    }  
    
	  private static List<Map<String, Object>> objectToPartsMap(List<?> list) throws Exception {
			if (list == null)
				return null;
			List<Map<String, Object>> maps=new ArrayList<Map<String,Object>>();
			Map<String, Object> map=null;
			for (Object obj : list) {
				map = new HashMap<String, Object>();
				BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
				PropertyDescriptor[] propertyDescriptors = beanInfo
						.getPropertyDescriptors();
				for (PropertyDescriptor property : propertyDescriptors) {
					String key = property.getName();
					if (key.compareToIgnoreCase("class") == 0) {
						continue;
					}
					Method getter = property.getReadMethod();
					Object value = getter != null ? getter.invoke(obj) : null;
					map.put(key, value);
					
				}
				if(obj.getClass().equals(DeviceParts.class)){
					String unitName="";
					DeviceParts device=(DeviceParts)obj;
					if(device.getMerchant()!=null){
						unitName=device.getMerchant().getUnitName();
					}
					map.put("unitName", unitName);
				}
				maps.add(map);
			}
			return maps;
		}
   
	  
	  

		@RequestMapping("/deviceActCountList")
	    public String deviceActCountList(Model model,
	            @RequestParam(required = false, defaultValue = "100") int pageSize,
	            @RequestParam(required = false, defaultValue = "1") int pageNo,
	            String merchantId)throws Exception {
			
	        Map<String, Object> params = new HashMap<String, Object>();
	    	HttpSession session = request.getSession();
			Admin admin =(Admin) session.getAttribute("admin");
			Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
			
			String type=request.getParameter("type")==null?"1":request.getParameter("type");
			if(merchant!=null && !merchant.getOrgCode().equals("SSJ-FX")){
				if("1".equals(type) || "2".equals(type)) {
					params.put("from_merchant_id", merchant.getId());
				}else {
					params.put("to_merchant_id", merchant.getId()); 
				}
			}else{
				params.put("from_merchant_id", "");
				List<Merchant> list=new ArrayList<Merchant>();
				List<Merchant> alllist=merchantService.findMerchantByPage();
				for (Merchant m : alllist) {
					if(!m.getOrgCode().equals("SSJ-FX")){
						list.add(m);
					}
				}
			    model.addAttribute("poslist", list);
			}
			
			if(StringUtils.isNotEmpty(merchantId)){
				if("1".equals(type) || "2".equals(type)) {
					params.put("from_merchant_id", merchantId);
				}else {
					params.put("to_merchant_id", merchantId); 
				}
			}
			
			params.put("merchantId", merchantId);
	        params.put("type", type);
	        params.put("batchCode", request.getParameter("batchCode")==null?"":request.getParameter("batchCode"));
	        
	        
	        params.put("startTime", request.getParameter("startTime"));
	        params.put("endTime", request.getParameter("endTime"));
	        
	        
	        SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	        Page<Map<String,Object>> page = deviceActService.findDeviceActCountListPage(params,initPage(pageNo, pageSize, 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/deviceActCountList";
	    }
		
		
		
		@RequestMapping("/deviceActDetailsList")
	    public String deviceActCountDetailsList(Model model,
	            @RequestParam(required = false, defaultValue = "100") int pageSize,
	            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
			
	        Map<String, Object> params = new HashMap<String, Object>();
	        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("from_merchant_id", merchant.getId());
//			}else{
				params.put("from_merchant_id", "");
//			}
	        params.put("type", request.getParameter("type")==null?"1":request.getParameter("type"));
	        params.put("batchCode", request.getParameter("batchCode")==null?"":request.getParameter("batchCode"));
	      
	        SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	        Page<Map<String,Object>> page = deviceActService.findDeviceActDetailsPage(params, initPage(pageNo, pageSize, 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);
	        List<Merchant> list=merchantService.findMerchantByPage();
			model.addAttribute("poslist", list);
	        return "sys/fx/deviceActDetailsList";
	    }
		
		
		
	    @RequestMapping(value = "/exportDeviceActCountList", method = RequestMethod.POST)
	    @ResponseBody
	    public void exportDeviceActCountList( HttpServletRequest request, HttpServletResponse response,
	    		String merchantId) {  
	    	ServletOutputStream os = null;
	    	try { 
	    		String libName="批次管理导出_"+DateHelper.formatDateByFormat(new Date(), "yyyy-MM-dd_HH:mm:ss");
	    		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>();
	 	    	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("from_merchant_id", merchant.getId());
	 			}else{
	 				params.put("from_merchant_id", "");
	 			}
	 			if(StringUtils.isNotEmpty(merchantId)){
	 				 params.put("from_merchant_id", merchantId);
	 			}
				int type=request.getParameter("type")==null?1:Integer.parseInt(request.getParameter("type").toString()) ;
				String typeName = type>2 ? (type==3 ? "设备入库":"退回入库"):(type==1 ? "分配下级":"退回上级");
	 			params.put("merchantId", merchantId);
	 	        params.put("type", type);
	 	        params.put("batchCode", request.getParameter("batchCode")==null?"":request.getParameter("batchCode"));

	 	        params.put("startTime", request.getParameter("startTime"));
	 	        params.put("endTime", request.getParameter("endTime"));
	 	        Page<Map<String,Object>> page = deviceActService.findDeviceActCountListPage(params,initPage(1, 10000, Direction.DESC, new String[]{"createTime"}));
	 	        List<Map<String,Object>> list= page.getContent();
	 	       for (Map<String, Object> map : list) {
				   map.put("type", typeName);
				}

	 	        List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
	    		myColumns3.add(new ExcelColumn("物流状态", "type", 20));
	    		myColumns3.add(new ExcelColumn("批次编号", "batch_code", 20));
	    		myColumns3.add(new ExcelColumn("批次总量", "count", 20));
				myColumns3.add(new ExcelColumn("始商户", "fpos_code", 20));
				myColumns3.add(new ExcelColumn("始商户名称", "funit_name", 20));
				myColumns3.add(new ExcelColumn("至商户", "pos_code", 20));
				myColumns3.add(new ExcelColumn("至商户名称", "unit_name", 20));


	    		myColumns3.add(new ExcelColumn("快递单号", "ems_number", 20));
	    		myColumns3.add(new ExcelColumn("快递联系人", "ems_username", 20));
	    		myColumns3.add(new ExcelColumn("快递联系号码", "ems_telephone", 20));
	    		myColumns3.add(new ExcelColumn("快递地址", "ems_address", 40));
	    		myColumns3.add(new ExcelColumn("备注", "remarks", 20));
	    		myColumns3.add(new ExcelColumn("操作时间", "create_time", 20));

	    		CustomizeToExcel.downFile(myColumns3, list, os);
	    	}catch (IOException e) {  
	    		e.printStackTrace();  
	    	}catch (Exception e1){
	    		e1.printStackTrace();
	    	}finally{
	    		if(os != null){
	    			try {
	    				os.flush();
	    				os.close(); 
	    			} catch (IOException e) {
	    				e.printStackTrace();
	    			}  
	    		}
	    	}
	    }  
	    
	      
	    @RequestMapping(value = "/exportDeviceActDetailsList", method = RequestMethod.POST)
	    @ResponseBody
	    public void exportDeviceActDetailsList( HttpServletRequest request, HttpServletResponse response,
	    		String merchantId) {  
	    	ServletOutputStream os = null;
	    	try { 
	    		String batchCode=request.getParameter("batchCode")==null?"":request.getParameter("batchCode");
				int type=request.getParameter("type")==null?1:Integer.parseInt(request.getParameter("type").toString()) ;
				String typeName = type>2 ? (type==3 ? "设备入库":"退回入库"):(type==1 ? "分配下级":"退回上级");
				String libName="批次_"+batchCode+"_"+typeName+"_明细表";
	    		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>();
	   	        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("from_merchant_id", merchant.getId());
	   			}else{
	   				params.put("from_merchant_id", "");
	   			}
	   	        params.put("type", request.getParameter("type")==null?"1":request.getParameter("type"));
	   	        params.put("batchCode", request.getParameter("batchCode")==null?"":request.getParameter("batchCode"));

	   	        Page<Map<String,Object>> page = deviceActService.findDeviceActDetailsPage(params, initPage(1, 100000, Direction.DESC, new String[]{"createTime"}));
	 	        List<Map<String,Object>> list= page.getContent();
	 	        for (Map<String, Object> map : list) {
					map.put("type", typeName);
					switch (map.get("status").toString()) {
						case "1":
							map.put("status", "待收货(现商户)");
							break;
						case "2":
							map.put("status", "已收货(现商户)");
							break;
						case "3":
							map.put("status", "待收货(退回)");
							break;
						case "4":
							map.put("status", "已收货(退回)");
							break;
						case "5":
							map.put("status", "无效");
							break;
						default:
							map.put("status", "");
							break;
					}
					switch (map.get("dtype").toString()) {
						case "1":
							map.put("dtype", "出售");
							break;
						case "2":
							map.put("dtype", "租赁");
							break;
						case "3":
							map.put("dtype", "损坏");
							break;
						case "4":
							map.put("dtype", "留存 ");
							break;
						default:
							map.put("dtype", "");
							break;
					}
				}
	 	        
	 	        List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
	    		myColumns3.add(new ExcelColumn("物流状态", "type", 20));
	    		myColumns3.add(new ExcelColumn("批次编号", "batch_code", 20));
	    		myColumns3.add(new ExcelColumn("imei号", "imei", 20));
	    		myColumns3.add(new ExcelColumn("设备名称", "device_name", 20));
	    		myColumns3.add(new ExcelColumn("设备颜色", "device_color", 20));
	    		myColumns3.add(new ExcelColumn("设备编号", "device_number", 20));
	    		myColumns3.add(new ExcelColumn("设备SN", "device_sn", 20));
	    		myColumns3.add(new ExcelColumn("设备状态", "status", 20));
	    		myColumns3.add(new ExcelColumn("流通类型", "dtype", 20));
	    		myColumns3.add(new ExcelColumn("至商户", "pos_code", 20));
	    		myColumns3.add(new ExcelColumn("至商户名称", "unit_name", 40));
	    		myColumns3.add(new ExcelColumn("快递单号", "ems_number", 20));
	    		myColumns3.add(new ExcelColumn("快递联系人", "ems_username", 20));
	    		myColumns3.add(new ExcelColumn("快递联系号码", "ems_telephone", 20));
	    		myColumns3.add(new ExcelColumn("快递地址", "ems_address", 20));
	    		myColumns3.add(new ExcelColumn("备注", "remarks", 20));
	    		myColumns3.add(new ExcelColumn("操作时间", "create_time", 20));
		    		
		    	CustomizeToExcel.downFile(myColumns3, list, os);
	    	}catch (IOException e) {  
	    		e.printStackTrace();  
	    	}catch (Exception e1){
	    		e1.printStackTrace();
	    	}finally{
	    		if(os != null){
	    			try {
	    				os.flush();
	    				os.close(); 
	    			} catch (IOException e) {
	    				e.printStackTrace();
	    			}  
	    		}
	    	}
	    } 
	    

		@RequestMapping("/deviceUnloadingList")
	    public String deviceUnloadingList(Model model,
	            @RequestParam(required = false, defaultValue = "100") int pageSize,
	            @RequestParam(required = false, defaultValue = "1") int pageNo,String merchantId)throws Exception {
		 	Map<String, Object> params = new HashMap<String, Object>();
		 	
		 	HttpSession session = request.getSession();
 			Admin admin =(Admin) session.getAttribute("admin");
 			Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
 			
 			List<Merchant> poslist=merchantService.findMerchantByPage();
		 	if(StringUtils.isEmpty(merchantId)){
	 		 	if(!"SSJ-FX".equals(merchant.getOrgCode())){
	 		 		merchantId=merchant.getId();
	 		 	}
		 	}
 			if(StringUtils.isNotEmpty(merchantId)){
				params.put("merchantId",merchantId);
			}

	        params.put("startMonth", request.getParameter("startMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("startMonth"));
	        params.put("endMonth", request.getParameter("endMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("endMonth"));
	        params.put("status", request.getParameter("status")==null?"1":request.getParameter("status"));
	        
	        SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize); 
	        sp.setParams(params);
	        Page<Map<String, Object>> page = deviceService.deviceUnloadingList(params, initPage(pageNo, pageSize, 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);
	        model.addAttribute("poslist", poslist);
	        model.addAttribute("merchant", merchant);
	        return "sys/fx/deviceUnloadingList";
	    }
		
 
	    @RequestMapping(value = "/exportDeviceUnloadingList", method = RequestMethod.POST)
	    @ResponseBody
	    public void exportDeviceUnloadingList( HttpServletRequest request, HttpServletResponse response) {  
	    	ServletOutputStream os = null;
	    	try { 
	    		
	    		HttpSession session = request.getSession();
	 			Admin admin =(Admin) session.getAttribute("admin");
	 			
	 			String merchantId="";
	 			Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
	 		 	if(!"SSJ-FX".equals(merchant.getOrgCode())){
	 		 		merchantId=merchant.getId();
	 		 	}
 	    		
	    		os = response.getOutputStream(); //获得输出流  
	            response.reset();   //清空输出流  
	    		Map<String, Object> params = new HashMap<String, Object>();
	            params.put("startMonth", request.getParameter("startMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("startMonth"));
	            params.put("endMonth", request.getParameter("endMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("endMonth"));
	            params.put("status", request.getParameter("status")==null?"1":request.getParameter("status"));
	            
	            Page<Map<String, Object>> page = deviceService.deviceUnloadingList(params, initPage(1, 10000, Direction.DESC, new String[]{"createTime"}));
	           
	            String fileName ="";
	            ClassPathResource classPathResource = null;
	            if("1".equals(params.get("status"))){
	            	fileName= new String("出入库登记".getBytes("gb2312"), "ISO8859-1") +".xlsx";
	            	classPathResource = new ClassPathResource("/excel/report/report16.xlsx");
	            }else if("2".equals(params.get("status"))){
	            	fileName= new String("全新库存登记".getBytes("gb2312"), "ISO8859-1") +".xlsx";
	            	classPathResource = new ClassPathResource("/excel/report/report17.xlsx");
	            }else if("3".equals(params.get("status"))){
	            	fileName= new String("二手库存登记".getBytes("gb2312"), "ISO8859-1") +".xlsx";
	            	classPathResource = new ClassPathResource("/excel/report/report18.xlsx");
	            }
	            
			    XSSFWorkbook workbook = new XSSFWorkbook(classPathResource.getInputStream());
        	    int rownum = 4; //添加的起始行  
        	    
                response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头  
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setCharacterEncoding("utf-8");
        	    
         	    XSSFSheet sheet = workbook.getSheetAt(0);   //读取第一个工作簿  
                XSSFRow row;  
                XSSFCell cell = null;  
                XSSFCellStyle style = this.getxStyle(workbook);  
                
         	    for (Map<String, Object> map : page.getContent()) {
         		   row = sheet.createRow(rownum);  
         		   int i = -1;
         		   myCreateCellx(++i, map.get("time").toString(), row, cell, style);    //列1 
         		   myCreateCellx(++i, map.get("unit_name").toString(), row, cell, style);    //列1   
         		   myCreateCellx(++i, map.get("price").toString(), row, cell, style);    //列1   
         		   myCreateCellx(++i, StringUtils.isNotEmpty(merchantId) ? "*" : map.get("counta").toString(), row, cell, style);    //列1   
          		   myCreateCellx(++i, StringUtils.isNotEmpty(merchantId) ? "*" :String.valueOf(Double.parseDouble(map.get("price").toString())*Double.parseDouble(map.get("counta").toString())), row, cell, style);    //列1   
          		   myCreateCellx(++i, StringUtils.isNotEmpty(merchantId) ? "*" : map.get("out_price").toString(), row, cell, style);    //列1   
          		   myCreateCellx(++i, map.get("countb").toString(), row, cell, style);    //列1   
          		   myCreateCellx(++i, StringUtils.isNotEmpty(merchantId) ? "*" :String.valueOf(Double.parseDouble(map.get("out_price").toString())*Double.parseDouble(map.get("countb").toString())), row, cell, style);    //列1   
          		   myCreateCellx(++i, String.valueOf(Double.parseDouble(map.get("counta").toString())- Double.parseDouble(map.get("countb").toString())), row, cell, style);    //列1   
          		   rownum++; 
			    }
         	    workbook.write(os);  
	    	}catch (IOException e) {  
	    		e.printStackTrace();  
	    	}catch (Exception e1){
	    		e1.printStackTrace();
	    	}finally{
	    		if(os != null){
	    			try {
	    				os.flush();
	    				os.close(); 
	    			} catch (IOException e) {
	    				e.printStackTrace();
	    			}  
	    		}
	    	}
	    } 
	      
	    private void myCreateCellx(int cellnum, String value, XSSFRow row,XSSFCell cell, XSSFCellStyle style) {  
	        cell = row.createCell((short) cellnum);  
	        cell.setCellValue(new XSSFRichTextString(value));  
	        cell.setCellStyle(style);  
	    } 
	    
	    
	    public XSSFCellStyle getxStyle(XSSFWorkbook workbook) {  
	        //设置字体;  
	        XSSFFont font = workbook.createFont();  
	        //设置字体大小;  
	        font.setFontHeightInPoints((short) 10);  
	        //设置字体名字;  
	        font.setFontName("Courier New");  
	        //font.setItalic(true);  
	        //font.setStrikeout(true);  
	        //设置样式;  
	        XSSFCellStyle style = workbook.createCellStyle();  
	        //设置底边框;  
	        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
	        //设置底边框颜色;  
	        style.setBottomBorderColor(HSSFColor.BLACK.index);  
	        //设置左边框;  
	        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
	        //设置左边框颜色;  
	        style.setLeftBorderColor(HSSFColor.BLACK.index);  
	        //设置右边框;  
	        style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
	        //设置右边框颜色;  
	        style.setRightBorderColor(HSSFColor.BLACK.index);  
	        //设置顶边框;  
	        style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
	        //设置顶边框颜色;  
	        style.setTopBorderColor(HSSFColor.BLACK.index);  
	        //在样式用应用设置的字体;  
	         style.setFont(font);  
	         //设置自动换行;  
	         style.setWrapText(false);  
	         //设置水平对齐的样式为居中对齐;  
	         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
	         //设置垂直对齐的样式为居中对齐;  
	         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
	         return style;  
	     }  

	    
	    
	    
	  //当前商户下的所有的设备，支持imei1范围，和批次号
		@RequestMapping("/consumeList")
	    public String consumeList(Model model,
	                              @RequestParam(required = false, defaultValue = "100") int pageSize,
	                              @RequestParam(required = false, defaultValue = "1") int pageNo)
	            throws Exception {
			HttpSession session = request.getSession();
			Admin admin =(Admin) session.getAttribute("admin");
			
			Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
			
	        Map<String, Object> params = new HashMap<String, Object>();
	        params.put("startTime", request.getParameter("startTime")==null? "" : request.getParameter("startTime"));
	        params.put("endTime", request.getParameter("endTime")==null? "" : request.getParameter("endTime"));
	        
	        params.put("type", request.getParameter("type")==null? "" : request.getParameter("type"));
	        params.put("remarks", request.getParameter("remarks")==null? "" : request.getParameter("remarks"));
	        String merchantId=request.getParameter("merchantId")==null? "" :request.getParameter("merchantId");
	    	if(!"SSJ-FX".equals(merchant.getOrgCode()) && StringUtils.isEmpty(merchantId)){
	    		merchantId=merchant.getId();
	    	}
	    	params.put("merchantId", merchantId);
	    	
	        SplitPage sp = new SplitPage(); 
	        sp.setAction(request.getRequestURI());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	        Page<Map<String, Object>> page = libJoinConsumeService.findByPage(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);
	        
	        List<Merchant> list=new ArrayList<Merchant>();
	        if("SSJ-FX".equals(merchant.getOrgCode())){
	        	list=merchantService.getMerchantByLikeOrgCode(merchant.getOrgCode());
	        }else{
	        	list=merchantService.getMerchantByParentPosCode(merchant.getPosCode());
	        	list.add(merchant);
	        }
			model.addAttribute("poslist", list);
			model.addAttribute("merchant", merchant);
	        return "sys/fx/consumeList";
	    }
		
		  //当前商户下的所有的设备，支持imei1范围，和批次号
		@RequestMapping("/consumeFxList")
	    public String consumeFxList(Model model,
	                              @RequestParam(required = false, defaultValue = "100") int pageSize,
	                              @RequestParam(required = false, defaultValue = "1") int pageNo)
	            throws Exception {
		    Map<String, Object> params = new HashMap<String, Object>();
	        params.put("startTime", request.getParameter("startTime")==null? "" : request.getParameter("startTime"));
	        params.put("endTime", request.getParameter("endTime")==null? "" : request.getParameter("endTime"));
	        
	        params.put("type", request.getParameter("type")==null? "" : request.getParameter("type"));
	        params.put("remarks", request.getParameter("remarks")==null? "" : request.getParameter("remarks"));
	        String merchantId=request.getParameter("merchantId")==null? "" :request.getParameter("merchantId");
	    	params.put("merchantId", merchantId);
	    	
	    	Merchant merchant= merchantService.getById(merchantId);
	    	
	        SplitPage sp = new SplitPage(); 
	        sp.setAction(request.getRequestURI());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	        Page<Map<String, Object>> page = libJoinConsumeService.findByPage(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);
	        model.addAttribute("merchant",merchant);
	        return "sys/fx/consumeFxList";
	    }

		
		
	 	@RequestMapping(value = "/exportConsumeList", method = RequestMethod.POST)
	    @ResponseBody
	    public void exportConsumeList(Model model,
                    @RequestParam(required = false, defaultValue = "100") int pageSize,
                    @RequestParam(required = false, defaultValue = "1") int pageNo) {  
		    	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");
		    		
		    		
		    		HttpSession session = request.getSession();
					Admin admin =(Admin) session.getAttribute("admin");
					Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
			        Map<String, Object> params = new HashMap<String, Object>();
			        params.put("startTime", request.getParameter("startTime")==null? "" : request.getParameter("startTime"));
			        params.put("endTime", request.getParameter("endTime")==null? "" : request.getParameter("endTime"));
			        params.put("type", request.getParameter("type")==null? "" : request.getParameter("type"));
			        
			        params.put("remarks", request.getParameter("remarks")==null? "" : request.getParameter("remarks"));
			        String merchantId=request.getParameter("merchantId")==null? "" :request.getParameter("merchantId");
			    	if(!"SSJ-FX".equals(merchant.getOrgCode()) && StringUtils.isEmpty(merchantId)){
			    		merchantId=merchant.getId();
			    	}
			    	params.put("merchantId", merchantId);
			    	
			        SplitPage sp = new SplitPage(); 
			        sp.setAction(request.getRequestURI());
			        sp.setPageNo(pageNo);
			        sp.setPageSize(pageSize);
			        sp.setParams(params);
			        Page<Map<String, Object>> page = libJoinConsumeService.findByPage(params, initPage(pageNo, pageSize));
			        List<Map<String,Object>> list= page.getContent();
			        
		 	        for (Map<String, Object> map : list) {
						switch (map.get("type").toString()) {
							case "1":
								map.put("type", "塾币充值【旧模式】");
								break;
							case "2":
								map.put("type", "塾币消费【旧模式】");
								break;
							case "3":
								map.put("type", "服务扣除【旧模式】");
								break;
							case "4":
								map.put("type", "上级分配币【旧模式】 ");
								break;
							case "5":
								map.put("type", "向下分配币【旧模式】");
								break;
							case "6":
								map.put("type", "服务包开通【新模式】");
								break;
							case "7":
								map.put("type", "服务包激活【新模式】");
								break;
							case "8":
								map.put("type", "服务包结算【新模式】");
								break;
							case "9":
								map.put("type", "加油包开通【新模式】");
								break;
							case "10":
								map.put("type", "加油包激活【新模式】");
								break;
							case "11":
								map.put("type", "加油包结算【新模式】");
								break;
							default:
								map.put("type", "");
								break;
						}
						
						switch (map.get("fm_type")!=null ? map.get("fm_type").toString() : "") {
							case "1":
								map.put("fm_type", "直接签约(旧模式)");
								break;
							case "2":
								map.put("fm_type", "内部消耗");
								break;
							case "3":
								map.put("fm_type", "外部签约");
								break;
							case "4":
								map.put("fm_type", "内部不结算(财务)");
								break;
							case "5":
								map.put("fm_type", "直接签约(新模式)");
								break;
							case "6":
								map.put("fm_type", "旧转新(新不结算)");
								break;
							case "7":
								map.put("fm_type", "旧转新(新旧不结算)");
								break;
							default:
								map.put("fm_type", "");
								break;
						}
						
						switch (map.get("tm_type")!=null ? map.get("tm_type").toString() : "") {
							case "1":
								map.put("tm_type", "直接签约(旧模式)");
								break;
							case "2":
								map.put("tm_type", "内部消耗");
								break;
							case "3":
								map.put("tm_type", "外部签约");
								break;
							case "4":
								map.put("tm_type", "内部不结算(财务)");
								break;
							case "5":
								map.put("tm_type", "直接签约(新模式)");
								break;
							case "6":
								map.put("tm_type", "旧转新(新不结算)");
								break;
							case "7":
								map.put("tm_type", "旧转新(新旧不结算)");
								break;
							default:
								map.put("tm_type", "");
								break;
						}
						
					}
		 	        List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
		    		myColumns3.add(new ExcelColumn("始商户", "fm_unit_name", 20));
		    		myColumns3.add(new ExcelColumn("始商户类型", "fm_type", 20));
		    		myColumns3.add(new ExcelColumn("至商户", "tm_unit_name", 20));
		    		myColumns3.add(new ExcelColumn("至商户类型", "tm_type", 20));
		    		myColumns3.add(new ExcelColumn("操作", "type", 20));
		    		myColumns3.add(new ExcelColumn("机构塾币", "lib_service", 20));
		    		myColumns3.add(new ExcelColumn("平台塾币", "platform_service", 20));
		    		myColumns3.add(new ExcelColumn("备注", "remarks", 20));
		    		myColumns3.add(new ExcelColumn("操作时间", "create_time", 20));
			    		
			    	CustomizeToExcel.downFile(myColumns3, list, os);
		    	}catch (IOException e) {  
		    		e.printStackTrace();  
		    	}catch (Exception e1){
		    		e1.printStackTrace();
		    	}finally{
		    		if(os != null){
		    			try {
		    				os.flush();
		    				os.close(); 
		    			} catch (IOException e) {
		    				e.printStackTrace();
		    			}  
		    		}
		    	}
		    } 
		
		
	    
		
		
		//批量分配设备商户下
		@RequestMapping("/likejoinList")
		@ResponseBody
	    public Response likejoinList(Model model,String name,String province,String city,String area,Integer pageNo,Integer pageSize)throws Exception {
			Response response = new  Response();
			Map<String,Object> data=new HashMap<String, Object>();
			if(pageNo==null) {
				pageNo=1;
			}
			Long countNum=libJoinService.countByLikeNameAndCity(name, province, city, area);
			List<TbLibJoin> jsonList =libJoinService.findByLikeNameAndCity(name, province, city, area,pageNo,pageSize);
			data.put("jsonList", jsonList);
			data.put("pageNo", pageNo);
			data.put("countNum", countNum);
			data.put("countPage", Math.ceil((double)countNum/(double)pageSize));
			response.success(data, "成功");
	        return response;
	    }
		
		//批量分配设备商户下
		@RequestMapping("/areaListPage")
		@ResponseBody
	    public Response areaListPage(Model model,String type,String upId,String name,Integer pageNo,Integer pageSize)throws Exception {
			Response response = new  Response();
			Map<String,Object> data=new HashMap<String, Object>();
			if(pageNo==null) {
				pageNo=1;
			}
			Long countNum=cnAreaService.countByTypeList(type, upId, name);
			List<CnArea> jsonList =cnAreaService.findByTypeList(type, upId, name, pageNo, pageSize);
			data.put("jsonList", jsonList);
			data.put("pageNo", pageNo);
			data.put("countNum", countNum);
			data.put("countPage", Math.ceil((double)countNum/(double)pageSize));
			response.success(data, "成功");
	        return response;
	    }


	@RequestMapping("/deviceInList")
	public String deviceInList(Model model,
									  @RequestParam(required = false, defaultValue = "100") int pageSize,
									  @RequestParam(required = false, defaultValue = "1") int pageNo,String merchantId)throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();

		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());

		List<Merchant> posList = merchantService.getMerchantByLikeOrgCode(merchant.getOrgCode());
		if(StringUtils.isEmpty(merchantId)){
			if(!"SSJ-FX".equals(merchant.getOrgCode())){
				merchantId=merchant.getId();
			}
		}
		if(StringUtils.isNotEmpty(merchantId)){
			params.put("merchantId",merchantId);
		}
		params.put("fromMerchantId",request.getParameter("fromMerchantId")==null?"":request.getParameter("fromMerchantId"));
		params.put("startMonth", request.getParameter("startMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("startMonth"));
		params.put("endMonth", request.getParameter("endMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("endMonth"));

		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String, Object>>  page = deviceService.deviceInAndOutList(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);
		model.addAttribute("poslist", posList);
		model.addAttribute("merchant", merchant);
		return "sys/fx/deviceInList";
	}

	@RequestMapping("/deviceOutList")
	public String deviceOutList(Model model,
							   @RequestParam(required = false, defaultValue = "100") int pageSize,
							   @RequestParam(required = false, defaultValue = "1") int pageNo,String merchantId)throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();

		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());

		List<Merchant> posList=merchantService.getMerchantByLikeOrgCode(merchant.getOrgCode());
		if(StringUtils.isEmpty(merchantId)){
			if(!"SSJ-FX".equals(merchant.getOrgCode())){
				merchantId=merchant.getId();
			}
		}
		if(StringUtils.isNotEmpty(merchantId)){
			params.put("merchantId",merchantId);
		}

		params.put("startMonth", request.getParameter("startMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("startMonth"));
		params.put("endMonth", request.getParameter("endMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("endMonth"));
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String, Object>> page = deviceService.deviceOutList(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);
		model.addAttribute("poslist", posList);
		model.addAttribute("merchant", merchant);
		return "sys/fx/deviceOutList";
	}

	@RequestMapping(value = "/exportDeviceInAndOut", method = RequestMethod.POST)
	@ResponseBody
	public void exportDeviceInAndOut(Model model,
								  @RequestParam(required = false, defaultValue = "100") int pageSize,
								  @RequestParam(required = false, defaultValue = "1") int pageNo,String merchantId,int type) {
		ServletOutputStream os = null;
		try {
			String libName=type==1?"商户入库":"商户出库";
			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>();
			HttpSession session = request.getSession();
			Admin admin =(Admin) session.getAttribute("admin");
			Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());

			//List<PosterTemplate> posList=merchantService.findMerchantByPage();
			if(StringUtils.isEmpty(merchantId)){
				if(!"SSJ-FX".equals(merchant.getOrgCode())){
					merchantId=merchant.getId();
				}
			}
			if(StringUtils.isNotEmpty(merchantId)){
				params.put("merchantId",merchantId);
			}
			params.put("fromMerchantId",request.getParameter("fromMerchantId")==null?"":request.getParameter("fromMerchantId"));
			params.put("startMonth", request.getParameter("startMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("startMonth"));
			params.put("endMonth", request.getParameter("endMonth")==null?DateHelper.format(new Date(), "yyyy-MM"):request.getParameter("endMonth"));

			SplitPage sp = new SplitPage();
			sp.setAction(request.getRequestURI());
			sp.setPageNo(pageNo);
			sp.setPageSize(pageSize);
			sp.setParams(params);
			if(type==1){
				Page<Map<String, Object>> page = deviceService.deviceInAndOutList(params, initPage(pageNo, pageSize));
				List<Map<String,Object>> list= page.getContent();
				List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
				myColumns3.add(new ExcelColumn("日期", "time", 20));
				myColumns3.add(new ExcelColumn("供应商", "unit_name2", 20));
				myColumns3.add(new ExcelColumn("收货商", "unit_name", 20));
				myColumns3.add(new ExcelColumn("收货内容", "content", 20));
				myColumns3.add(new ExcelColumn("入库数量", "counta", 20));
				myColumns3.add(new ExcelColumn("验收回退", "countb", 20));
				myColumns3.add(new ExcelColumn("当期结存", "lefts", 20));
				myColumns3.add(new ExcelColumn("累计库存", "total_left", 20));

				CustomizeToExcel.downFile(myColumns3, list, os);
			}else{

				Page<Map<String, Object>> page = deviceService.deviceOutList(params, initPage(pageNo, pageSize));
				List<Map<String,Object>> list= page.getContent();
				List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
				myColumns3.add(new ExcelColumn("日期", "time", 20));
				myColumns3.add(new ExcelColumn("商户", "unit_name", 20));
				myColumns3.add(new ExcelColumn("收货内容", "content", 20));
				myColumns3.add(new ExcelColumn("出库数量", "countab", 20));
				if("SSJ-FX".equals(merchant.getOrgCode())){
					myColumns3.add(new ExcelColumn("销售单价", "hardware_price", 20));
				}
				myColumns3.add(new ExcelColumn("出库退回", "countb", 20));
				myColumns3.add(new ExcelColumn("当月出库", "lefts", 20));
				myColumns3.add(new ExcelColumn("累计出库", "total_left", 20));

				CustomizeToExcel.downFile(myColumns3, list, os);
			}

		}catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e1){
			e1.printStackTrace();
		}finally{
			if(os != null){
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	//手动测试运行结算定时任务
	@RequestMapping("/run")
	@ResponseBody
    public Response run(Model model)throws Exception {
		Response response = new  Response();
		System.out.println("【套餐模式】处理套餐的数据定时任务，开始...");
		//merchantSignService.runMerchantSignByEndTime();
		System.out.println("【套餐模式】处理套餐的数据定时任务，结束。");
		response.success("成功");
        return response;
    }
	

	
	
	
	
	/**
	 * 
	 * 
	 * --------------------------------------------------------------------------------------------------
	 * CRM 商户相关功能重构
	 * 2021年1月5日9:38:19 导出功能
	 * 
	 * 
	 * 
	 */
	 @RequestMapping(value = "/exportMerchant", method = RequestMethod.POST)
	    @ResponseBody
	    public void exportMerchant( 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");
	    		
	    		HttpSession session = request.getSession();
	    		Admin admin =(Admin) session.getAttribute("admin");
	    		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());
	    		Map<String, Object> params = new HashMap<String, Object>();
	            params.put("LIKE_unitName", request.getParameter("LIKE_unitName")==null?"":request.getParameter("LIKE_unitName"));
	            params.put("LIKE_posCode", request.getParameter("LIKE_posCode")==null?"":request.getParameter("LIKE_posCode"));
	            if(request.getParameter("signType")!=null ) {
	            	if("0".equals(request.getParameter("signType").toString())){
	            		params.put("EQ_signType", 0);
	            	}else if("1".equals(request.getParameter("signType").toString())){
	            		params.put("GTE_signType", 1);
	            	}
	            }
	            String orgCode=request.getParameter("LIKE_orgCode")==null?"":request.getParameter("LIKE_orgCode");
	            if(StringUtils.isNotEmpty(orgCode)) {
	            	params.put("LIKE_orgCode", orgCode);
	            }else {
	            	params.put("LIKE_orgCode", merchant.getOrgCode());
	            }
	            
	            Page<Merchant> list = merchantService.findMerchantByPage(params, initPage(1, 10000, Direction.DESC, new String[]{"createTime"}));
	    		List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
	    		myColumns3.add(new ExcelColumn("商户账号", "posCode", 20));
	    		myColumns3.add(new ExcelColumn("商户编码", "orgCode", 20));
	    		myColumns3.add(new ExcelColumn("商户类别", "type", 20));
	    		myColumns3.add(new ExcelColumn("商户名称：合作名称/合作校区", "unitName", 40));
	    		
	    		myColumns3.add(new ExcelColumn("套餐：套餐类型", "mealType", 20));
	    		myColumns3.add(new ExcelColumn("套餐单价：平台管理费", "outPrice", 20));
	    		myColumns3.add(new ExcelColumn("关联机构", "joinName", 20));
	    		myColumns3.add(new ExcelColumn("签约端口数量", "portNum", 20));
	    		myColumns3.add(new ExcelColumn("机构塾币", "libService", 20));
	    		
	    		myColumns3.add(new ExcelColumn("甲方签约人", "signerPerson", 20));
	    		myColumns3.add(new ExcelColumn("合同编号", "contractNo", 20));
	    		myColumns3.add(new ExcelColumn("合同签约时间", "contractTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("地址", "address", 20));
	    		
	    		myColumns3.add(new ExcelColumn("法人姓名", "legalPerson", 20));
	    		myColumns3.add(new ExcelColumn("法人电话", "phone", 20));
	    		myColumns3.add(new ExcelColumn("商户代表", "deputyName", 20));
	    		myColumns3.add(new ExcelColumn("代表电话", "deputyPhone", 20));
	    		
	 
	    		myColumns3.add(new ExcelColumn("合同开始日期", "signTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("合同结束日期", "endSignTimeStr", 20));
	    		
	    		myColumns3.add(new ExcelColumn("激活开始日期", "startActiveTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("激活结束日期", "activeTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("计费开始日期", "computeTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("服务结束日期", "endActiveTimeStr", 20));
	    		
	    		myColumns3.add(new ExcelColumn("签约数（练习册用）", "signService", 20));
	    		
	    		myColumns3.add(new ExcelColumn("状态", "status", 20));
	    		myColumns3.add(new ExcelColumn("创建时间", "createTime", 20));
	    		
	    		CustomizeToExcel.downFile(myColumns3, objectMerchantToMap(list.getContent()), os);
	    	}catch (IOException e) {  
	    		e.printStackTrace();  
	    	}catch (Exception e1){
	    		e1.printStackTrace();
	    	}finally{
	    		if(os != null){
	    			try {
	    				os.flush();
	    				os.close(); 
	    			} catch (IOException e) {
	    				e.printStackTrace();
	    			}  
	    		}
	    	}
	    }  
	 
	 
	    private List<Map<String, Object>> objectMerchantToMap(List<Merchant> list) throws Exception {
			if (list == null)
				return null;
			List<Map<String, Object>> maps=new ArrayList<Map<String,Object>>();
			Map<String, Object> map=null;
			for (Merchant obj : list) {
				map = new HashMap<String, Object>();
				BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
				PropertyDescriptor[] propertyDescriptors = beanInfo
						.getPropertyDescriptors();
				for (PropertyDescriptor property : propertyDescriptors) {
					String key = property.getName();
					if (key.compareToIgnoreCase("class") == 0) {
						continue;
					}
					Method getter = property.getReadMethod();
					Object value = getter != null ? getter.invoke(obj) : null;
					if("type".equals(key)){
						String str="";
						switch (value!=null ?value.toString():"") {
						case "1":
							str="直接签约(旧模式)";
							break;
						case "2":
							str="内部消耗";
							break;
						case "3":
							str="外部签约";
							break;
						case "4":
							str="内部不结算(财务)";
							break;
						case "5":
							str="直接签约(新模式)";
							break;
						case "6":
							str="旧转新(新不结算)";
							break;
						case "7":
							str="旧转新(新旧不结算)";
							break;
						default:
							str="--";
							break;
						}
						map.put(key,  str);
					}else if("level".equals(key)){
						String str="";
						switch (value!=null ?value.toString():"") {
						case "1":
							str="市代";
							break;
						case "2":
							str="区代";
							break;
						case "3":
							str="学校独家";
							break;
						case "4":
							str="普通";
							break;
						default:
							str="--";
							break;
						}
						map.put(key,  str);
					}else if("status".equals(key)){
						String str="";
						switch (value!=null ?value.toString():"") {
						case "1":
							str="正常";
							break;
						case "2":
							str="正常";
							break;
						case "3":
							str="正常";
							break;
						case "4":
							str="冻结";
							break;
						default:
							str="--";
							break;
						}
						map.put(key,  str);
					}else if("signType".equals(key)){
						String startActiveTimeStr="";
						String activeTimeStr="";
						String computeTimeStr="";
						String endActiveTimeStr="";
						switch (value!=null ?value.toString():"") {
						case "0":
							startActiveTimeStr="";
							activeTimeStr="";
							computeTimeStr="";
							endActiveTimeStr="";
							break;
						case "1":
							startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
							activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
							if(obj.getComputeTime()!=null) {
								computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
							}
							if(obj.getEndActiveTime()!=null) {
								endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
							}
							break;
						case "2":
							startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
							activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
							if(obj.getComputeTime()!=null) {
								computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
							}
							if(obj.getEndActiveTime()!=null) {
								endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
							}
							break;
						case "3":
							startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
							activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
							if(obj.getComputeTime()!=null) {
								computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
							}
							if(obj.getEndActiveTime()!=null) {
								endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
							}
							break;
						case "4":
							startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
							activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
							if(obj.getComputeTime()!=null) {
								computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
							}
							if(obj.getEndActiveTime()!=null) {
								endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
							}
							break;
						case "5":
							startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
							activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
							if(obj.getComputeTime()!=null) {
								computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
							}
							if(obj.getEndActiveTime()!=null) {
								endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
							}
							break;
						default:
							startActiveTimeStr="";
							activeTimeStr="" ;
							computeTimeStr="";
							endActiveTimeStr="";
							break;
						}
						map.put("startActiveTimeStr", startActiveTimeStr);
						map.put("activeTimeStr", activeTimeStr);
						map.put("computeTimeStr", computeTimeStr);
						map.put("endActiveTimeStr", endActiveTimeStr);
					}else if("mealType".equals(key)){
						String str="";
						switch (value!=null ?value.toString():"") {
						case "0":
							str="塾币模式";
							break;
						case "1":
							str="优选套餐";
							break;
						case "2":
							str="VIP套餐";
							break;
						case "3":
							str="尊享套餐";
							break;
						case "4":
							str="校园服务";
							break;
						default:
							str="";
							break;
						}
						map.put(key,  str);
					}else if("signTime".equals(key)){
						map.put("signTimeStr",DateHelper.format(obj.getSignTime(), "yyyy-MM-dd"));
					}else if("endSignTime".equals(key)){
						map.put("endSignTimeStr",DateHelper.format(obj.getEndSignTime(), "yyyy-MM-dd"));
					}else if("contractTime".equals(key)){
						map.put("contractTimeStr",DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd"));
					}else if("nextSummaryTime".equals(key)){
						map.put(key,DateHelper.format(obj.getNextSummaryTime(), "yyyy-MM-dd"));
					}else {
						map.put(key, value);
					} 
				}
				List<PositionSchoolV1Dto> positionSchoolV1Dtos=new ArrayList<PositionSchoolV1Dto>();
				String schoolText="";
				if(StringUtils.isNotEmpty(obj.getLibId())) { 
					 positionSchoolV1Dtos= merchantAreaService.findSchoolList(obj.getLibId());
					 if(positionSchoolV1Dtos!=null) {
						 for (PositionSchoolV1Dto positionSchoolV1Dto : positionSchoolV1Dtos) {
							 schoolText=schoolText+positionSchoolV1Dto.getSchoolName()+";";
						 }
						 if(schoolText.endsWith(";")) {
							 schoolText=schoolText.substring(0, schoolText.length()-1);
						 }
					 }
				}
				map.put("joinName", obj.getLibJoin()!=null ? obj.getLibJoin().getLeagueName() : "");
				map.put("schoolName", schoolText);
				maps.add(map);
			}
			return maps;
		}
	 
 	@RequestMapping(value = "/exportMerchantBackup", method = RequestMethod.POST)
    @ResponseBody
    public void exportMerchantBackup( 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("LIKE_unitName", request.getParameter("LIKE_unitName")==null?"":request.getParameter("LIKE_unitName"));
	            params.put("LIKE_posCode", request.getParameter("LIKE_posCode")==null?"":request.getParameter("LIKE_posCode"));
	            params.put("EQ_backupMonth", request.getParameter("EQ_backupMonth")==null||StringUtils.isEmpty(request.getParameter("EQ_backupMonth").toString())? DateHelper.format(new Date(),"yyyy-MM") :request.getParameter("EQ_backupMonth"));
	            
	            if(request.getParameter("signType")!=null ) {
	            	if("0".equals(request.getParameter("signType").toString())){
	            		params.put("EQ_signType", 0);
	            	}else if("1".equals(request.getParameter("signType").toString())){
	            		params.put("GTE_signType", 1);
	            	}
	            }
	            
	            Page<MerchantBackup> list = merchantBackupService.findMerchantBackupByPage(params, initPage(1, 10000, Direction.DESC, new String[]{"createTime"}));
	    		List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
	    		myColumns3.add(new ExcelColumn("备份月份", "backupMonth", 20));
	    		myColumns3.add(new ExcelColumn("商户账号", "posCode", 20));
	    		myColumns3.add(new ExcelColumn("商户编码", "orgCode", 20));
	    		myColumns3.add(new ExcelColumn("商户类别", "type", 20));
	    		myColumns3.add(new ExcelColumn("商户名称：合作名称/合作校区", "unitName", 40));
	    		
	    		myColumns3.add(new ExcelColumn("套餐：套餐类型", "mealType", 20));
	    		myColumns3.add(new ExcelColumn("套餐单价：平台管理费", "outPrice", 20));
	    		myColumns3.add(new ExcelColumn("关联机构", "joinName", 20));
	    		myColumns3.add(new ExcelColumn("签约端口数量", "portNum", 20));
	    		myColumns3.add(new ExcelColumn("机构塾币", "libService", 20));
	    		
	    		myColumns3.add(new ExcelColumn("甲方签约人", "signerPerson", 20));
	    		myColumns3.add(new ExcelColumn("合同编号", "contractNo", 20));
	    		myColumns3.add(new ExcelColumn("合同签约时间", "contractTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("地址", "address", 20));
	    		
	    		myColumns3.add(new ExcelColumn("法人姓名", "legalPerson", 20));
	    		myColumns3.add(new ExcelColumn("法人电话", "phone", 20));
	    		myColumns3.add(new ExcelColumn("商户代表", "deputyName", 20));
	    		myColumns3.add(new ExcelColumn("代表电话", "deputyPhone", 20));
	    		
	 
	    		myColumns3.add(new ExcelColumn("合同开始日期", "signTime", 20));
	    		myColumns3.add(new ExcelColumn("合同结束日期", "endSignTime", 20));
	    		
	    		myColumns3.add(new ExcelColumn("激活开始日期", "startActiveTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("激活结束日期", "activeTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("计费开始日期", "computeTimeStr", 20));
	    		myColumns3.add(new ExcelColumn("服务结束日期", "endActiveTimeStr", 20));
	    		
	    		myColumns3.add(new ExcelColumn("签约数（练习册用）", "signService", 20));
	    		
	    		myColumns3.add(new ExcelColumn("状态", "status", 20));
	    		myColumns3.add(new ExcelColumn("创建时间", "createTime", 20));
	    		
	    		CustomizeToExcel.downFile(myColumns3, objectMerchantBackupToMap(list.getContent()), os);
	    	}catch (IOException e) {  
	    		e.printStackTrace();  
	    	}catch (Exception e1){
	    		e1.printStackTrace();
	    	}finally{
	    		if(os != null){
	    			try {
	    				os.flush();
	    				os.close(); 
	    			} catch (IOException e) {
	    				e.printStackTrace();
	    			}  
	    		}
	    	}
	    }  
	
    private List<Map<String, Object>> objectMerchantBackupToMap(List<MerchantBackup> list) throws Exception {
		if (list == null)
			return null;
		List<Map<String, Object>> maps=new ArrayList<Map<String,Object>>();
		Map<String, Object> map=null;
		for (MerchantBackup obj : list) {
			map = new HashMap<String, Object>();
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo
					.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				if (key.compareToIgnoreCase("class") == 0) {
					continue;
				}
				Method getter = property.getReadMethod();
				Object value = getter != null ? getter.invoke(obj) : null;
				if("type".equals(key)){
					String str="";
					switch (value!=null ?value.toString():"") {
					case "1":
						str="直接签约(旧模式)";
						break;
					case "2":
						str="内部消耗";
						break;
					case "3":
						str="外部签约";
						break;
					case "4":
						str="内部不结算(财务)";
						break;
					case "5":
						str="直接签约(新模式)";
						break;
					case "6":
						str="旧转新(新不结算)";
						break;
					case "7":
						str="旧转新(新旧不结算)";
						break;
					default:
						str="--";
						break;
					}
					map.put(key,  str);
				}else if("level".equals(key)){
					String str="";
					switch (value!=null ?value.toString():"") {
					case "1":
						str="市代";
						break;
					case "2":
						str="区代";
						break;
					case "3":
						str="学校独家";
						break;
					case "4":
						str="普通";
						break;
					default:
						str="--";
						break;
					}
					map.put(key,  str);
				}else if("status".equals(key)){
					String str="";
					switch (value!=null ?value.toString():"") {
					case "1":
						str="正常";
						break;
					case "2":
						str="正常";
						break;
					case "3":
						str="正常";
						break;
					case "4":
						str="冻结";
						break;
					default:
						str="--";
						break;
					}
					map.put(key,  str);
				}else if("signType".equals(key)){
					String startActiveTimeStr="";
					String activeTimeStr="";
					String computeTimeStr="";
					String endActiveTimeStr="";
					switch (value!=null ?value.toString():"") {
					case "0":
						startActiveTimeStr="";
						activeTimeStr="";
						computeTimeStr="";
						endActiveTimeStr="";
						break;
					case "1":
						startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
						activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
						if(obj.getComputeTime()!=null) {
							computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
						}
						if(obj.getEndActiveTime()!=null) {
							endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
						}
						break;
					case "2":
						startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
						activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
						if(obj.getComputeTime()!=null) {
							computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
						}
						if(obj.getEndActiveTime()!=null) {
							endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
						}
						break;
					case "3":
						startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
						activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
						if(obj.getComputeTime()!=null) {
							computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
						}
						if(obj.getEndActiveTime()!=null) {
							endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
						}
						break;
					case "4":
						startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
						activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
						if(obj.getComputeTime()!=null) {
							computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
						}
						if(obj.getEndActiveTime()!=null) {
							endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
						}
						break;
					case "5":
						startActiveTimeStr=DateHelper.format(obj.getStartActiveTime(), "yyyy-MM-dd") ;
						activeTimeStr=DateHelper.format(obj.getActiveTime(), "yyyy-MM-dd") ;
						if(obj.getComputeTime()!=null) {
							computeTimeStr=DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd") ;
						}
						if(obj.getEndActiveTime()!=null) {
							endActiveTimeStr=DateHelper.format(obj.getEndActiveTime(), "yyyy-MM-dd") ;
						}
						break;
					default:
						startActiveTimeStr="";
						activeTimeStr="" ;
						computeTimeStr="";
						endActiveTimeStr="";
						break;
					}
					map.put("startActiveTimeStr", startActiveTimeStr);
					map.put("activeTimeStr", activeTimeStr);
					map.put("computeTimeStr", computeTimeStr);
					map.put("endActiveTimeStr", endActiveTimeStr);
				}else if("mealType".equals(key)){
					String str="";
					switch (value!=null ?value.toString():"") {
					case "0":
						str="塾币模式";
						break;
					case "1":
						str="优选套餐";
						break;
					case "2":
						str="VIP套餐";
						break;
					case "3":
						str="尊享套餐";
						break;
					case "4":
						str="校园服务";
						break;
					default:
						str="";
						break;
					}
					map.put(key,  str);
				}else if("signTime".equals(key)){
					map.put(key,DateHelper.format(obj.getSignTime(), "yyyy-MM-dd"));
				}else if("endSignTime".equals(key)){
					map.put(key,DateHelper.format(obj.getEndSignTime(), "yyyy-MM-dd"));
				}else if("contractTime".equals(key)){
					map.put("contractTimeStr",DateHelper.format(obj.getComputeTime(), "yyyy-MM-dd"));
				}else if("nextSummaryTime".equals(key)){
					map.put(key,DateHelper.format(obj.getNextSummaryTime(), "yyyy-MM-dd"));
				}else {
					map.put(key, value);
				} 
			}
			List<PositionSchoolV1Dto> positionSchoolV1Dtos=new ArrayList<PositionSchoolV1Dto>();
			String schoolText="";
			if(StringUtils.isNotEmpty(obj.getLibId())) { 
				 positionSchoolV1Dtos= merchantAreaService.findSchoolList(obj.getLibId());
				 if(positionSchoolV1Dtos!=null) {
					 for (PositionSchoolV1Dto positionSchoolV1Dto : positionSchoolV1Dtos) {
						 schoolText=schoolText+positionSchoolV1Dto.getSchoolName()+";";
					 }
					 if(schoolText.endsWith(";")) {
						 schoolText=schoolText.substring(0, schoolText.length()-1);
					 }
				 }
			}
			map.put("joinName", obj.getLibJoin()!=null ? obj.getLibJoin().getLeagueName() : "");
			map.put("schoolName", schoolText);
			maps.add(map);
		}
		return maps;
	}

	
    
	//服务包订单表导出
 	@RequestMapping(value = "/exportMerchantMealOrderList", method = RequestMethod.POST)
    @ResponseBody
    public void exportMerchantMealOrderList( 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("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
	        params.put("signType", request.getParameter("signType")==null?"":request.getParameter("signType"));
	        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
	        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
	        
	        Page<Map<String, Object>> page = merchantMealOrderService.findMerchantMealOrderByPage(params, initPage(1, 10000, Direction.DESC, new String[]{"createTime"}));
	        List<Map<String, Object>> list=page.getContent();
	        for (Map<String, Object> map : list) {
				switch (map.get("sign_type").toString()) {
				case "1":
					map.put("sign_type","服务包1");
					break;
				case "2":
					map.put("sign_type","服务包2");
					break;
				case "3":
					map.put("sign_type","服务包3");
					break;
				case "4":
					map.put("sign_type","服务包4");
					break;
				case "5":
					map.put("sign_type","服务包5");
					break;
				default:
					break;
				}
				switch (map.get("type").toString()) {
				case "1":
					map.put("buy_month",map.get("buy_month"));
					map.put("give_month",map.get("give_month"));
					map.put("sign_time","--");
					map.put("end_sign_time","--");
					break;
				case "2":
					map.put("buy_month","--");
					map.put("give_month","--");
					map.put("sign_time",map.get("sign_time"));
					map.put("end_sign_time",map.get("end_sign_time"));
					break;
				default:
					break;
				}
			}
	        
	        List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("订单编号", "id", 20));
    		myColumns3.add(new ExcelColumn("商户名称", "unit_name", 20));
    		myColumns3.add(new ExcelColumn("服务包类型", "sign_type", 20));
    		myColumns3.add(new ExcelColumn("服务包人数", "lib_service", 20));
    		myColumns3.add(new ExcelColumn("购买月份", "buy_month", 40));
    		myColumns3.add(new ExcelColumn("赠送月份", "give_month", 20));
    		myColumns3.add(new ExcelColumn("试用开始时间", "sign_time", 20));
    		myColumns3.add(new ExcelColumn("试用结束时间", "end_sign_time", 20));
    		myColumns3.add(new ExcelColumn("月单价（成本）", "unit_price", 20));
    		myColumns3.add(new ExcelColumn("总价（收入）", "price", 20));
    		myColumns3.add(new ExcelColumn("购买时间", "create_time", 20));

    		CustomizeToExcel.downFile(myColumns3, list, os);
    	}catch (IOException e) {  
    		e.printStackTrace();  
    	}catch (Exception e1){
    		e1.printStackTrace();
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
    				e.printStackTrace();
    			}  
    		}
    	}

    }

 	//加油包订单导出
 	@RequestMapping(value = "/exportMerchantSignOrderList", method = RequestMethod.POST)
    @ResponseBody
    public void exportMerchantSignOrderList( 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("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
	        params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
	        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
	        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
	        
	        Page<Map<String, Object>> page = merchantSignOrderService.findMerchantSignOrderByPage(params, initPage(1, 10000));
	        List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
	        for (Map<String, Object> map : page.getContent()) {
	        	switch (map.get("type").toString()) {
				case "1":
					map.put("type","加油包-月包");
					break;
				case "2":
					map.put("type","加油包-量包");
					break;
				default:
					break;
				}
	     	}
    		List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("订单号", "id", 20));
    		myColumns3.add(new ExcelColumn("商户名称", "unit_name", 20));
    		myColumns3.add(new ExcelColumn("加油包类型", "type", 20));
    		myColumns3.add(new ExcelColumn("购买数量", "num", 20));
    		myColumns3.add(new ExcelColumn("加油包单价", "unit_price", 20));
    		myColumns3.add(new ExcelColumn("购买总价", "price", 20));
    		myColumns3.add(new ExcelColumn("服务总人数", "lib_service", 20));
    		myColumns3.add(new ExcelColumn("激活时间", "sign_time", 20));
    		myColumns3.add(new ExcelColumn("购买时间", "create_time", 20));
    		
			CustomizeToExcel.downFile(myColumns3, list, os);
    	}catch (IOException e) {  
    		e.printStackTrace();  
    	}catch (Exception e1){
    		e1.printStackTrace();
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
    				e.printStackTrace();
    			}  
    		}
    	}
    }  
 	
 	
 	
 	
 	//平台管理订单导出
 	@RequestMapping(value = "/exportMerchantPlatOrderList", method = RequestMethod.POST)
    @ResponseBody
    public void exportMerchantPlatOrderList( 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("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
	        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
	        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
	        
	        Page<Map<String, Object>> page = merchantPlatOrderService.findMerchantPlatOrderByPage(params, initPage(1, 10000));
	        List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
	        for (Map<String, Object> map : page.getContent()) {
	        	switch (map.get("meal_type").toString()) {
				case "1":
					map.put("meal_type","优选套餐");
					break;
				case "2":
					map.put("meal_type","VIP套餐");
					break;
				case "3":
					map.put("meal_type","尊享套餐");
					break;
				case "4":
					map.put("meal_type","校园服务");
					break;
				default:
					map.put("meal_type","--");
					break;
				}
	     	}
    		List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("订单号", "id", 20));
    		myColumns3.add(new ExcelColumn("商户名称", "unit_name", 20));
    		myColumns3.add(new ExcelColumn("套餐类型", "meal_type", 20));
    		myColumns3.add(new ExcelColumn("费用金额", "price", 20));
    		myColumns3.add(new ExcelColumn("购买时间", "create_time", 20));
    		
			CustomizeToExcel.downFile(myColumns3, list, os);
    	}catch (IOException e) {  
    		e.printStackTrace();  
    	}catch (Exception e1){
    		e1.printStackTrace();
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
    				e.printStackTrace();
    			}  
    		}
    	}
    }  
 	
 	
 	
 	//端口资金流水表
 	@RequestMapping(value = "/exportMerchantCapList", method = RequestMethod.POST)
    @ResponseBody
    public void exportMerchantCapList( 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("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
	        params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
	        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
	        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
	        

	        Page<Map<String, Object>> page = merchantMealService.findMerchantCapByPage(params, initPage(1, 10000, Direction.DESC, new String[]{"createTime"}));
	        
	        List<Map<String, Object>> mapList=page.getContent();
	        for (Map<String, Object> map : mapList) {
	        	if(Integer.parseInt(map.get("cap_type").toString())==1) {
	        		map.put("pr_1",new BigDecimal(new BigDecimal(map.get("price").toString()).doubleValue()/(Integer.parseInt(map.get("buy_month").toString())+Integer.parseInt(map.get("give_month").toString()))/Integer.parseInt(map.get("lib_service").toString())).setScale(2, RoundingMode.UP).doubleValue());
	        		map.put("pr_2",map.get("price"));
	        		map.put("pr_3","");
	        	}else if(Integer.parseInt(map.get("cap_type").toString())==2) {
	        		map.put("pr_1",new BigDecimal(new BigDecimal(map.get("price").toString()).doubleValue()/(Integer.parseInt(map.get("buy_month").toString())+Integer.parseInt(map.get("give_month").toString()))/Integer.parseInt(map.get("lib_service").toString())).setScale(2, RoundingMode.UP).doubleValue());
	        		map.put("pr_2","");
	        		map.put("pr_3",new BigDecimal(new BigDecimal(map.get("price").toString()).doubleValue()/(Integer.parseInt(map.get("buy_month").toString())+Integer.parseInt(map.get("give_month").toString()))).setScale(2, RoundingMode.UP).doubleValue());
	        	}else if(Integer.parseInt(map.get("cap_type").toString())==3) {
	        		map.put("pr_1","");
	        		map.put("pr_2",map.get("price"));
	        		map.put("pr_3","");
	        	}else if(Integer.parseInt(map.get("cap_type").toString())==4) {
	        		map.put("pr_1","");
	        		map.put("pr_2","");
	        		map.put("pr_3",map.get("price"));
	        	}else if(Integer.parseInt(map.get("cap_type").toString())==5) {
	        		map.put("pr_1", new BigDecimal(new BigDecimal(map.get("unit_price").toString()).doubleValue()*(Integer.parseInt(map.get("buy_month").toString()))/Integer.parseInt(map.get("lib_service").toString())).setScale(2, RoundingMode.UP).doubleValue());
	        		map.put("pr_2", new BigDecimal(new BigDecimal(map.get("unit_price").toString()).doubleValue()*(Integer.parseInt(map.get("buy_month").toString()))).setScale(2, RoundingMode.UP).doubleValue());
	        		map.put("pr_3","");
	        	}else if(Integer.parseInt(map.get("cap_type").toString())==6) {
	        		map.put("pr_1", new BigDecimal(new BigDecimal(map.get("unit_price").toString()).doubleValue()/Integer.parseInt(map.get("lib_service").toString())).setScale(2, RoundingMode.UP).doubleValue());
	        		map.put("pr_2","");
	        		map.put("pr_3",map.get("unit_price"));
	        	}
	        	String remarks="";
	        	String type="";
	        	switch (map.get("cap_type").toString()) {
				case "1":
					remarks="充值服务包";
					type="充值";
					break;
				case "2":
					remarks="消耗服务包";
					type="消耗";
					break;
				case "3":
					remarks="充值平台管理费";
					type="充值";
					break;
				case "4":
					remarks="消耗平台管理费";
					type="消耗";
					break;
				case "5":
					remarks="充值加油包";
					type="充值";
					break;
				case "6":
					remarks="消耗加油包";
					type="消耗";
					break;
				default:
					break;
				}
	        	map.put("remarks",remarks);
	        	map.put("type",type);
			}
	        List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
    		myColumns3.add(new ExcelColumn("商户账号", "pos_code", 20));
    		myColumns3.add(new ExcelColumn("单位名称", "unit_name", 20));
    		myColumns3.add(new ExcelColumn("端口数量", "lib_service", 20));
    		myColumns3.add(new ExcelColumn("端口单价", "pr_1", 20));
    		myColumns3.add(new ExcelColumn("充值金额", "pr_2", 20));
    		myColumns3.add(new ExcelColumn("消耗金额", "pr_3", 20));
    		myColumns3.add(new ExcelColumn("流水时间", "time", 20));
    		myColumns3.add(new ExcelColumn("流水备注", "remarks", 20));
    		myColumns3.add(new ExcelColumn("流水类型", "type", 20));
    		
			CustomizeToExcel.downFile(myColumns3, mapList, os);
    	}catch (IOException e) {  
    		e.printStackTrace();  
    	}catch (Exception e1){
    		e1.printStackTrace();
    	}finally{
    		if(os != null){
    			try {
    				os.flush();
    				os.close(); 
    			} catch (IOException e) {
    				e.printStackTrace();
    			}  
    		}
    	}
    }  
 	
 	
 	
	/**
	 * 
	 * 
	 * --------------------------------------------------------------------------------------------------
	 * CRM 商户相关功能重构
	 * 2020年12月28日14:59:35
	 * 
	 */
 	
 	
 	//塾币商户建立
	@RequestMapping("/saveMerchantOld")
	@ResponseBody
    public Response saveMerchantOld(Model model,Merchant merchant,String startTime,String endTime,String activeTimeStr,String endActiveTimeStr,String contractTimeStr
    		,String password,String province,String city,String area,String schoollist,String location)throws Exception {
		Response response = new  Response();
		HttpSession session = request.getSession();
		Admin curadmin =(Admin) session.getAttribute("admin");
		
		if(!merchant.getSignType().equals(0)) {
			response.failure("不支持开通此类型商户");
	        return response;
		}
		if(StringUtils.isEmpty(merchant.getLibId())) {
			merchant.setLibId(null);
		}
	    return merchantService.saveMerchantByUsed(merchant, startTime, endTime,contractTimeStr, password, province, city, area, schoollist, location, curadmin);
    }
	
	
	//端口商户建立
	@RequestMapping("/saveMerchant")
	@ResponseBody
    public Response saveMerchant(Model model,Merchant merchant,String startTime,String endTime,String startActiveTimeStr,String activeTimeStr,String computeTimeStr
    		,String contractTimeStr,String password,String province,String city,String area,String schoollist,String location)throws Exception {
		HttpSession session = request.getSession();
		Admin curadmin =(Admin) session.getAttribute("admin");
		if(StringUtils.isEmpty(merchant.getLibId())) {
			merchant.setLibId(null);
		}
        return merchantService.saveMerchantByNew(merchant, startTime, endTime,startActiveTimeStr,activeTimeStr, computeTimeStr,contractTimeStr, password, province, city, area, schoollist, location, curadmin);
		
    }
	
	//学校商户建立
	@RequestMapping("/saveMerchantSc")
	@ResponseBody
    public Response saveMerchantSc(Model model,Merchant merchant,String startTime,String endTime,String activeTimeStr,String endActiveTimeStr
    		,String contractTimeStr,String password,String province,String city,String area,String schoollist,String location)throws Exception {
		HttpSession session = request.getSession();
		Admin curadmin =(Admin) session.getAttribute("admin");
		if(StringUtils.isEmpty(merchant.getLibId())) {
			merchant.setLibId(null);
		}
        return merchantService.saveMerchantByNew_Sc(merchant, startTime, endTime,activeTimeStr, endActiveTimeStr,contractTimeStr, password, province, city, area, schoollist, location, curadmin);
    }
 	
 	
	
	
	
	
	/**
	 * 
	 * 
	 * --------------------------------------------------------------------------------------------------
	 * CRM 商户相关功能重构
	 * 2020年12月28日14:59:35
	 * 
	 */

	//手动刷新商户的服务人数与服务日期
	@RequestMapping("/refMeal")
	@ResponseBody
    public Response refMeal(Model model,String id)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(id)) {
			try {
				logger.info("手动刷新服务人数与日期，开始>id="+id);
				merchantMealService.updateMerchantByMeal(id);
			} catch (Exception e) {
				logger.info("手动刷新服务人数与日期，异常...>id="+id);
				e.printStackTrace();
			}
		}else {
			List<Merchant> merchants=merchantService.findMerchantSignByAll();
			for (Merchant merchant : merchants) {
				try {
					logger.info("手动刷新服务人数与日期，开始>id="+merchant.getId());
					merchantMealService.updateMerchantByMeal(merchant.getId());
				} catch (Exception e) {
					logger.info("手动刷新服务人数与日期，异常...>id="+merchant.getId());
					e.printStackTrace();
				}
				//停2秒
				Thread.sleep(2000);
			}
		}
        return response;
    }
	
	
	//服务包订单表
	@RequestMapping("/merchantMealOrderList")
    public String merchantMealOrderList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
        params.put("signType", request.getParameter("signType")==null?"":request.getParameter("signType"));
        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = merchantMealOrderService.findMerchantMealOrderByPage(params, initPage(pageNo, pageSize, 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);
        List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
        return "sys/fx/merchantMealOrderList";
    }
	
	
	//服务包订单明细表
	@RequestMapping("/merchantMealList")
    public String merchantMealList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderId", request.getParameter("orderId")==null?"":request.getParameter("orderId"));
        params.put("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = merchantMealService.findMerchantMealByPage(params, initPage(pageNo, pageSize, 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);
        List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
        return "sys/fx/merchantMealList";
    }
	
	
	//服务包订单明细表
	@RequestMapping("/merchantMealStatusList")
    public String merchantMealStatusList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
        params.put("signType", request.getParameter("signType")==null?"":request.getParameter("signType"));
        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = merchantMealService.findMerchantMealStatusPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"createTime"}));
        sp.setRowCnt((int) page.getTotalElements());
        
        List<Map<String, Object>> mapList=page.getContent();
        for (Map<String, Object> map : mapList) {
        	if(map.get("sign_type")!=null) {
	        	map.put("pr_1", ((int)map.get("buy_month")+(int)map.get("give_month"))>0? new BigDecimal((new BigDecimal(map.get("price").toString()).doubleValue()/(int)map.get("lib_service")/((int)map.get("buy_month")+(int)map.get("give_month")))).setScale(2, RoundingMode.UP).doubleValue() : "0.0");
	        	map.put("pr_6", new BigDecimal(map.get("unit_price").toString()).doubleValue()*((int)map.get("buy_month")+(int)map.get("give_month")));
	        	
	        	map.put("pr_2", ((int)map.get("buy_month")+(int)map.get("give_month"))>0? new BigDecimal(((double)map.get("pr_6")/(int)map.get("lib_service")/((int)map.get("buy_month")+(int)map.get("give_month")))).setScale(2, RoundingMode.UP).doubleValue() : "0.0");
	        	map.put("pr_3", ((int)map.get("buy_month")+(int)map.get("give_month"))>0? new BigDecimal(new BigDecimal(map.get("price").toString()).doubleValue()/((int)map.get("buy_month")+(int)map.get("give_month"))).setScale(2, RoundingMode.UP).doubleValue() : "0.0" );
	        	map.put("pr_4", map.get("unit_price"));
	        	map.put("pr_5", map.get("price"));
        	}else {
        		map.put("pr_1","");
        		map.put("pr_2","");
        		map.put("pr_3","");
        		map.put("pr_4","");
        		map.put("pr_5","");
        		map.put("pr_6","");
        	}
		}
        model.addAttribute("list", mapList);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
        return "sys/fx/merchantMealStatusList";
    }
	
	
	
	//加油包订单列表
	@RequestMapping("/merchantSignOrderList")
    public String merchantSignOrderList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
        params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = merchantSignOrderService.findMerchantSignOrderByPage(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);
        List<Merchant> list=merchantService.findMerchantByPage();	
		model.addAttribute("poslist", list);
        return "sys/fx/merchantSignOrderList";
    }
	
	
	//管理费订单列表
	@RequestMapping("/merchantPlatOrderList")
    public String merchantplatOrderList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = merchantPlatOrderService.findMerchantPlatOrderByPage(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);
        List<Merchant> list=merchantService.findMerchantByPage();	
		model.addAttribute("poslist", list);
        return "sys/fx/merchantPlatOrderList";
    }
		
	
	
	
	//加油包明细列表
	@RequestMapping("/merchantSignList")
    public String merchantSignList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
        params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
        params.put("orderId", request.getParameter("orderId")==null?"":request.getParameter("orderId"));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = merchantSignService.findMerchantSignByPage(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);
        List<Merchant> list=merchantService.findMerchantByPage();	
		model.addAttribute("poslist", list);
        return "sys/fx/merchantSignList";
    }
	
	
	//服务包订单明细表
	@RequestMapping("/merchantSignStatusList")
    public String merchantSignStatusList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
        params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = merchantSignService.findMerchantSignStatusByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"createTime"}));
        sp.setRowCnt((int) page.getTotalElements());
        
        List<Map<String, Object>> mapList=page.getContent();
        for (Map<String, Object> map : mapList) {
        	if(map.get("type")!=null) {
	        	map.put("pr_1", (int)map.get("lib_service")>0 ? new BigDecimal(new BigDecimal(map.get("unit_price").toString()).doubleValue()/(int)map.get("lib_service")).setScale(2, RoundingMode.UP).doubleValue() : "0.0");
	        	map.put("pr_2", new BigDecimal(map.get("unit_price").toString()).doubleValue());
        	}else {
        		map.put("pr_1","");
        		map.put("pr_2","");
        	}
		}
        model.addAttribute("list", mapList);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
        return "sys/fx/merchantSignStatusList";
    }
	
	
	
	//端口资金流水表
	@RequestMapping("/merchantCapList")
    public String merchantCapList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("merchantId", request.getParameter("merchantId")==null?"":request.getParameter("merchantId"));
        params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
        params.put("signTime", request.getParameter("signTime")==null?"":request.getParameter("signTime"));
        params.put("endSignTime", request.getParameter("endSignTime")==null?"":request.getParameter("endSignTime"));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = merchantMealService.findMerchantCapByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"createTime"}));
        sp.setRowCnt((int) page.getTotalElements());
        
        List<Map<String, Object>> mapList=page.getContent();
        for (Map<String, Object> map : mapList) {
        	if(Integer.parseInt(map.get("cap_type").toString())==1) {
        		map.put("pr_1",new BigDecimal(new BigDecimal(map.get("price").toString()).doubleValue()/(Integer.parseInt(map.get("buy_month").toString())+Integer.parseInt(map.get("give_month").toString()))/Integer.parseInt(map.get("lib_service").toString())).setScale(2, RoundingMode.UP).doubleValue());
        		map.put("pr_2",map.get("price"));
        		map.put("pr_3","");
        	}else if(Integer.parseInt(map.get("cap_type").toString())==2) {
        		map.put("pr_1",new BigDecimal(new BigDecimal(map.get("price").toString()).doubleValue()/(Integer.parseInt(map.get("buy_month").toString())+Integer.parseInt(map.get("give_month").toString()))/Integer.parseInt(map.get("lib_service").toString())).setScale(2, RoundingMode.UP).doubleValue());
        		map.put("pr_2","");
        		map.put("pr_3",new BigDecimal(new BigDecimal(map.get("price").toString()).doubleValue()/(Integer.parseInt(map.get("buy_month").toString())+Integer.parseInt(map.get("give_month").toString()))).setScale(2, RoundingMode.UP).doubleValue());
        	}else if(Integer.parseInt(map.get("cap_type").toString())==3) {
        		map.put("pr_1","");
        		map.put("pr_2",map.get("price"));
        		map.put("pr_3","");
        	}else if(Integer.parseInt(map.get("cap_type").toString())==4) {
        		map.put("pr_1","");
        		map.put("pr_2","");
        		map.put("pr_3",map.get("price"));
        	}else if(Integer.parseInt(map.get("cap_type").toString())==5) {
        		map.put("pr_1", new BigDecimal(new BigDecimal(map.get("unit_price").toString()).doubleValue()*(Integer.parseInt(map.get("buy_month").toString()))/Integer.parseInt(map.get("lib_service").toString())).setScale(2, RoundingMode.UP).doubleValue());
        		map.put("pr_2", new BigDecimal(new BigDecimal(map.get("unit_price").toString()).doubleValue()*(Integer.parseInt(map.get("buy_month").toString()))).setScale(2, RoundingMode.UP).doubleValue());
        		map.put("pr_3","");
        	}else if(Integer.parseInt(map.get("cap_type").toString())==6) {
        		map.put("pr_1", new BigDecimal(new BigDecimal(map.get("unit_price").toString()).doubleValue()/Integer.parseInt(map.get("lib_service").toString())).setScale(2, RoundingMode.UP).doubleValue());
        		map.put("pr_2","");
        		map.put("pr_3",map.get("unit_price"));
        	}
		}
        model.addAttribute("list", mapList);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        List<Merchant> list=merchantService.findMerchantByPage();
		model.addAttribute("poslist", list);
        return "sys/fx/merchantCapList";
    }
	
	
	//端口服务包开通
	@RequestMapping("/merchantMealAdd")
    public String merchantMealAdd(Model model,String id)throws Exception {
		Merchant merchant=merchantService.getById(id);
		List<MerchantMealOrder> list=merchantMealOrderService.findMerchantMealOrderAll(id);
		model.addAttribute("merchant", merchant);
		model.addAttribute("list", list);
        return "sys/fx/merchantMealAdd";
    }
	
	//学校服务包开通
	@RequestMapping("/merchantMealScAdd")
    public String merchantMealSCAdd(Model model,String id)throws Exception {
		Merchant merchant=merchantService.getById(id);
		List<MerchantMealOrder> list=merchantMealOrderService.findMerchantMealOrderAll(id);
		model.addAttribute("merchant", merchant);
		model.addAttribute("list", list);
        return "sys/fx/merchantMealScAdd";
    }
	
	//端口服务包开通
	@RequestMapping("/merchantPlatAdd")
    public String merchantPlatAdd(Model model,String id)throws Exception {
		Merchant merchant=merchantService.getById(id);
		List<MerchantPlatOrder> list=merchantPlatOrderService.findMerchantPlatOrderAll(id);
		model.addAttribute("merchant", merchant);
		model.addAttribute("list", list);
        return "sys/fx/merchantPlatAdd";
    }

	//加油包开通
	@RequestMapping("/merchantSignAdd")
    public String merchantSignAdd(Model model,String id)throws Exception {
		Merchant merchant=merchantService.getById(id);
		List<MerchantSignOrder> list=merchantSignOrderService.findMerchantSignAll(id);
		//计算出加油包的激活日期
		Date signTime=new Date();
		if(merchant.getActiveTime()!=null && merchant.getActiveTime().getTime()>=new Date().getTime()) {
			signTime=merchant.getActiveTime();
		}
		model.addAttribute("signTime", signTime);
		model.addAttribute("merchant", merchant);
		model.addAttribute("list", list);
        return "sys/fx/merchantSignAdd";
    }
	
	
	//端口服务包开通保存
	@RequestMapping("/saveMerchantMeal")
	@ResponseBody
    public Response saveMerchantMeal(Model model,String id,Integer signType,Integer libService,Integer buyMonth,Integer giveMonth,Double unitPrice,Double price)throws Exception {
		Response response = new  Response();
		if(signType==null) {
			response.failure("请选择购买的服务包");
			return response;
		}
		if(buyMonth==null || buyMonth<=0) {
			response.failure("购买月份不可小于1");
			return response;
		}
		if(libService==null) {
			libService=0;
		}
		if(unitPrice==null) {
			unitPrice=(double) 0;
		}
		if(price==null) {
			price=(double) 0;
		}
		Merchant merchant=merchantService.getById(id);
		if(merchant.getPosType()==2) {
			merchantMealService.saveMerchantMeal(id, signType, libService, buyMonth, giveMonth, unitPrice, price);
			response.success("成功");
		}else {
			response.failure("商户类型不可购买此服务包");
		}
        return response;
    }
	
	////学校服务包开通
	@RequestMapping("/saveMerchantMealSc")
	@ResponseBody
    public Response saveMerchantMealSc(Model model,String id,Integer signType,Integer libService,String startActiveTime,String endActiveTime,Double unitPrice,Double price)throws Exception {
		Response response = new  Response();
		if(signType==null) {
			response.failure("请选择购买的服务包");
			return response;
		}
		if(StringUtils.isEmpty(startActiveTime)) {
			response.failure("试用开始日期不可为空");
			return response;
		}
		if(StringUtils.isEmpty(endActiveTime)) {
			response.failure("试用结束日期不可为空");
			return response;
		}
		if(libService==null) {
			libService=0;
		}
		if(unitPrice==null) {
			unitPrice=(double) 0;
		}
		if(price==null) {
			price=(double) 0;
		}
		Merchant merchant=merchantService.getById(id);
		if(merchant.getPosType()==3) {
			merchantMealService.saveMerchantMealSC(id, signType, libService, startActiveTime, endActiveTime, unitPrice, price);
			response.success("成功");
		}else {
			response.failure("商户类型不可购买此服务包");
		}
        return response;
    }
	
	
	@RequestMapping(value="/saveMerchantSign")
	@ResponseBody
	public Response saveMerchantSign(Model model, String id,Integer type,Integer num,Integer libService,String signTime,Double unitPrice) {
		Response response = new  Response();
		if(type==null) {
			response.failure("请选择购买的加油包");
			return response;
		}
		if(num==null || num<=0) {
			response.failure("购买的加油包数量不可小于1喔");
			return response;
		}
		if(StringUtils.isEmpty(signTime)) {
			response.failure("激活日期不可为空");
			return response;
		}
		merchantSignService.saveMerchantSign(id, type, num, libService, signTime, unitPrice);
		response.success("操作成功");
		return response;
	}
	
	
	@RequestMapping(value="/saveMerchantPlat")
	@ResponseBody
	public Response saveMerchantPlat(Model model, String id,Double price,String remarks) {
		Response response = new  Response();
		if(price==null || price<=0) {
			response.failure("请输入管理费用金额");
			return response;
		}
		Merchant merchant=merchantService.getById(id);
		merchant.setOutPrice(price);
		
		MerchantPlatOrder platOrder=new MerchantPlatOrder();
		platOrder.setMerchantId(id);
		platOrder.setMealType(merchant.getMealType());
		platOrder.setPrice(price);
		platOrder.setRemarks(remarks);
		platOrder.setCreateTime(new Date());
		merchantPlatOrderService.save(platOrder);
		merchantService.save(merchant);
		
		response.success("操作成功");
		return response;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}