package com.chinacreator.video.service;

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

import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.exception.BusinessException;
import com.chinacreator.video.restful.dao.QueryCapOrderDao;
import com.chinacreator.video.util.RedisService;
import net.sf.ehcache.CacheManager;
import org.apache.commons.lang.StringUtils;
import org.apache.el.lang.ELArithmetic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Component;

import com.chinacreator.video.bean.AreaInfo;
import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.HandleOrgMap;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelBusiLimitDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.mapper.QueryOrderDao;
import com.chinacreator.video.mapper.UnifiedInvokeDao;
import com.chinacreator.video.util.ApplicationContextUtils;
import com.chinacreator.video.util.AreaUtil;
import com.chinacreator.video.util.SpringUtils;
import com.chinacreator.video.validate.ChannelValidate;
import com.chinacreator.video.validate.IpValidate;
import com.chinacreator.video.validate.MobValidate;
import com.chinacreator.video.validate.SignValidate;
import com.chinacreator.video.validate.TimetampValidate;

@Component
public class HandleService {

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private SignValidate signValidate;

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private MobValidate mobValidate;

    @Autowired
    private HandleOrgMap handleOrgMap;

    @Autowired
    private UnifiedInvokeDao unifiedInvokeDao;

    @Autowired
    private QueryOrderDao queryOrderDao;

    @Autowired
    private RedisService redisService;

    @Autowired
    private QueryCapOrderDao queryCapOrderDao;

    @Autowired
    private CommonService commonService;

    private Integer cnt=0;
    
	@Autowired
	private ChannelBusiLimitDao cblDao;
	
    @Autowired
    private DictionaryDao dictionaryDao;

    public void check(OrderInfo orderInfo) throws Exception {
        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        //channelValidate.validate(orderInfo.getChannel());
		//渠道验证，如果是二级渠道，包含了IP验证
		boolean hasChannelBuild = channelValidate.validate(orderInfo);
		//非二级渠道，要另外进行IP验证
		if(!hasChannelBuild){
			//ip验证
			ipValidate.volidate(orderInfo);
		}
        //签名验证
        signValidate.validate(orderInfo);
        //手机号码验证
        mobValidate.validate(orderInfo);
        //省份限制验证
        valiProvLimit(orderInfo);
        //token检验
        //checkToken(orderInfo);
        //访问限制
        vistValiByHandle(orderInfo);
    }

    /**
     * 验证访问限制，1分钟内同一业务只能办理一次
     * @param orderInfo
     * @throws Exception
     */
    private void vistValiByHandle(OrderInfo orderInfo) throws Exception {
        String [] params = new String [3];
        params[0] = orderInfo.getType();
        params[1] = orderInfo.getUserid();
        params[2] = orderInfo.getSpid();
        if(commonService.vistVali2(params, "handle")){
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }

    /**
     * token校验
     *
     * @param orderInfo
     */
    public void checkToken(OrderInfo orderInfo) throws BussinessException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
        String format = simpleDateFormat.format(new Date());
        String token = orderInfo.getToken();
        if (StringUtils.isEmpty(token)) {
            return;
        }
        if (token.length() != 32) {
            throw new BussinessException("9003", "token位数不对");
        }
        Long hincr = redisService.hincr(format, token, 1L);
        if (hincr > 1) {
            throw new BussinessException("9002", "token重复");
        }
    }


    public void handle(OrderInfo orderInfo) throws Exception {
    	//办理限制
        commonService.valiChannelSpidLimit(orderInfo);
        String handle = "";
        String resultcode = "0";
        String errorinfo = "";
        String id = "";
        try {
            //获取接口转发配置信息
            List<Map> unifiedInvokeList = unifiedInvokeDao.getConfig(orderInfo.getChannel());
            //System.out.println("=========unifiedInvokeList======> "+unifiedInvokeList);
            if (unifiedInvokeList != null && unifiedInvokeList.size() > 0) {
                Map map = null;
                for (int i = 0; i < unifiedInvokeList.size(); i++) {
                    map = unifiedInvokeList.get(i);
                    if (map.get("CHANNEL").equals(orderInfo.getChannel())
                            && map.get("CPID").equals(orderInfo.getCpid())
                            && map.get("SPID").equals(orderInfo.getSpid())) {
                        handle = (String) map.get("HANDLE");
                        break;
                    }
                }
            }
            //getCache();
            if (!StringUtils.isEmpty(handle)) {
                //if("specifyOrder".equals(handle)){
                spidSwitch(orderInfo);
                //}
                IHandleService iHandleService = (IHandleService) SpringUtils.getBean(handle);
                if ("0".equals(orderInfo.getType())) {
                    try {
                        id = queryCapOrderDao.getID();
                        queryCapOrderDao.insertQueryCap(id, orderInfo);
                    } catch (Exception e) {
                        cnt++;
                        if (cnt>900){
                            cnt=0;
                        }
                            try {
                            id=id+cnt;
                            queryCapOrderDao.insertQueryCap(id, orderInfo);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }
                    try {
                        iHandleService.handle(orderInfo);
                    } catch (Exception e) {
                        if (e instanceof BussinessException) {
                            resultcode = ((BussinessException) e).getCode();
                            errorinfo = e.getMessage();
                        }
                        throw e;
                    } finally {
                        try {
                            if (StringUtils.isNotEmpty(id)) {
                                Map<String, String> map = new HashMap<>();
                                map.put("resultcode", resultcode);
                                map.put("errorinfo", errorinfo);
                                queryCapOrderDao.updateQueryCap(id, JSONObject.toJSONString(map));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    iHandleService.handle(orderInfo);
                }

            } else {
				//渠道建设新增加的渠道信息验证
				ChannelBean channelBean = cblDao.qryChannelConfById(orderInfo.getChannel());
				//是二级渠道
				if("1".equals(channelBean.getIspage()) && "对外接口类".equals(channelBean.getShape())){
					//101走video-activity/order.do
					if("101".equals(orderInfo.getSpid())){
						IHandleService iHandleService = (IHandleService) SpringUtils.getBean("specifyOrder");
						iHandleService.handle(orderInfo);
					//其他走videoif/order.do
					}else{
						IHandleService iHandleService = (IHandleService) SpringUtils.getBean("commonOrder");
						iHandleService.handle(orderInfo);
					}
				}else{
					throw new BussinessException("10011", "无业务办理配置信息");
				}
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                throw e;
            } else {
                if (e.getMessage().indexOf("SQLException") != 0) {
                    throw new BussinessException("10013", "匹配转接口出现SQLException异常。");
                } else {
                    throw new BussinessException("10013", "匹配转接口出现异常，" + e.getMessage());
                }
            }
        }
    }

    /**
     * SPID转换
     */
    public void spidSwitch(OrderInfo orderInfo) throws Exception {
        try {
            //腾讯101退订，如果当前生效的84，把spid改为84
            if ("1".equals(orderInfo.getType()) && "tencent".equals(orderInfo.getCpid()) && "101".equals(orderInfo.getSpid())) {
                //System.out.println("=======================腾讯101退订");
                List<OrderInfo> list = queryOrderDao.getOrder(orderInfo.getUserid());
                OrderInfo bean101 = null;
                OrderInfo bean84 = null;
                if (list != null && list.size() > 0) {
                    for (OrderInfo oi : list) {
                        if ("tencent".equals(oi.getCpid()) && "84".equals(oi.getSpid())) {
                            bean84 = oi;
                            break;
                            //}else if("tencent".equals(oi.getCpid()) && "101".equals(oi.getSpid())){
                            //bean101 = oi;
                        }
                    }
                }
                //System.out.println("bean101:"+bean101);
                //System.out.println("bean84:"+bean84);
                //本地订购关系的是84且是订购状态
                if (bean84 != null && "0".equals(bean84.getStatus())) {
                    orderInfo.setSpid("84");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BussinessException("10012", "转换SPID出现异常，" + e.getMessage());
        }
    }

    private void getCache() {
        EhCacheCacheManager cacheCacheManager = ApplicationContextUtils.applicationContext.getBean(EhCacheCacheManager.class);
        CacheManager cacheManager = cacheCacheManager.getCacheManager();
        String[] cacheNames = cacheManager.getCacheNames();
        for (String name : cacheNames) {
            System.out.println("cacheName:" + name);
            net.sf.ehcache.Cache cache = cacheManager.getCache(name);
            List list = cache.getKeys();
            System.out.println(list);
        }
    }
    
    /**
     * 省份限制验证
     * @param orderInfo
     */
    public void valiProvLimit(OrderInfo orderInfo) throws Exception{
    	//获取数据库的配置信息
    	String handleProvLimit = dictionaryDao.getValue("handleProvLimit"+orderInfo.getChannel());
    	//只有订购才限制
    	if(!StringUtils.isEmpty(handleProvLimit) && "0".equals(orderInfo.getType())){
    		//转为LIST
    		List<String> provList =  Arrays.asList(handleProvLimit.trim().split(","));
    		if(provList != null && provList.size()>0){
    			String province = orderInfo.getProvince();
    			//省份为空
    			if(StringUtils.isEmpty(province)){
        			//获取地市信息
                	AreaInfo areaInfo = AreaUtil.getAreaInfoByUserid(orderInfo.getUserid());
                	if(areaInfo != null){
                		province = areaInfo.getProvince();
                		orderInfo.setProvince(province);
                	}
    			}
    			//判断省份是否包含在限制配置内
    			if(!StringUtils.isEmpty(province) && provList.contains(province)){
    				throw new BussinessException("80016", "抱歉，您当前暂不能参加此活动");
    			}
    		}
    	}
    }
}
