package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.IOUtil;
import com.hai.common.pay.util.XmlUtil;
import com.hai.common.utils.*;
import com.hai.config.TelConfig;
import com.hai.entity.*;
import com.hai.enum_type.GoodsType;
import com.hai.enum_type.PayType;
import com.hai.model.ResponseData;
import com.hai.service.HighOrderService;
import com.hai.service.HighUserService;
import com.hai.service.TelApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.regex.Pattern;

@RestController
@RequestMapping(value = "/telApi")
@Api(value = "电话费充值数据接口")
public class TelApiController {
    private static Logger log = LoggerFactory.getLogger(TelApiController.class);

    @Resource
    private TelApiService telApiService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighUserService highUserService;

    /**
     * 中国电信号码格式验证 手机段： 133,153,180,181,189,177,1700,173,199
     **/
    private static final String CHINA_TELECOM_PATTERN = "(^1(33|53|77|73|99|8[019])\\d{8}$)|(^1700\\d{7}$)";

    /**
     * 中国联通号码格式验证 手机段：130,131,132,155,156,185,186,145,176,1709
     **/
    private static final String CHINA_UNICOM_PATTERN = "(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";

    /**
     * 中国移动号码格式验证
     * 手机段：134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     **/
    private static final String CHINA_MOBILE_PATTERN = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";


    @RequestMapping(value = "/telPay", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "充值话费")
    public ResponseData certification(@RequestBody HighTelOrder highTelOrder) {
        try {

            if (StringUtils.isBlank(highTelOrder.getTel()) ||
                    highTelOrder.getPrice() == null
            ) {
                log.error("telApi -> telPay() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            int random = (int) (1 + Math.random() * (999999 - 100000 + 1));

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

            String mchid = "HFb44f8_10004";
            String tel = highTelOrder.getTel();
            String orderid = "HF" + DateUtil.date2String(new Date(), "yyyyMMddHHmmss") + IDGenerator.nextId(5);
            BigDecimal price = BigDecimal.valueOf(highTelOrder.getPrice());
            String teltype = isChinaMobilePhoneNum(highTelOrder.getTel()).toString();
            int timeout = 300;
            String notify = "notify";
            String time = String.valueOf(new Date().getTime());
            String APIKEY = "483e5a68fe9bda2f7ab3f2665a0006cd";
            String sign = mchid + tel + price + orderid + teltype + notify + time + random + APIKEY;

            String param = "mchid=" + mchid +
                    "&tel=" + tel +
                    "&orderid=" + orderid +
                    "&price=" + price +
                    "&teltype=" + teltype +
                    "&notify=" + notify +
                    "&time=" + time +
                    "&rand=" + random +
                    "&sign=" + MD5Util.encode(sign.getBytes());
            map.put("from", param);

            JSONObject object = HttpsUtils.doSmsPost("http://45.130.154.125:9998/api/telpay", map, new HashMap<>());
            return ResponseMsgUtil.success(object);
        } catch (Exception e) {
            log.error("HighMerchantController -> insertMerchant() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    @ApiOperation(value = "话费充值 -> 异步回调")
    public void wechatNotify(HttpServletRequest request, HttpServletResponse response) {
        try {

            log.info("话费充值 -> 异步通知：处理开始");

            String notifyXml = null;    // 话费充值系统发送的数据（<![CDATA[product_001]]>格式）
            notifyXml = IOUtil.inputStreamToString(request.getInputStream(), "UTF-8");

            log.info("话费充值系统发送的数据：" + notifyXml);
            SortedMap<String, String> map = XmlUtil.parseXmlToTreeMap(notifyXml, "UTF-8");

//            resXml = notifyService.wechatNotify(map);
//
//
//            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
//            out.write(resXml.getBytes());
//            out.flush();
//            out.close();
            log.info("话费充值 -> 异步通知：处理完成");
        } catch (Exception e) {
            log.error("WechatPayController --> wechatNotify() error!", e);
        }
    }

    /**
     * 查询电话属于哪个运营商
     *
     * @param tel 手机号码
     * @return 0：不属于任何一个运营商，0:移动，1：联通，2：电信 99: 什么都不是
     */
    public Integer isChinaMobilePhoneNum(String tel) {
        boolean b1 = tel != null && !tel.trim().equals("") && match(CHINA_MOBILE_PATTERN, tel);
        if (b1) {
            return 0;
        }
        b1 = tel != null && !tel.trim().equals("") && match(CHINA_UNICOM_PATTERN, tel);
        if (b1) {
            return 1;
        }
        b1 = tel != null && !tel.trim().equals("") && match(CHINA_TELECOM_PATTERN, tel);
        if (b1) {
            return 2;
        }
        return 99;
    }

    /**
     * 匹配函数
     *
     * @param regex
     * @param tel
     * @return
     */
    private static boolean match(String regex, String tel) {
        return Pattern.matches(regex, tel);
    }


    @RequestMapping(value = "/getMemberGoods", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取渠道商获取关联商品")
    public ResponseData getMemberGoods() {
        try {

            JSONObject data = TelConfig.getMemberGoods();

            return ResponseMsgUtil.success(data);
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getTest", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测试接口")
    public ResponseData getTest() {
        try {


            return ResponseMsgUtil.success("1");
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

}
