package com.bonus.sgzb.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import com.bonus.sgzb.auth.form.*;
import com.bonus.sgzb.auth.service.NwRegisterService;
import com.bonus.sgzb.auth.utils.HttpUtils;
import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.core.exception.base.BaseException;
import com.bonus.sgzb.common.core.utils.ip.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author: LYJ
 * @date: 2021/8/14 18:47
 * @description: 注册实现类
 */
@Service
@Slf4j
public class NwRegisterServiceImpl implements NwRegisterService {

    @Override
    public String registersNew(HttpServletRequest request, RegisterForms registerForms) {
        log.info("统一个人手机注册 registersForPersonal方法 入参 request:{}, registerForms:{}", request, JSON.toJSONString(registerForms));
        //校验请求参数
        this.checkRequestParam(request, registerForms);
        Integer loginModeType = registerForms.getLoginModeType();
        NwApp nwApp = new NwApp();
        if (loginModeType == NwLoginConstants.ONE) {
            nwApp.setCode(1);
            nwApp.setAppId(NwLoginConstants.appId);
            nwApp.setAppsecret(NwLoginConstants.appsecret);
        } else if (loginModeType == NwLoginConstants.TWO) {
            nwApp.setCode(2);
            nwApp.setAppId(NwLoginConstants.h5AppId);
            nwApp.setAppsecret(NwLoginConstants.h5Appsecret);
        } else if (loginModeType == NwLoginConstants.THREE) {
            nwApp.setCode(3);
            nwApp.setAppId(NwLoginConstants.wechatAppId);
            nwApp.setAppsecret(NwLoginConstants.wechatAppsecret);
        } else if (loginModeType == NwLoginConstants.FOUR) {
            nwApp.setCode(4);
            nwApp.setAppId(NwLoginConstants.appAppId);
            nwApp.setAppsecret(NwLoginConstants.appAppsecret);
        }
        try {
            //发送注册请求(调用南网的注册方法)
            RespLoginData respLoginData = null;
//            查询用户中心是否存在当前用户
            CloudUserVo cloudUserVo = this.queryUserBySso(registerForms);
//            数据幂等性操作 记录日志
            RegistersVo registersVo = getRegisterVo(registerForms);
            log.error("check001_registersVo:{}", JSON.toJSONString(registersVo));

            if (null == cloudUserVo) {
                log.info("系统不存在,用户中心不存在,同步数据到用户中心");
                respLoginData = HttpUtils.postJson(NwLoginConstants.registerPhone, registersVo, null, Map.class, null);
                log.error("check002_respLoginData:{}", JSON.toJSONString(respLoginData));
                if (respLoginData.getCode().equals(NwLoginConstants.HTTP_RESPONSE_CODE_200)) {
                    return NwLoginConstants.REGISTERIP_SUCCESS;
                }else {
                    return NwLoginConstants.REGISTERIP_FAIL;
                }
            } else {
                log.info("系统不存在,用户中心存在,操作绑定业务");
                respLoginData = this.bindSsoUser(registerForms);
                log.error("check002_respLoginData:{}", JSON.toJSONString(respLoginData));
                if (respLoginData.getCode().equals(NwLoginConstants.HTTP_RESPONSE_CODE_200)) {
                    return NwLoginConstants.REGISTERIP_SUCCESS_BIND;
                }else {
                    return NwLoginConstants.REGISTERIP_FAIL;
                }
            }
        } catch (Exception e) {
            throw new BaseException("9999", e.getMessage());
        }
    }

    private void checkRequestParam(HttpServletRequest request, RegisterForms registerForms) {
        String ipAddress = IpUtils.getIpAddr(request);
        Integer loginModeType = registerForms.getLoginModeType();
        NwApp nwApp = new NwApp();
        if (loginModeType == 1) {
            nwApp.setCode(1);
            nwApp.setAppId(NwLoginConstants.appId);
            nwApp.setAppsecret(NwLoginConstants.appsecret);
        } else if (loginModeType == 2) {
            nwApp.setCode(2);
            nwApp.setAppId(NwLoginConstants.h5AppId);
            nwApp.setAppsecret(NwLoginConstants.h5Appsecret);
        } else if (loginModeType == 3) {
            nwApp.setCode(3);
            nwApp.setAppId(NwLoginConstants.wechatAppId);
            nwApp.setAppsecret(NwLoginConstants.wechatAppsecret);
        } else if (loginModeType == 4) {
            nwApp.setCode(4);
            nwApp.setAppId(NwLoginConstants.appAppId);
            nwApp.setAppsecret(NwLoginConstants.appAppsecret);
        }

        if (null == loginModeType) {
            throw new BaseException(NwLoginConstants.LOGIN_TYPE_EXCEPTION_CODE, NwLoginConstants.LOGIN_TYPE_EXCEPTION_MSG);
        }
        if (null == ipAddress) {
            throw new BaseException(NwLoginConstants.IP_NULL_CODE, NwLoginConstants.IP_NULL_MSG);
        }
        if (null == registerForms) {
            throw new BaseException(NwLoginConstants.PARAM_IS_NULL_ERROR_CODE, NwLoginConstants.PARAM_IS_NULL_ERROR_CODE_MSG);
        }
        if (StringUtils.isEmpty(registerForms.getMobilePhone())) {
            throw new BaseException(NwLoginConstants.PHONE_NOT_NULL_CODE, NwLoginConstants.PHONE_NOT_NULL_MSG);
        }
        if (!this.checkPhone(registerForms.getMobilePhone())) {
            throw new BaseException(NwLoginConstants.MOBILE_FORMAT_ERROR_CODE, NwLoginConstants.MOBILE_FORMAT_ERROR_CODE_MSG);
        }
        if (StringUtils.isBlank(registerForms.getUserAccount())) {
            throw new BaseException(NwLoginConstants.USER_NAME_NOT_NULL_CODE, NwLoginConstants.USER_NAME_NOT_NULL_MSG);
        }

        if (StringUtils.isBlank(registerForms.getUserPassword())) {
            throw new BaseException(NwLoginConstants.PASSWORD_NOT_NULL_CODE, NwLoginConstants.PASSWORD_NOT_NULL_MSG);
        }
        if (null == registerForms.getAgainPassword()) {
            throw new BaseException(NwLoginConstants.AGAIN_PASSWORD_NOT_NULL_CODE, NwLoginConstants.AGAIN_PASSWORD_NOT_NULL_MSG);
        }

        if (null == registerForms.getPlatformId()) {
            registerForms.setPlatformId(NwLoginConstants.PLATFORM_ID);
        }
    }

   /* *
     * 验证手机号
     *
     * @param phone
     * @return 验证成功返回true，验证失败返回false*/

    public static boolean checkPhone(String phone) {
        String regex = "^1\\d{10}$";
        return Pattern.matches(regex, phone);
    }


    private CloudUserVo queryUserBySso(RegisterForms registerForms) throws Exception {
        try {
            LbcloudUserVo lbcloudUserVo = new LbcloudUserVo();
            lbcloudUserVo.setMobilePhone(registerForms.getMobilePhone());
            HashMap<String, String> requestMap = Maps.newHashMap();
            requestMap.put(NwLoginConstants.CACEL_DESENSITIZATION, NwLoginConstants.TRUE); //查询用户信息 不脱敏查询
            NwApp nwApp = new NwApp();
            nwApp.setCode(1);
            nwApp.setAppId(NwLoginConstants.appId);
            nwApp.setAppsecret(NwLoginConstants.appsecret);
            RespLoginData mobileResult = HttpUtils.postJsonForApi(NwLoginConstants.personEasyList, lbcloudUserVo, null, Map.class, requestMap, nwApp);
            Map<String, Object> resultMap = (Map<String, Object>) mobileResult.getData();
            JSONArray dataArray = (JSONArray) resultMap.get(NwLoginConstants.USER_RECORDS);

            if (!NwLoginConstants.HTTP_RESPONSE_CODE_200.equals(mobileResult.getCode())) {
                log.info("调用南网用户信息接口失败:{}", JSON.toJSONString(mobileResult));
                throw new BaseException(mobileResult.getCode(), mobileResult.getMessage());
            }
            if (CollectionUtils.isEmpty(dataArray)) {
                return null;
            }
            CloudUserVo cloudUserVo = new CloudUserVo();
            if (CollectionUtils.isNotEmpty(dataArray)) {
                JSONObject dataObject = (JSONObject) dataArray.get(NwLoginConstants.ZERO);
                String userId = dataObject.get(NwLoginConstants.USER_LBCLOUD_ID) != null ? dataObject.get(NwLoginConstants.USER_LBCLOUD_ID).toString() : null;
                String userName = dataObject.get(NwLoginConstants.USER_LBCLOUD_NAME) != null ? dataObject.get(NwLoginConstants.USER_LBCLOUD_NAME).toString() : null;
                String userAccount = dataObject.get(NwLoginConstants.USER_LBCLOUD_ACCOUNT) != null ? dataObject.get(NwLoginConstants.USER_LBCLOUD_ACCOUNT).toString() : null;
                cloudUserVo.setUserId(userId);
                cloudUserVo.setUserAccount(userAccount);
                cloudUserVo.setUserName(userName);
            }
            cloudUserVo.setIsOriginalUser(StringUtils.isBlank(cloudUserVo.getUserAccount()) ? NwLoginConstants.ZERO : NwLoginConstants.ONE);
            registerForms.setExternalId(cloudUserVo.getUserId());
            return cloudUserVo;

        } catch (Exception e) {
            log.info("调用南网用户信息接口异常:{}", e.getMessage());
            throw new Exception(NwLoginConstants.USER_DATA_QUERY_FAILED_MSG);
        }
    }


  /* 封装南网需要的注册信息*/

    private RegistersVo getRegisterVo(RegisterForms registerForms) {
        RegistersVo registersVo = new RegistersVo();
        if (null != registerForms.getEnterpriseName()) {
            registersVo.setName(registerForms.getEnterpriseName());
        }
        if (null != registerForms.getMobilePhone()) {
            registersVo.setPhone(registerForms.getMobilePhone());
        }
        if (null != registerForms.getMobilePhoneCode()) {
            registersVo.setCode(registerForms.getMobilePhoneCode());
        }
        if (null != registerForms.getUserAccount()) {
            registersVo.setUserAccount(registerForms.getUserAccount());
        }
        NwApp nwApp = new NwApp();
        Integer loginModeType = registerForms.getLoginModeType();
        if (loginModeType == NwLoginConstants.ONE) {
            nwApp.setCode(1);
            nwApp.setAppId(NwLoginConstants.appId);
            nwApp.setAppsecret(NwLoginConstants.appsecret);
        } else if (loginModeType == NwLoginConstants.TWO) {
            nwApp.setCode(2);
            nwApp.setAppId(NwLoginConstants.h5AppId);
            nwApp.setAppsecret(NwLoginConstants.h5Appsecret);
        } else if (loginModeType == NwLoginConstants.THREE) {
            nwApp.setCode(3);
            nwApp.setAppId(NwLoginConstants.wechatAppId);
            nwApp.setAppsecret(NwLoginConstants.wechatAppsecret);
        } else if (loginModeType == NwLoginConstants.FOUR) {
            nwApp.setCode(4);
            nwApp.setAppId(NwLoginConstants.appAppId);
            nwApp.setAppsecret(NwLoginConstants.appAppsecret);
        }
        registersVo.setAppId(nwApp.getAppId());
        registersVo.setAppSecret(nwApp.getAppsecret());
        registersVo.setUserName(registerForms.getUserAccount());
        registersVo.setPsCode(registerForms.getUserPassword());
        registersVo.setConfirmPsCode(registerForms.getAgainPassword());
        return registersVo;
    }

    private RespLoginData bindSsoUser(RegisterForms registerForms) {
        //手机验证码校验
        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("verificationCodeType", NwLoginConstants.REGISTERED);
        paraMap.put("verificationCode", registerForms.getMobilePhoneCode());
        paraMap.put("phone", registerForms.getMobilePhone());
        RespLoginData verifyResult = HttpUtils.postJson(NwLoginConstants.verifyPhoneCode, null, null, Boolean.class, paraMap);
        log.info("verifyResult:{}", JSON.toJSONString(verifyResult));
        if (NwLoginConstants.HTTP_RESPONSE_CODE_200.equals(verifyResult.getCode())) {
            Boolean result = (Boolean) verifyResult.getData();
            if (!result) {
                throw new BaseException(NwLoginConstants.CHECK_MOBILEPHONECODE_WRONG_ERROR_CODE, NwLoginConstants.CHECK_MOBILEPHONECODE_WRONG_ERROR_CODE_MSG);
            }
        } else {
            throw new BaseException(verifyResult.getCode(), verifyResult.getMessage());
        }
        LbcloudUserVo lbcloudUserVo = new LbcloudUserVo();
        lbcloudUserVo.setUserId(registerForms.getExternalId());
        lbcloudUserVo.setAppId(NwLoginConstants.appId);
        lbcloudUserVo.setAccount(registerForms.getUserAccount());
        return HttpUtils.postJson(NwLoginConstants.userBindUrl, lbcloudUserVo, null, Map.class, null);
    }

}
