package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.VerifyCode;
import com.hai.common.security.VerifyCodeStorage;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.MessageConfig;
import com.hai.entity.ApiMerchants;
import com.hai.entity.BsOrganization;
import com.hai.model.MtSmsMessageModel;
import com.hai.model.ResponseData;
import com.hai.service.ApiMerchantsService;
import com.hai.service.BsCompanyService;
import com.hai.service.BsOrganizationService;
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 javax.net.ssl.*;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
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);

    @Resource
    private MessageConfig messageConfig;

    @Resource
    private ApiMerchantsService apiMerchantsService;

    /**
     * 设置不验证主机
     */
    private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private BsOrganizationService organizationService;

    @RequestMapping(value = "/sendRechargeSmsCode", method = RequestMethod.GET)
    @ApiOperation(value = "发送充值短信验证码")
    @ResponseBody
    public ResponseData sendRechargeSmsCode(@RequestParam(value = "phone", required = true) String phone,
                                            @RequestParam(value = "orgId", required = true) Long orgId,
                                            @RequestParam(value = "price", required = true) BigDecimal price) {
        try {
            // 查询部门信息
            BsOrganization organization = organizationService.findById(orgId);
            if (organization == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到部门信息");
            }

            VerifyCode verifyCode = VerifyCodeStorage.getDate(phone);
            String smsCode = String.valueOf(new Random().nextInt(899999) + 100000);

            // ip：port根据实际情况填写
            String url = "https://139.9.32.119:18312/common/sms/sendTemplateMessage";
            String msisdn = phone;
            String smsTemplateId = "SMS_22041400005";
            Map<String, String> templateParas = new HashMap<String, String>();
            templateParas.put("name",  organization.getName());
            templateParas.put("price", "￥" + price.toString());
            templateParas.put("code", smsCode);
            String account = "760887"; //实际账号
            String password = "Z.o'&mO%7_?5M,Br"; //实际密码

            // If the request body does not contain the signature name, set signature to null.
            Map<String, Object> body = buildRequestBody(msisdn, smsTemplateId, templateParas, account, password);
            if (null == body || body.isEmpty()) {
                return ResponseMsgUtil.success("");
            }

            HttpsURLConnection connection = null;
            InputStream is = null;
            BufferedReader br = null;
            trustAllHttpsCertificates();
            try {
                URL realUrl = new URL(url);
                connection = (HttpsURLConnection) realUrl.openConnection();
                connection.setHostnameVerifier(DO_NOT_VERIFY);
                connection.setDoInput(true); // 设置可输入
                connection.setDoOutput(true); // 设置该连接是可以输出的
                connection.setRequestMethod("POST"); // 设置请求方式
                connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                // connection.connect();
                ObjectMapper objectMapper = new ObjectMapper();
                PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
                pw.write(objectMapper.writeValueAsString(body));
                pw.flush();
                pw.close();

                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                int status = connection.getResponseCode();
                if (200 == status) { // 200
                    is = connection.getInputStream();
                } else { // 400/401
                    is = connection.getErrorStream();
                }
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line = null;
                StringBuilder result = new StringBuilder();
                while ((line = br.readLine()) != null) { // 读取数据
                    result.append(line + "");
                }
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != is) {
                        is.close();
                    }
                    if (null != br) {
                        br.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            redisUtil.set("COMPANY_AMOUNT_RECHARGE_SMS_CODE",smsCode, 60*5);
            return ResponseMsgUtil.success("发送成功");

        } catch (Exception e) {
            log.error("CmsContentController --> sendSmsCode() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    // msisdn, smsTemplateId, paramValues, countryID
    public static Map<String, Object> buildRequestBody(String msisdn, String smsTemplateId,
                                                       Map<String, String> paramValues, String accout, String passward) {
        if (null == msisdn || null == smsTemplateId || null == accout || null == passward) {
            System.out.println(
                    "buildRequestBody(): mobiles, templateId or templateParas or account or password is null.");
            return null;
        }


        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(msisdn);
        mtSmsMessage.setMobiles(mobiles);
        mtSmsMessage.setTemplateId(smsTemplateId);
        mtSmsMessage.setTemplateParas(paramValues);
        mtSmsMessage.setSignature("【嗨森逛】");
        requestLists.add(mtSmsMessage);
        map.put("account", accout);
        map.put("password", passward);
        map.put("requestLists", requestLists);
        return map;
    }


    static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return;
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return;
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }
        };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    @RequestMapping(value = "/sendRechargeSmsCodeByMchId", method = RequestMethod.GET)
    @ApiOperation(value = "发送充值短信验证码")
    @ResponseBody
    public ResponseData sendRechargeSmsCodeByMchId(@RequestParam(value = "phone", required = true) String phone,
                                            @RequestParam(value = "merchantId", required = true) Long merchantId,
                                            @RequestParam(value = "price", required = true) BigDecimal price) {
        try {
            // 查询部门信息
            ApiMerchants apiMerchants = apiMerchantsService.findById(merchantId);
            if (apiMerchants == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户信息");
            }

            String smsCode = String.valueOf(new Random().nextInt(899999) + 100000);

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

            // If the request body does not contain the signature name, set signature to null.
            Map<String, Object> body = buildRequestBody(phone, smsTemplateId, templateParas, account, password);
            if (null == body || body.isEmpty()) {
                return ResponseMsgUtil.success("");
            }

            HttpsURLConnection connection = null;
            InputStream is = null;
            BufferedReader br = null;
            trustAllHttpsCertificates();
            try {
                URL realUrl = new URL(url);
                connection = (HttpsURLConnection) realUrl.openConnection();
                connection.setHostnameVerifier(DO_NOT_VERIFY);
                connection.setDoInput(true); // 设置可输入
                connection.setDoOutput(true); // 设置该连接是可以输出的
                connection.setRequestMethod("POST"); // 设置请求方式
                connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                // connection.connect();
                ObjectMapper objectMapper = new ObjectMapper();
                PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
                pw.write(objectMapper.writeValueAsString(body));
                pw.flush();
                pw.close();

                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                int status = connection.getResponseCode();
                if (200 == status) { // 200
                    is = connection.getInputStream();
                } else { // 400/401
                    is = connection.getErrorStream();
                }
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line = null;
                StringBuilder result = new StringBuilder();
                while ((line = br.readLine()) != null) { // 读取数据
                    result.append(line + "");
                }
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != is) {
                        is.close();
                    }
                    if (null != br) {
                        br.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            redisUtil.set("COMPANY_AMOUNT_RECHARGE_SMS_CODE",smsCode, 60*5);
            return ResponseMsgUtil.success("发送成功");

        } catch (Exception e) {
            log.error("CmsContentController --> sendSmsCode() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
