package com.ssj.api.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ssj.api.domain.vo.merchant.ServiceVo;
import com.ssj.api.security.annotation.IgnoreSecurity;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.weixin.libmy.domain.TbLibJoinConsume;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.weixin.library.service.ILibJoinConsumeService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "商户相关的", tags = "商户相关的")
@RestController
@RequestMapping("/open/api/merchant")
public class ApiMerchantController extends BaseController {
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private ILibJoinConsumeService  libJoinConsumeService;
	
	@Autowired
	private LibVipServiceService  libVipServiceService;
	
	
	//1：激活日期之前，生成一条数据为0的记录，重新设置激活日期，设置下一个结算日。
	//注：type=1处理
	
	//2：开始计费日之前的，由定时任务处理数据，这里不做处理。
	//注：type=1处理
	
	//3：开始计费日之后的，第1次激活的，生成一条真实的数据，设置下一个结算日。
	//注：type=1处理
	
	@IgnoreSecurity
	@RequestMapping(value = "/service")
    @ApiOperation(value = "获取商户套餐信息接口",  notes = "获取商户套餐信息接口")
    public ResponseEntity service(@RequestBody ServiceVo requestVO) {
		logger.info("第三方调用接口【service】，请求参数："+JSONObject.toJSONString(requestVO));
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String,Object> data=new HashMap<String, Object>();
        try {
        	Merchant merchant=merchantService.getMerchantByLibId(requestVO.getLibId());
        	if(merchant!=null && merchant.getStartActiveTime()!=null) {
        		if(merchant.getStartActiveTime().getTime()<=new Date().getTime()) {
        			//1：激活日期之后才可以生成数据，生成一条数据为0的记录，重新设置激活日期，设置下一个结算日。
        			List<TbLibJoinConsume> consumes=libJoinConsumeService.findTbLibJoinConsumeByStartActiveTime(merchant.getId(), merchant.getStartActiveTime());
        			if(consumes==null || consumes.size()<=0) {
        				logger.info("第三方调用接口【service】，商户产生激活期："+merchant.getId());
        				
        				if(merchant.getComputeTime()==null) {
        					merchant.setCurIsSummary(1);
        				}else {
        					merchant.setCurIsSummary(0);
        				}
	        			merchant.setActiveTime(new Date());
						merchant.setCurSummaryTime(new Date());
						merchant.setNextSummaryTime(DateHelper.getMonthDate(merchant.getCurSummaryTime(),1));
						merchantService.save(merchant);
						
						//记录
						TbLibJoinConsume consume=new TbLibJoinConsume();
						consume.setFromLibId(merchant.getLibId());
						consume.setFromMerchantId(merchant.getId());
						consume.setLibService(merchant.getLibService());
						consume.setPlatformService(0);
						consume.setType(7);
						consume.setSignType(merchant.getSignType());
						consume.setComputeNum(merchant.getCurIsSummary());
						consume.setRemarks("激活期扣费【服务包扣费】-来源开放接口");
						consume.setCreateTime(new Date());
						libJoinConsumeService.save(consume);
						
						
						if(merchant.getComputeTime()==null) {
							DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
							//调用openApi接口
							libVipServiceService.openApiServiceCRM(
									3,
									merchant.getLibId(), 
									merchant.getSignType(),
									merchant.getMealType(),
									merchant.getLibService(),
									merchant.getStartActiveTime()!=null ? format.format(merchant.getStartActiveTime()) : "",
									merchant.getComputeTime()!=null ? format.format(merchant.getComputeTime()) : format.format(merchant.getActiveTime()),
									merchant.getEndActiveTime()!=null ? format.format(merchant.getEndActiveTime()) :"" );
						}
        			}else {
        				
        				//自主激活的第一条都要记录，所以判断之前的数据是否有自主激活的，没有就保存一条。
        				boolean isActive=false;
            			for (TbLibJoinConsume tbLibJoinConsume : consumes) {
    						if(StringUtils.isNotEmpty(tbLibJoinConsume.getRemarks()) && tbLibJoinConsume.getRemarks().contains("来源开放接口")) {
    							isActive=true;
    						}
    					}
            			if(!isActive) {
            				//记录
    						TbLibJoinConsume consume=new TbLibJoinConsume();
    						consume.setFromLibId(merchant.getLibId());
    						consume.setFromMerchantId(merchant.getId());
    						consume.setLibService(merchant.getLibService());
    						consume.setPlatformService(0);
    						consume.setType(7);
    						consume.setSignType(merchant.getSignType());
    						consume.setComputeNum(merchant.getCurIsSummary());
    						consume.setRemarks("激活期扣费【服务包扣费】-来源开放接口");
    						consume.setCreateTime(new Date());
    						libJoinConsumeService.save(consume);
            			}
            			
            		}
        		}
	        	
	        	DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        		data.put("id", merchant.getId());
        		data.put("libId", merchant.getLibId());
        		data.put("startActiveTime", merchant.getStartActiveTime()!=null ?  format.format(merchant.getStartActiveTime()) : "");
        		data.put("summaryTime", merchant.getComputeTime()!=null ? 
        				format.format(merchant.getComputeTime()) :  format.format(merchant.getActiveTime()));
        		data.put("endSummaryTime", merchant.getEndActiveTime()!=null ? format.format(merchant.getEndActiveTime()) : "");
        		data.put("signType", merchant.getSignType());
        		data.put("mealType", merchant.getMealType());
        		data.put("libService", merchant.getLibService());
	            responseEntity.success(data, "获取商户套餐信息成功");
        	}else {
        		responseEntity.failure(ResponseConstant.CODE_500, "libId未绑定商户");
        	}
        } catch (Exception e) {
            logger.error("获取商户套餐信息接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        logger.info("第三方调用接口【service】，返回结果："+JSONObject.toJSONString(responseEntity));
        return responseEntity;
    }
	

	
}
