package com.chinacreator.video.restful.controller;

import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.validate.IpValidate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class GetCapKeyController {

    @Autowired
    private IpValidate ipValidate;

    @Value("${capKey.iosId}")
    private String iosId;
    @Value("${capKey.iosPwd}")
    private String iosPwd;

    @Value("${capKey.Android}")
    private String Android;
    @Value("${capKey.AndroidPwd}")
    private String AndroidPwd;

    @PostMapping("/getCapKey")
    public Map<String,String> getCapKey(@RequestBody OrderInfo orderInfo)  {

        String resultCode="0";
        String errorInfo="";
        Map<String,String> respMap=new HashMap<>();
        try {
            orderInfo.setInvokeface("getCapKey");
            //ip验证
            ipValidate.volidate(orderInfo,"1");
            int num= (int) (Math.random()*100000);//随机数然后取整数
            if (num<10000){
                num+=10000;
            }
            long timestamp = System.currentTimeMillis();
            String authNo= String.valueOf(timestamp+num);
            String clientId="";
            String clientSecret="";
            if ("1".equals(orderInfo.getType())){
             clientId=iosId;
             clientSecret= MD5.MD5Encode(iosPwd+authNo);
            }else {
                clientId=Android;
                clientSecret= MD5.MD5Encode(AndroidPwd+authNo);
            }
            respMap.put("clientId",clientId);
            respMap.put("authNo",authNo);
            respMap.put("clientSecret",clientSecret);
        } catch (Exception e) {
            if (e instanceof BussinessException){
                resultCode=((BussinessException) e).getCode();
            }else {
                resultCode="8000";
            }
            errorInfo=e.getMessage();
            e.printStackTrace();
        }
        respMap.put("resultCode",resultCode);
        respMap.put("errorInfo",errorInfo);
        return respMap;
    }

    public static void main(String[] args) {
        int num= (int) (Math.random()*100000);//随机数然后取整数
        if (num<10000){
            num+=10000;
        }
        System.out.println(num);
    }
}
