package com.winsun.sendSms;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.WinsunCoreServiceApplication;
import com.winsun.base.AppApplicationBaseIT;
import com.winsun.bean.AttributeList;
import com.winsun.bean.Order;
import com.winsun.bean.School;

import com.winsun.mapper.OrderCardAddressMapper;
import com.winsun.mapper.OrderMapper;
import com.winsun.mapper.SchoolMapper;

import com.winsun.outSideSystem.IntelligenceSendOrders;
import com.winsun.utils.MD5Util;
import com.winsun.utils.RSAUtils;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@SpringBootTest(classes = WinsunCoreServiceApplication.class)
@RunWith(SpringRunner.class)
@ActiveProfiles("local")
public class sendSms {
    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private OrderCardAddressMapper orderCardAddressMapper;

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    private IntelligenceSendOrders intelligenceSendOrders;

    final static String publicKey =
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAok8DnvM2OBwtzNoJb4nA" +
                    "jn4lgCkSxLyRw5lLiUfsi+40h00CGAC1arvbinTTbtrSnm4YDYlaJwveiOeDKdk0" +
                    "f2Yglb/8loEbNTqb1OqNxUeM1wYLRBXvAkkZ5fZllajWzFMkoNU/JQ4+T8sMATxm" +
                    "1d1XRcgM6zlgVwX6siDoLZ5Dm23CTS7SXhyMLtS9cgLefHcOckPQyXoB/IJqb0K1" +
                    "P0Sk0PE1OSRzpsI9JVzhsSW164fwYpxEbygj9O9JAmAszixwItt2j5zLJ6zRnK3R" +
                    "OrcAVMN/vpXTN2dCLGZXQrsTK9sAWASzIWTiQRzmnwxsQY7y4u2h+k41n8Z5tw03" +
                    "wwIDAQAB";

    @Test
    public void sendSms() throws Exception {

        String id = "33f76a5984a4";
        Order orderData = orderMapper.selectById(id);
        String hehuoren_id = orderData.getHehuorenId();
        String business_number = orderData.getBusinessNumber();
        String business_iccid = orderData.getBusinessIccid();
        Map<String, Object> partnerById = orderMapper.findPartnerById(hehuoren_id);
        Map<String, String> schoolMap = schoolMapper.selectByHeHuorenId(hehuoren_id);
        Map<String, Object> map1 = new HashMap<>();

        int ysm = Integer.parseInt(String.valueOf(partnerById.get("ysm")));
        Map<String, Object> ysmById = orderMapper.findYsmById(ysm);
        map1.put("ysmUser", ysmById.get("user_name"));
        map1.put("sign", ysmById.get("sign"));

        map1.put("lzgh", schoolMap.get("lzgh"));
        map1.put("lzUser", schoolMap.get("lz_user"));

        map1.put("lzgh", "44100621");
        map1.put("lzUser", "黄友健");

        map1.put("idCardUrl1", orderData.getIdCardz().replace("manager", "app"));
        map1.put("idCardUrl2", orderData.getIdCardf().replace("manager", "app"));
        map1.put("idCardUrl3", orderData.getIdCardzs().replace("manager", "app"));
        map1.put("cardType", orderData.getKapin());

        if ("49".equals(orderData.getPackageId())) {
            map1.put("userName", orderData.getParentName());
            map1.put("idCardUrl4", orderData.getIdCardzs().replace("manager", "app"));
        } else {
            map1.put("userName", orderData.getCustomerName());
            map1.put("idCardUrl4", orderData.getStudenCard().replace("manager", "app"));
        }
        map1.put("linkPhone", orderData.getContactNumber());
        map1.put("idCard", orderData.getIdCard());
        map1.put("orderPhone", business_number);
        map1.put("iccId", business_iccid);

        String site = orderData.getSite();
        String[] split = site.split(" ");


        map1.put("sheng", split[0]);
        map1.put("shi", split[1]);
        map1.put("xian", split[2]);


        map1.put("address", orderData.getAddress());

        String result = sendOrder(map1);
        System.out.println(result);
    }

    public String sendOrder(Map<String, Object> map) {

        kong.unirest.HttpResponse<String> str = null;

        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String timeStr = simpleDateFormat.format(new Date());
            String cardType = (String) map.get("cardType");

            if (cardType.contains("大王卡")) {
                map.put("productId", "483");
                map.put("salesId", "1185");
            } else if (cardType.contains("天翼学生证")) {
                map.put("productId", "1327");
                map.put("salesId", "4453");
            } else {
                map.put("productId", "727");
                map.put("salesId", "2137");
            }

            map.put("timeStr", timeStr);
            map.put("orderNum", "XY" + timeStr);
            map.put("imgUrl1", (String) map.get("idCardUrl1"));
            map.put("imgUrl2", (String) map.get("idCardUrl2"));
            map.put("imgUrl3", (String) map.get("idCardUrl3"));
            map.put("imgUrl4", (String) map.get("idCardUrl4"));
            str = sendAitransOrder2(map, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str.getBody();
    }

    // 保存卡品认证信息
    public kong.unirest.HttpResponse<String> sendAitransOrder2(Map<String, Object> map, int count) throws Exception {
        log.info("移动下单前已有参数：" + JSONObject.fromObject(map).toString());
        Map<String, String> return_data = new HashMap<>();
        return_data.put("code", "");
        return_data.put("route", "提交下单"); //[提交下单] [订单保存] [提交审核] 默认为提交下单
        return_data.put("微信openId", "");
        return_data.put("微信appId", "");
        map.put("return_data", return_data);

        String cardAddress = orderCardAddressMapper.selectByOrderId(map.get("order_id"));

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

        Map<String, Object> attachment = new HashMap<>(); // 附件
        attachment.put("身份证照1", map.get("imgUrl1"));
        attachment.put("身份证照2", map.get("imgUrl2"));
        attachment.put("身份证照3", map.get("imgUrl3"));
        attachment.put("身份证照4", map.get("imgUrl4"));
        order_data.put("附件", attachment);


        order_data.put("代理商账号", "hyoujian");
        order_data.put("使用人姓名", "黄友健");
        order_data.put("使用人证件号", "440802199006080830");

        Map<String, Object> customerInformation = new HashMap<>(); //客户信息
        customerInformation.put("联系人", (String) map.get("userName"));
        customerInformation.put("客户证件号码", (String) map.get("idCard"));
        customerInformation.put("客户证件姓名", (String) map.get("userName"));
        customerInformation.put("联系电话", (String) map.get("linkPhone"));
        customerInformation.put("客户证件地址", cardAddress);
        customerInformation.put("客户证件类型", "身份证");
        customerInformation.put("通讯地址", (String) map.get("address"));
        order_data.put("客户信息", customerInformation);


        order_data.put("订单来源单号", (String) map.get("orderNum")); // 订单来源单号，必填； 与订单来源对应，用于业务上记录订单的来源订单编号
        order_data.put("订单备注", "");
        order_data.put("付费类型", "预付费"); //预付费、后付费、其他  选填

        Map<String, Object> packageInformation = new HashMap<>();   //揽装信息
        packageInformation.put("揽装姓名", map.get("lzUser"));
        packageInformation.put("揽装工号", map.get("lzgh"));
        order_data.put("揽装信息", packageInformation);

        HashMap<String, Object> invoiceInformation = new HashMap<>();   //发票信息
        invoiceInformation.put("发票抬头", ""); //若发票投递方式为不需要，可以不填值，但必须有参数
        invoiceInformation.put("发票投递方式", "不需要");    // 必填 一次性发票，分月发票，不需要
        invoiceInformation.put("电子邮箱", ""); //若发票投递方式为不需要，可以不填值，但必须有参数
        order_data.put("发票信息", invoiceInformation);

        order_data.put("接口下单账号", "xiaoyuan");  //接口下单账号

        HashMap<String, Object> orderingProducts = new HashMap<>();  //订购产品
        //orderingProducts.put("产品SKU", "");
        orderingProducts.put("产品名称", map.get("cardType"));
        //orderingProducts.put("受理内容", "");
        orderingProducts.put("付费类型", "预付费");

        // 属性列表
        AttributeList userCategory = new AttributeList();
        userCategory.setName("用户类别");
        userCategory.setValue("学生");

        AttributeList studentID = new AttributeList();
        studentID.setName("学生证号");
        studentID.setValue((String) map.get("idCard"));

        AttributeList userType = new AttributeList();
        userType.setName("用户类型");
        userType.setValue((String) map.get("cardType"));

        AttributeList[] attributeList = new AttributeList[]{userCategory, studentID, userType};  //属性列表
        orderingProducts.put("属性列表", attributeList);
        order_data.put("订购产品", orderingProducts);

        Map<Object, Object> logisticsInformation = new HashMap<>();     //物流信息
        logisticsInformation.put("受理类型", "不受理");
        logisticsInformation.put("发货类型", "代理商自行发货");

        order_data.put("业务类型", "移动业务");  //业务类型
        //order_data.put("业务类型", "单宽业务");  //业务类型
        //order_data.put("业务类型", "预付费礼包业务");  //业务类型
        order_data.put("办理类型", "新装主卡");  //业务类型

        List<Map<String, Object>> mobileAccessList = new ArrayList<>();    //移动接入
        Map<String, Object> mobileAccess = new HashMap<>();
        mobileAccess.put("订购类型", "新装");
        mobileAccess.put("UIM实物串号", map.get("iccId"));
        mobileAccess.put("号码类型", "主卡");
        mobileAccess.put("移动接入号", map.get("orderPhone"));
        mobileAccessList.add(mobileAccess);
        order_data.put("移动接入", mobileAccessList);

        Map<String, Object> realNameInformation = new HashMap<>();      //实名信息
        realNameInformation.put("姓名", "主卡");
        realNameInformation.put("身份证号", map.get("idCard"));
        realNameInformation.put("ICCID", map.get("iccId"));
        realNameInformation.put("证件地址", cardAddress);
        order_data.put("实名信息", realNameInformation);

        Map<String, Object> logistics = new HashMap<>();     //物流信息
        logistics.put("发货类型", "代理商自行发货");
        order_data.put("物流信息", logistics);


        Map<String, Object> map1 = new HashMap<>();
        map1.put("order_data", order_data);
        String order_dataJSON = com.alibaba.fastjson.JSONObject.toJSONString(map1);


        // 获得md5串
        String sign = MD5Util.MD5Encode(order_dataJSON, "Utf-8");
        // 获得小写md5串
        sign = sign.toLowerCase();
        System.out.println(sign);
        // RSA加密
        byte[] encodedData = RSAUtils.encryptByPublicKey(sign, publicKey);
        sign = (new BASE64Encoder()).encodeBuffer(encodedData);
        System.out.println("签名：" + sign);
        //去除换行
        sign = sign.replaceAll("\\r|\\n", "");
        System.out.println("签名2  ：" + sign);
        log.info("移动下单接口中的携带的签名：" + sign);

        kong.unirest.HttpResponse<String> responese = null;
        try {
            log.info("提交参数:" + order_dataJSON);
            com.winsun.constant.Constant.trustEveryone();
            //responese = Unirest.post("http://132.97.20.21:8080/generate")
            responese = Unirest.post("https://applet.mini189.cn/prod/generate")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("X-Sign", sign)
                    .body(order_dataJSON)
                    .asString();
            System.out.println(responese.getStatus());
            System.out.println(responese.getParsingError());
            log.info("移动下单接口，返回信息:" + responese.getBody());
        } catch (ResourceAccessException e) {
            count++;
            if (count < 20) {
                responese = sendAitransOrder2(map, count);
            } else {
                log.error("单宽带(预付费、移动、融合、续约、增值)下单接口异常尝试20次失误。请检查接口");
            }
        } catch (Exception e) {
            log.error("[HTTP] [CREATE_ORDER] 预付费下单接口异常");
            e.printStackTrace();
        }

        return responese;
    }

    @Test
    public void send() throws Exception {
        System.out.println(intelligenceSendOrders.queryStatus("220210115950awrtwart"));
    }
}
