package com.cyksj.service.register.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.EnvCommonService;
import com.cyksj.common.constant.TemplateEnum;
import com.cyksj.common.util.Jsons;
import com.cyksj.common.util.StringUtil;
import com.cyksj.dto.RedisKey;
import com.cyksj.mapper.ProxysMapper;
import com.cyksj.mapper.RegisterOrderDonMapper;
import com.cyksj.mapper.manage.coupon.CouponMapper;
import com.cyksj.model.dto.WxMpTemplateData;
import com.cyksj.model.dto.WxMpTemplateMessage;
import com.cyksj.model.entity.Coupon;
import com.cyksj.model.entity.CouponUser;
import com.cyksj.model.entity.RegisterOrderDon;
import com.cyksj.model.entity.SysConfig;
import com.cyksj.model.request.SpotifyRegisterReq;
import com.cyksj.model.response.ProxyInfo;
import com.cyksj.model.views.WxAppTemplateView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.mange.coupon.CouponCommonService;
import com.cyksj.service.register.SpotifyService;
import com.cyksj.service.sys.SysConfigService;
import com.cyksj.service.template.TemplateCommonService;
import com.cyksj.service.wechat.WeChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chan
 * @date 2022/11/7 1:54 PM
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SpotifyServiceImpl implements SpotifyService {

    private final ProxysMapper proxysMapper;

    private final RegisterOrderDonMapper registerOrderDonMapper;

    private final RedisService redisService;

    private final EnvCommonService envCommonService;

    private final WeChatService weChatService;

    private final CouponMapper couponMapper;

    private final CouponCommonService couponCommonService;

    private final SysConfigService sysConfigService;

    private final TemplateCommonService templateCommonService;

    private static final List<String> User_Agent_LIST =  List.of(
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
            "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
            "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
            "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
            "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
            "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
            "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
            "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
            "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10");


    @Override
    public synchronized void register(Long registerOrderId){
        log.info("spotify 注册 orderId:{}",registerOrderId);
        RegisterOrderDon registerOrderDon = registerOrderDonMapper.selectById(registerOrderId);

        SpotifyRegisterReq registerReq = new SpotifyRegisterReq();
        SpotifyRegisterReq.AccountDetails accountDetails = new SpotifyRegisterReq.AccountDetails();
        SpotifyRegisterReq.AccountDetails.EmailAndPasswordIdentifier emailAndPasswordIdentifier = new SpotifyRegisterReq.AccountDetails.EmailAndPasswordIdentifier();
        emailAndPasswordIdentifier.setEmail(registerOrderDon.getEmail());
        emailAndPasswordIdentifier.setPassword(registerOrderDon.getPassword());
        accountDetails.setEmail_and_password_identifier(emailAndPasswordIdentifier);
        accountDetails.setBirthdate(Optional.ofNullable(registerOrderDon.getBirthYear()).orElse("1989") + "-" + Optional.ofNullable(registerOrderDon.getBirthMonth()).orElse("10") + "-" + Optional.ofNullable(registerOrderDon.getBirthDay()).orElse("06"));
        accountDetails.setDisplay_name(emailAndPasswordIdentifier.getEmail());
        accountDetails.setGender(1);
        registerReq.setAccount_details(accountDetails);

        Map<String,String> map = new HashMap<>();
        map.put("User-Agent", User_Agent_LIST.get(RandomUtil.randomInt(User_Agent_LIST.size())));
        map.put( "authority","spclient.wg.spotify.com");
        map.put( "method","POST");
        map.put("Host","spclient.wg.spotify.com");
        map.put("Accept", "*/*");
        map.put( "path","/signup/public/v2/account/create");
        map.put( "Referer", "https://www.spotify.com/");
        map.put("Content-Type", "application/json; charset=utf-8");
        map.put("Origin", "https://www.spotify.com");
        map.put("Connection", "keep-alive");
        map.put("sec-ch-ua", "\"Not?A_Brand\";v=\"8\", \"Chromium\";v=\"108\", \"Google Chrome\";v=\"108\"");
        map.put("sec-ch-ua-mobile", "?0");
        map.put("sec-ch-ua-platform", "Windows");
        map.put("Sec-Fetch-Dest", "empty");
        map.put("Sec-Fetch-Mode", "cors");
        map.put("Sec-Fetch-Site", "same-site");
        map.put("referrer-policy", "strict-origin-when-cross-origin");
        CopyOnWriteArrayList<ProxyInfo> proxyInfos = (CopyOnWriteArrayList<ProxyInfo>) redisService.get(RedisKey.IP_LIST);
        if (proxyInfos == null || proxyInfos.size() == 0) {
            //String res = HttpUtil.get("http://api.proxy.ipidea.io/getProxyIp?num=30&return_type=json&lb=1&sb=0&flow=1&regions=&protocol=http");
            //JSONObject jsonObject = JSONUtil.parseObj(res);
            //JSONArray data = jsonObject.getJSONArray("data");
            //proxyInfos = new CopyOnWriteArrayList<>(data.toList(ProxyInfo.class));

            String result = HttpUtil.get("https://dvapi.doveproxy.net/cmapi.php?rq=distribute&user=1031494735&token=ckc1MUFURnk3bi80MXVxeUFTZUh0Zz09&auth=0&geo=ph&agreement=0&timeout=10&num=1&type_ip=1&repeat=0");
            log.info("付费ip 请求返回 res:{}",result);
            /*
             * {
             *   "errno": 200,
             *   "msg": "Success",
             *   "data": {
             *     "geo": "mx", //国家
             *     "ip": "47.253.12.97", //代理ip
             *     "port": 40076, //代理端口
             *     "d_ip": "201.162.169.86" //目标ip
             *     "timeout": 600 //有效时间（秒）
             *   }
             * }
             */
            JSONObject resObj = JSONUtil.parseObj(result);
            if (200 == resObj.getInt("errno")) {
                JSONObject data = resObj.getJSONObject("data");
                ProxyInfo proxyInfo = new ProxyInfo();
                proxyInfo.setPort(data.getInt("port"));
                proxyInfo.setIp(data.getStr("ip"));
                log.info("----------付费IP地址----------\n ip:{}",proxyInfo);
                proxyInfos = new CopyOnWriteArrayList<>();
                proxyInfos.add(proxyInfo);
            }else {
                log.error("----------获取 付费IP 错误 停止循环----------");
                return;
            }
        }
        AtomicInteger count =  new AtomicInteger(1);
        while (count.get() <= 3) {
            boolean flag = false;
            count.addAndGet(1);
            for (ProxyInfo proxyInfo : proxyInfos) {
                try {
                    log.info("执行：info:{}", proxyInfo);

                    Proxy proxy = new Proxy(Proxy.Type.SOCKS,
                            new InetSocketAddress(proxyInfo.getIp(), proxyInfo.getPort()));
                    //OkHttpClient client = new OkHttpClient().newBuilder().proxy(proxy).build();
                    //log.info("spotify request body :{}",JSONUtil.toJsonStr(registerReq));
                    //RequestBody requestBody = FormBody.create(JSONUtil.toJsonStr(registerReq),MediaType.parse("application/json; charset=utf-8"));
                    //
                    //Request request = new Request.Builder()
                    //        .url("https://spclient.wg.spotify.com/signup/public/v2/account/create")
                    //        .post(requestBody)
                    //        .headers(Headers.of(map))
                    //        .build();
                    //
                    //okhttp3.Response response = client.newCall(request).execute();
                    //ResponseBody body = response.body();
                    HttpRequest request = new HttpRequest("https://spclient.wg.spotify.com/signup/public/v2/account/create");
                    request.setProxy(proxy);
                    request.body(JSONUtil.toJsonStr(registerReq));
                    request.addHeaders(map);
                    request.setMethod(Method.POST);
                    request.setConnectionTimeout(15 * 1000);
                    request.setReadTimeout(15 * 1000);
                    String spotifyBody = request.execute().body();

                    log.info("spotify 返回body:{}", spotifyBody);
                    /*
                    {
                        "error":{
                            "error_details":{
                                "code":2,
                                "title":"请检查你的详细信息，然后再试一次。",
                                "body":"此电子邮件已关联至某个帐号。请登录你的帐号，或使用其他电子邮件注册。",
                                "already_exists":{

                                }
                            }
                        }
                    }
                     */
                    /*
                    {
                        "success": {
                            "username": "31naixo6v3uydhvcp63sya57ozae",
                            "login_token": "N7N9gHZ3QeG74yHWAx8hAw"
                        }
                    }
                     */
                    JSONObject resObj = JSONUtil.parseObj(spotifyBody);
                    log.info("spotify 返回:{}",resObj);
                    JSONObject error = resObj.getJSONObject("error");
                    if (error == null || error.isEmpty()) {
                        JSONObject success = resObj.getJSONObject("success");
                        if (StringUtils.isNotBlank(success.getStr("login_token")) || StringUtils.isNotBlank("username")) {
                            log.info("注册成功！");
                            registerOrderDon.setStatus(RegisterOrderDon.Status.complete);
                            registerOrderDonMapper.updateById(registerOrderDon);
                            //注册成功发放模板消息
                            spotifyTemplateMsg(registerOrderDon, String.format("%s%s", envCommonService.getDomain(), "yinhe/web/sign/list"), true);
                            //注册成功发放声破天优惠券
                            sendSpotifyCoupon(registerOrderDon);
                            flag = true;
                            break;
                        }else if(!resObj.getJSONObject("challenge").isEmpty()) {
                            log.info("spotify 注册 被监测出代理服务 。 删除该代理 ip:{}", proxyInfo.getIp());
                            proxyInfos.remove(proxyInfo);
                        }
                    }else {
                        JSONObject error_details = error.getJSONObject("error_details");
                        String errorMsg = error_details.getStr("body");
                        Integer code = error_details.getInt("code");
                        if (code.equals(4) || "你的设备似乎已连接至代理或 VPN 服务。请关闭此类服务，然后再试一次。".equals(errorMsg)) {
                            log.info("spotify 注册 被监测出代理服务 。 删除该代理 ip:{}", proxyInfo.getIp());
                            proxyInfos.remove(proxyInfo);
                            continue;
                        }
                        //{"error":{"error_details":{"code":1,"invalid_argument":{"field_errors":[{"code":6,"message":"你的密码安全强度太低。设置安全强度较高的密码。","field":"FIELD_PASSWORD"}]},"title":"请检查你的详细信息，然后再试一次。"}}}
                        //{"error":{"error_details":{"code":2,"title":"请检查你的详细信息，然后再试一次。","body":"此电子邮件已关联至某个帐号。请登录你的帐号，或使用其他电子邮件注册。","already_exists":{}}}}
                        if(code == 1 || error_details.getJSONObject("invalid_argument") != null){
                            JSONObject invalid_argument = error_details.getJSONObject("invalid_argument") ;
                            JSONArray field_errors = invalid_argument.getJSONArray("field_errors");
                            JSONObject errmsg = (JSONObject)field_errors.get(0);
                            registerOrderDon.setErrorMsg(errmsg.getStr("message"));
                            registerOrderDon.setStatus(RegisterOrderDon.Status.error);
                        }else {
                            registerOrderDon.setErrorMsg(error_details.getStr("body"));
                            registerOrderDon.setStatus(RegisterOrderDon.Status.error);
                        }
                        registerOrderDonMapper.updateById(registerOrderDon);

                        //注册失败发放模板消息
                        spotifyTemplateMsg(registerOrderDon, String.format("%s%s", envCommonService.getDomain(), "yinhe/web/sign/list"), false);
                        flag = true;
                        break;
                    }
                } catch (Exception e) {
                    proxyInfos.remove(proxyInfo);
                    log.error("错误 ip:{}", proxyInfo.getIp());
                    log.error("spotify 注册 error:{}", StringUtil.getErrorText(e));
                    break;
                }
            }

            if(flag){
                log.info("spotify 停止");
                break;
            }
        }

        redisService.set(RedisKey.IP_LIST,proxyInfos,360L);
    }

    private void sendSpotifyCoupon(RegisterOrderDon registerOrderDon) {
        //已经拥有声破天年费的不用发
        Integer exists = registerOrderDonMapper.isPaySpotifyYearTicket(registerOrderDon.getUserId());
        if (exists == null) {
            SysConfig spotify_register_success_cid = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey, "spotify_register_success_cid").last("limit 1"));
            if (spotify_register_success_cid != null && StrUtil.isNotBlank(spotify_register_success_cid.getSysValue())) {
                Long spotifyRegisterSucCid = Long.parseLong(spotify_register_success_cid.getSysValue());
                Coupon coupon = couponMapper.selectById(spotifyRegisterSucCid);
                if (coupon != null) {
                    couponCommonService.sendCouponToUser(registerOrderDon.getUserId(), spotifyRegisterSucCid, null, null, null, CouponUser.Channel.manual);
                }
            }
        }
    }

    private void spotifyTemplateMsg(RegisterOrderDon registerOrderDon, String url, Boolean isSuccess) throws Exception {
        if (!EnvCommonService.active.equals(envCommonService.getEnv())) {
            String openId = registerOrderDon.getOpenId();
            if (StrUtil.isNotBlank(openId)) {
                WxAppTemplateView wxAppTemplateView = templateCommonService.getWxAppByUserId(openId, TemplateEnum.SPOTIFY_TEMPLATE.getDesc());
                if (wxAppTemplateView != null) {
                    WxMpTemplateMessage templateMessage = new WxMpTemplateMessage()
                            .setToUser(openId)
                            .setTemplateId(wxAppTemplateView.getTemplateId())
                            .setUrl(url);
                    WxMpTemplateMessage.TemplateData data = templateMessage.getData();
                    data.setFirst(new WxMpTemplateData(isSuccess ? "Spotify账号已注册成功" : "Spotify账号注册失败，请修改后重新提交"));
                    data.setKeyword1(new WxMpTemplateData(registerOrderDon.getPhone()));
                    data.setKeyword2(new WxMpTemplateData(DateUtil.format(registerOrderDon.getCreatedTime(), "yyyy-MM-dd HH:mm:ss")));
                    weChatService.sendTemplateMessage(weChatService.getAccessToken(wxAppTemplateView.getAppId()), Jsons.toJson(templateMessage));
                }
            }
        }
    }

}
