package com.ssj.sys.controller;

import com.ssj.bean.kmt.kmt.domain.KmtCourse;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.service.kmt.service.KmtCourseService;
import com.ssj.service.sys.counter.service.CounterService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.library.service.ILibSubscribeService;
import com.ssj.service.weixin.order.service.LessonServiceSalesService;
import com.ssj.service.weixin.order.service.OrderDetailsService;
import com.ssj.sys.model.FrontCounter;
import com.ssj.sys.model.SignModel;
import com.ssj.sys.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("sys/counter")
@Controller
public class CounterController extends BaseController {

	@Autowired
	private CounterService counterService;
	@Autowired
	private OrderDetailsService orderDetailsService;
	@Autowired
	private ILibJoinService libJoinService;
	@Autowired
	private ILibSubscribeService libSubscribeService;
	@Autowired
	private LessonServiceSalesService lessonServiceSalesService;
	@Autowired
	private KmtCourseService kmtCourseService;



	

    @RequestMapping(value = "/selectOpenCard")
    @ResponseBody
    public ResponseEntity selectOpenCard(Boolean iscount) {
    	ResponseEntity responseEntity = new ResponseEntity();
    	boolean is=false;
    	try{
    		String libIds="";
     	    List<TbLibJoin> list= libJoinService.getLibJoinByCode(orgcodeList());
     	    if(list!=null && list.size()>0){
     	    	//libId=list.get(0).getId();
     	    	for (TbLibJoin tbLibJoin : list) {
     	    		libIds+=tbLibJoin.getId()+";";
 				}
     	    	libIds=libIds.substring(0, libIds.length()-1);
     	    }
	        List<Map<String, Object>> payUserCounters=counterService.getPayUserCounter(libIds,iscount);
	        List<Map<String, Object>> notActiveCounters=counterService.getNotActiveCounter(libIds,iscount);
	        for (Map<String, Object> payUser : payUserCounters) {
	        	String libId=payUser.get("lib_id").toString();
	        	is=false;
				for (Map<String, Object> notActive : notActiveCounters) {
					if(libId.equals(notActive.get("lib_id").toString())){
						is=true;
						payUser.put("notactivenum", notActive.get("notactivenum").toString());
					}
				}
				if(!is){
					payUser.put("notactivenum", "0");
				}
			}
	    	Map<String, Object> map =new HashMap<String, Object>();
	    	map.put("rows", payUserCounters);
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }
	
	
    @RequestMapping(value = "/selectCounter")
    @ResponseBody
    public ResponseEntity selectCounter(String type,String startDate, String endDate,String selectLibId) {
    	ResponseEntity responseEntity = new ResponseEntity();
    	try{
    		SimpleDateFormat formatter= new SimpleDateFormat ("yyyy-MM-dd"); 
    	    Date startTime = formatter.parse(startDate);
    	    Date endTime = formatter.parse(endDate);
    	    String libId="";
    	    if(StringUtils.isNotEmpty(selectLibId)){
    	    	libId=selectLibId;
    	    }else{
	    	    List<TbLibJoin> list= libJoinService.getLibJoinByCode(orgcodeList());
	    	    if(list!=null && list.size()>0){
	    	    	for (TbLibJoin tbLibJoin : list) {
	    	    		libId+=tbLibJoin.getId()+";";
					}
	    	    	libId=libId.substring(0, libId.length()-1);
	    	    }
    	    }
	        List<Map<String, Object>> counters=counterService.selectByCounter(libId, type, startTime, endTime);
	    	Map<String, Object> map =new HashMap<String, Object>();
	    	map.put("rows", counters);
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }
    
    @RequestMapping(value = "/frontCounter")
    @ResponseBody
    public ResponseEntity frontCounter(String selectLibId) {
    	ResponseEntity responseEntity = new ResponseEntity();
    	try{
    		String libId="";
    		  if(StringUtils.isNotEmpty(selectLibId)){
      	    	libId=selectLibId;
      	    }else{
  	    	    List<TbLibJoin> list= libJoinService.getLibJoinByCode(orgcodeList());
  	    	    if(list!=null && list.size()>0){
  	    	    	for (TbLibJoin tbLibJoin : list) {
  	    	    		libId+=tbLibJoin.getId()+";";
  					}
  	    	    	libId=libId.substring(0, libId.length()-1);
  	    	    }
      	    }
    		FrontCounter frontCounter=new FrontCounter();
    		frontCounter.setUserAddNum(counterService.frontByCounter(libId, Constants.USERADD));
    		frontCounter.setSignNum(counterService.frontByCounter(libId, Constants.SIGN));
    		frontCounter.setBorrowNum(counterService.frontByCounter(libId, Constants.BORROW));
    		frontCounter.setOrderDay(counterService.frontByCounter(libId, Constants.ORDERDAY));
    		frontCounter.setOrderCount(counterService.frontByCounter(libId, Constants.ORDER));
	    	Map<String, Object> map =new HashMap<String, Object>();
	    	map.put("frontCounter", frontCounter);
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }
    
    @RequestMapping(value = "/top")
    @ResponseBody
    public ResponseEntity top(String selectLibId) {
    	ResponseEntity responseEntity = new ResponseEntity();
    	try{
    		String libId="";
    		if(StringUtils.isNotEmpty(selectLibId)){
      	    	libId=selectLibId;
      	    }else{
  	    	    List<TbLibJoin> list= libJoinService.getLibJoinByCode(orgcodeList());
  	    	    if(list!=null && list.size()>0){
  	    	    	for (TbLibJoin tbLibJoin : list) {
  	    	    		libId+=tbLibJoin.getId()+";";
  					}
  	    	    	libId=libId.substring(0, libId.length()-1);
  	    	    }
      	    }
    		List<Map<String, Object>> tops=orderDetailsService.countOrderDetailsByTop(libId);
	    	Map<String, Object> map =new HashMap<String, Object>();
	    	map.put("rows", tops);
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }
    
    @RequestMapping(value = "/topByUser")
    @ResponseBody
    public ResponseEntity topByUser(String selectLibId) {
    	ResponseEntity responseEntity = new ResponseEntity();
    	try{
    		String libId="";
    		if(StringUtils.isNotEmpty(selectLibId)){
      	    	libId=selectLibId;
      	    }else{
  	    	    List<TbLibJoin> list= libJoinService.getLibJoinByCode(orgcodeList());
  	    	    if(list!=null && list.size()>0){
  	    	    	for (TbLibJoin tbLibJoin : list) {
  	    	    		libId+=tbLibJoin.getId()+";";
  					}
  	    	    	libId=libId.substring(0, libId.length()-1);
  	    	    }
      	    }
    		List<Map<String, Object>> tops=orderDetailsService.countOrderDetailsByUser(libId);
	    	Map<String, Object> map =new HashMap<String, Object>();
	    	map.put("rows", tops);
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }
    
    @RequestMapping(value = "/topByDayUser")
    @ResponseBody
    public ResponseEntity topByDayUser(String selectLibId) {
    	ResponseEntity responseEntity = new ResponseEntity();
    	try{
    		String libId="";
    		if(StringUtils.isNotEmpty(selectLibId)){
      	    	libId=selectLibId;
      	    }else{
  	    	    List<TbLibJoin> list= libJoinService.getLibJoinByCode(orgcodeList());
  	    	    if(list!=null && list.size()>0){
  	    	    	for (TbLibJoin tbLibJoin : list) {
  	    	    		libId+=tbLibJoin.getId()+";";
  					}
  	    	    	libId=libId.substring(0, libId.length()-1);
  	    	    }
      	    }
    		List<Map<String, Object>> tops=orderDetailsService.countOrderDetailsByDayUser(libId);
	    	Map<String, Object> map =new HashMap<String, Object>();
	    	map.put("rows", tops);
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }
    
    @RequestMapping(value = "/signCounter")
    @ResponseBody
    public ResponseEntity signCounter(String selectLibId) {
    	ResponseEntity responseEntity = new ResponseEntity();
    	try{
    		String libId="";
    		if(StringUtils.isNotEmpty(selectLibId)){
      	    	libId=selectLibId;
      	    }else{
  	    	    List<TbLibJoin> list= libJoinService.getLibJoinByCode(orgcodeList());
  	    	    if(list!=null && list.size()>0){
  	    	    	for (TbLibJoin tbLibJoin : list) {
  	    	    		libId+=tbLibJoin.getId()+";";
  					}
  	    	    	libId=libId.substring(0, libId.length()-1);
  	    	    }
      	    }
    		
    		//30天内的
    		//Integer withinThirty=orderDetailsService.signSubscribCounter(libId, 30, "<=");
    		
    		//全约过的-30天内的=30天无签到记录，但以往有签到记录
    		//Integer count=orderDetailsService.signSubscribCount(libId);
    		//Integer signcounnt=orderDetailsService.signSubscribCounter(libId, 0, ">=");
    		//Integer frontThirty=signcounnt-withinThirty;
    		
    		//总的卡数-60天内的=近60天无任何使用记录
    		//Integer withinSixty=orderDetailsService.signSubscribCounter(libId, 60, "<=");
    		//withinSixty=count-withinSixty;
    		
    		SignModel sign=new SignModel();
    		sign.setWithinThirty(counterService.exportActive(libId).size());
    		sign.setFrontThirty(counterService.exportImminent(libId).size());
    		sign.setWithinSixty(counterService.exportSilent(libId).size());
    		
	    	Map<String, Object> map =new HashMap<String, Object>();
	    	map.put("sign", sign);
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }
    
    
    
    
    

    
    

    @RequestMapping(value = "/runsales")
    @ResponseBody
    public ResponseEntity runsales(String id) {
    	ResponseEntity responseEntity = new ResponseEntity();
    	try{
			//结课后 插入财务分成数据
			KmtCourse course = kmtCourseService.getById(id);
			TbLibJoin lib = libJoinService.findOneByCourseId(course.getId());
			if (lib != null) {
				if (Objects.equals(2, lib.getLibtype()) || Objects.equals(3, lib.getLibtype())) {//共享馆
					lessonServiceSalesService.saveLessonServiceSalesByCourseSharedLib(course);
				} else {//非共享馆
					lessonServiceSalesService.saveLessonServiceSalesByCourse(course.getId());
				}
			} else {
				logger.error("结课后 插入财务分成数据，发现异常，查询不到对应的馆，courseId" + course.getId());
			}
	    	Map<String, Object> map =new HashMap<String, Object>();	
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }
    
    

    @RequestMapping(value = "/runcount")
    @ResponseBody
    public ResponseEntity runcount() {
    	ResponseEntity responseEntity = new ResponseEntity();
    	try{
    		
    		
    		try {
    			logger.info("每月第一天早上八点更新上月的结算金额统计");
    			Date endDate   =new  Date();
    			Date startDate = DateHelper.getLastMonthFirstDay(endDate);//上月的第一天
    			endDate =DateHelper.getLastMonthLastDay(endDate);//上月的最后一天
    			LessonServiceSalesService lessonServiceSalesService =  SystemResourceLocator.getBean(LessonServiceSalesService.class);
    			lessonServiceSalesService.countLessonServiceSalesByTime(startDate, endDate);
    		} catch (Exception e) {
    			logger.error("每月第一天早上八点更新上月的结算金额统计异常-->"+e.getMessage());
    		}finally{
    			logger.info("每月第一天早上八点更新上月的结算金额统计结束");
    		}
    		
    		
	    	Map<String, Object> map =new HashMap<String, Object>();	
	    	responseEntity.success(map,"操作成功");
    	}catch (Exception e) {
  	      e.printStackTrace();
	    }
    	return responseEntity;
    }

}
