package com.lightinit.hsdataplatform.controller;

import com.lightinit.hsdataplatform.common.OneTimePasswordAlgorithm;
import com.lightinit.hsdataplatform.common.SecureCardUtilsPro;
import com.lightinit.hsdataplatform.json.pojo.BindCardEntity;
import com.lightinit.hsdataplatform.json.pojo.CardJsonResult;
import com.lightinit.hsdataplatform.json.pojo.JsonResult;
import com.lightinit.hsdataplatform.entity.Securekey;
import com.lightinit.hsdataplatform.service.ISecureKeyService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Lantinit on 2018/1/31.
 */
@Controller
@RequestMapping("/token")
public class TokenController {
    @Autowired
    private ISecureKeyService secureKeyService;
    @Autowired
    private SecureCardUtilsPro secureCardUtilsPro;
    @ResponseBody
    @RequestMapping(value = "json/user/secret.action",method = RequestMethod.GET)
    public JsonResult print_json_user_secret(HttpSession session) {
        JsonResult result = new JsonResult();
        String []xAxis=new String[]{"A","B","C","D","E","F","G","H","J","K"};
        String []yAxis=new String[]{"1","2","3","4","5","6","7","8"};
        Random xRand = new Random();
        Random yRand = new Random();
        List<String> keyList=new ArrayList<String>();
        for (int i=0;i<4;i++) {
            keyList.add(xAxis[xRand.nextInt(10)]+yAxis[yRand.nextInt(8)]);
        }
        session.setAttribute("SECUREKEY_SESSION_KEY", String.join(":::",keyList));
        result.setStatus(1);
        result.setMessage("请输入对应的密钥："+String.join("、",keyList));
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "json/user/secret/key.action",method = RequestMethod.GET)
    public JsonResult print_json_user_secret_key(HttpSession session) {
        JsonResult result = new JsonResult();
        String []xAxis=new String[]{"A","B","C","D","E","F","G","H","J","K"};
        String []yAxis=new String[]{"1","2","3","4","5","6","7","8"};
        Random xRand = new Random();
        Random yRand = new Random();
        List<String> keyList=new ArrayList<String>();
        for (int i=0;i<4;i++) {
            keyList.add(xAxis[xRand.nextInt(10)]+yAxis[yRand.nextInt(8)]);
        }
        session.setAttribute("SECUREKEY_SESSION_KEY", String.join(":::",keyList));
        result.setStatus(1);
        result.setMessage(String.join(":",keyList));
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "json/user/secret/verification.action",method = RequestMethod.GET)
    public JsonResult print_json_user_secret_verification(HttpSession session, @RequestParam(defaultValue = "")String token) {
        JsonResult result = new JsonResult();
        if (StringUtils.isEmpty(token)) {
            result.setStatus(-1);
            result.setMessage("非法Token！");
            return result;
        }
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser == null) {
            result.setStatus(-1);
            result.setMessage("当前用户不存在！");
            return result;
        }
        String capText = session.getAttribute("SECUREKEY_SESSION_KEY") != null ? session.getAttribute("SECUREKEY_SESSION_KEY").toString() : "";
        if (StringUtils.isEmpty(capText)) {
            result.setStatus(-1);
            result.setMessage("系统异常！");
            return result;
        }
        Securekey securekey = secureKeyService.QueryOne(currentUser.getPrincipal().toString());
        if (securekey == null) {
            result.setStatus(-1);
            result.setMessage("授权失败！");
            return result;
        }
        String realToken = "";
        String[] TokenArray = capText.split(":::");
        for (String item : TokenArray) {
            String secretStr = item.substring(1) + ":::" + securekey.getSecurekey() + ":::" + item.substring(0, 1);
            try {
                realToken += OneTimePasswordAlgorithm.generateOTP(secretStr.getBytes(), 0, 2, false, -1);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
        }
        if (realToken.equalsIgnoreCase(token) == false) {
            result.setStatus(-1);
            result.setMessage("授权失败！");
            return result;
        } else {
            session.removeAttribute("SECUREKEY_SESSION_KEY");
            result.setStatus(1);
            result.setMessage("授权成功！");
            return result;
        }
    }


    @ResponseBody
    @RequestMapping(value = "json/secret/make/card.action",method = RequestMethod.GET)
    public CardJsonResult print_json_user_secret_make() {
        CardJsonResult result = new CardJsonResult();
        try {
            SimpleDateFormat syncDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date syncDate= syncDateFormat.parse(syncDateFormat.format(new Date()));
                result.setSynctime(syncDate.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyMMddHHmmssSSS");
            String[][] CardSecret = new String[10][8];
            String SerialNo = "1"+ org.apache.commons.lang3.StringUtils.leftPad(simpleDateFormat.format(new Date()),18,"0");
            String[] xAxis = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "J", "K"};
            String[] yAxis = new String[]{"1", "2", "3", "4", "5", "6", "7", "8"};
            for (int j = 0; j < 8; j++) {
                for (int i = 0; i < 10; i++) {
                    String secretStr = yAxis[j] + ":::"+SerialNo+":::"+result.getSynctime()+":::" + xAxis[i];
                    CardSecret[i][j] = OneTimePasswordAlgorithm.generateOTP(secretStr.getBytes(), 0, 2, false, -1);
                }
            }
            result.setSecretkeys(CardSecret);
            result.setSerialno(SerialNo);
            result.setStatus(1);
            result.setMessage("操作成功");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            result.setStatus(0);
            result.setMessage("服务异常");
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            result.setStatus(0);
            result.setMessage("服务异常");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "json/secret/bind/card.action",method = RequestMethod.POST)
    public JsonResult print_json_user_secret_bind(HttpSession session,@RequestBody BindCardEntity item) {
        JsonResult result = new JsonResult();
        try {
            if(secureCardUtilsPro.verification(session,item.getToken(),item.getCardno(),item.getSynctime())==false){
                result.setStatus(0);
                result.setMessage("服务异常");
                return result;
            }
            SimpleDateFormat syncDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date syncDate=syncDateFormat.parse(syncDateFormat.format(item.getSynctime()));
                Securekey record=secureKeyService.QueryOne(item.getUsername());
                if(record==null){
                    record=new Securekey();
                }
                record.setBinddatetime(new Date());
                record.setCyclestep(0);
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(new Date());
                rightNow.add(Calendar.YEAR,1);
                record.setExpiresdatetime(rightNow.getTime());
                record.setSecurekey(item.getCardno());
                record.setSyncdatetime(syncDate);
                record.setSecurekeytype(0);
                record.setUsername(item.getUsername());
                if(record.getSecurekeyid()<=0) {
                    if (secureKeyService.Insert(record)) {
                        result.setStatus(1);
                        result.setMessage("操作成功");
                    } else {
                        result.setStatus(1);
                        result.setMessage("操作成功");
                    }
                }else{
                    if (secureKeyService.Update(record)) {
                        result.setStatus(1);
                        result.setMessage("操作成功");
                    } else {
                        result.setStatus(1);
                        result.setMessage("操作成功");
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            result.setStatus(1);
            result.setMessage("操作成功");
        }catch (Exception e) {
            e.printStackTrace();
            result.setStatus(0);
            result.setMessage("服务异常");
        }
        return result;
    }
}
