package com.duiba.tuia.youtui.web.controller;

import cn.com.duiba.tuia.activity.center.api.util.SignTool;
import com.duiba.tuia.youtui.web.service.AppService;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import cn.com.duiba.tuia.activity.center.api.remoteservice.RemoteAlipayService;
import com.duiba.tuia.youtui.web.tool.SecureTool;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.com.duibaboot.ext.autoconfigure.accesslog.MD5;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by xuefeng on 2017/11/18.
 */
@RestController
public class TestController {
    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private AppService appService;

    @Autowired
    RemoteAlipayService remoteAlipayService;

    @RequestMapping("/decrypt")
    public String decrypt(String data){
        return SecureTool.decryptConsumerCookie(data);
    }

    @RequestMapping("/success")
    public Object success(@RequestParam Map<String,Object> map){
        log.warn("虚拟商品成功请求参数 param={}", map.toString());
        String code = "0";
        String msg = "成功啦，高兴吧";
        if(!isExpire(map.get("timestamp").toString())){
        	code = "-3";
            msg = "过期的还请求你妹啊，5分钟的过期时间";
        }
        if(!map.get("sign").equals(getSign(map))){
        	code = "-4";
            msg = "签名不通过";
        }

        JSONObject json = new JSONObject();
        json.put("code",code);
        json.put("msg",msg);
        return json;
    }

    @RequestMapping("/fail")
    public Object fail(@RequestParam Map<String,Object> map){
        log.warn("虚拟商品失败请求参数 param={}", map.toString());
        JSONObject json = new JSONObject();
        json.put("code","-2");
        json.put("msg","请求失败，2b东雪");
        return json;
    }

    @RequestMapping("/retry")
    public Object retry(@RequestParam Map<String,Object> map){
        log.warn("虚拟商品重填请求参数 param={}",map.toString());
        JSONObject json = new JSONObject();
        json.put("code","-1");
        json.put("msg","东雪渣渣,重填");
        return json;
    }

    @RequestMapping("/timeout")
    public Object timeOut(@RequestParam Map<String,Object> map){
    	log.warn("虚拟商品超时请求参数 param={}",map.toString());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            log.warn("ex={}",e.getMessage());
            Thread.currentThread().interrupt();
        }
        return "ok";
    }

    /**
     * qb 测试用模拟接口，开发and测试环境用
     * 模拟充值成功
     * @param request
     * @return
     */
    @RequestMapping("/qbSuccess")
    public Object qbSuccess(HttpServletRequest request) {
        Map<String,Object> result = Maps.newHashMap();
        String uOrderId = null;
        uOrderId = request.getParameter("uorderid");
        if (StringUtils.isBlank(uOrderId)) {
            uOrderId = request.getParameter("orderId");
        }
        if (StringUtils.isNotBlank(uOrderId)) {
            String orderId = uOrderId.split("_")[0];
            this.remoteAlipayService.updateQBOrderSuccess(orderId);
        }
        result.put("error_code", 0);
        return result;
    }

    /**
     * 是否过期
     * @param timestamp 时间戳
     * @return true 没有过期; false 过期
     */
    private boolean isExpire(String timestamp) {

        Date date = null;
        try {
            date = new Date(Long.valueOf(timestamp));
        } catch (Exception e) {
            return false;
        }
        //5分钟失效
        return date.after(new Date(new Date().getTime() - 5 * 60 * 1000L));
    }
    
    /**
     * 获取签名
     * @param param 参数
     * @return
     */
    private String getSign(Map<String,Object> param){
    	StringBuilder sb = new StringBuilder();
    	sb.append(param.get("timestamp"));//时间戳
    	sb.append(param.get("prizeFlag"));//奖品标识
    	sb.append(param.get("orderId"));//订单号
    	sb.append(param.get("appKey"));//开发者信息
    	try {
			sb.append(appService.findAppByAppKey(param.get("appKey").toString()).getAppSecret());
		} catch (Exception e1) {
			log.warn("ex={}",e1.getMessage());
		}
    	try {
			return MD5.md5(sb.toString());
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			log.warn("虚拟商品充值签名失败 msg={}",e.getMessage(),e);
			return null;
		}
    }

    @RequestMapping("/third")
    public JSONObject third(@RequestParam Map<String,String> map){
        log.warn("模拟第三方更新金币接口，param={}", map.toString());
        JSONObject json = new JSONObject();
        try {
            if(!SignTool.signVerify(appService.findAppByAppKey(map.get("appKey").toString()).getAppSecret(), map)){

                json.put("status","fail");
                json.put("errorMessage","签名校验失败");
            }else{
                json.put("status","ok");
            }
        } catch (ExecutionException e) {
            log.warn("ex={}",e.getMessage());
        }
        json.put("orderId", map.get("orderId"));
        json.put("credits","1000");
        return json;
    }

    @RequestMapping("/sign")
    public String sign(String muId, Long credits, String appKey, String timestamp, String appSecret){
        Map<String,String> map = new HashMap<>();
        map.put("muId", muId);
        map.put("credits", credits.toString());
        map.put("appKey", appKey);
        map.put("timestamp", timestamp);
        map.put("appSecret", appSecret);
        return SignTool.sign(map);
    }
}
