package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.Base64Util;
import com.hai.common.security.VerifyCode;
import com.hai.common.security.VerifyCodeStorage;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.model.MtSmsMessageModel;
import com.hai.model.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


@Controller
@Api(value = "华为云短信发送")
@RequestMapping(value = "/sendSms")
public class SendSmsController {

    private static final String[] HEX_DIGITS = {"0" ,"1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

    private static Logger log = LoggerFactory.getLogger(CmsContentController.class);

    //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";


    @Resource
    private RedisUtil redisUtil;

    @RequestMapping(value = "/sendSmsCode", method = RequestMethod.GET)
    @ApiOperation(value = "发送短信验证码")
    @ResponseBody
    public ResponseData sendSmsCode(@RequestParam(value = "phone", required = true) String phone) {
        try {

            // ip：port根据实际情况填写
            String url = "https://139.9.32.119:18312/common/sms/sendTemplateMessage";
            String smsTemplateId = "SMS_21092300061";
            Map<String, String> templateParas = new HashMap<String, String>();
            String account = "760887"; //实际账号
            String password = "Z.o'&mO%7_?5M,Br"; //实际密码

            VerifyCode verifyCode = VerifyCodeStorage.getDate(phone);
            String smsCode;
            if (verifyCode != null){
                smsCode = verifyCode.getObject();
            }else{
                // 生成随机6位验证码
                smsCode = String.valueOf(new Random().nextInt(899999) + 100000);
            }

             templateParas.put("code" , smsCode);

            Map<String, Object> map = new HashMap<String, Object>();

            List<MtSmsMessageModel> requestLists = new ArrayList<MtSmsMessageModel>();
            MtSmsMessageModel mtSmsMessage = new MtSmsMessageModel();
            List<String> mobiles = new ArrayList<String>();
            mobiles.add(phone);
            mtSmsMessage.setMobiles(mobiles);
            mtSmsMessage.setTemplateId(smsTemplateId);
            mtSmsMessage.setTemplateParas(templateParas);

            requestLists.add(mtSmsMessage);

            map.put("account" , account);
            map.put("password" , password);
            map.put("requestLists" , requestLists);


            Map<String,Object> header = new LinkedHashMap<>();
            header.put(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE);

            JSONObject object = HttpsUtils.doPostSendSms(url, map);
            String code = object.getString("code");
            if (code.equals("000000")) {
                redisUtil.set(phone,smsCode, 60*10);
                return ResponseMsgUtil.success("发送成功");
            }
            return ResponseMsgUtil.success(object);
        } catch (Exception e) {
            log.error("CmsContentController --> sendSmsCode() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    public String encodeBySHA256(String str) {
        try{
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
            return getFormattedText(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    private String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j=0;j<len;j++){
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
}
