package com.github.wxiaoqi.security.admin.jobhandler;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.biz.AppUserDetailBiz;
import com.github.wxiaoqi.security.admin.entity.AppUserDetail;
import com.xxfc.platform.universal.dto.RegionDTO;
import com.xxfc.platform.universal.feign.RegionFeign;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/12/27 11:14
 */
@JobHandler(value = "ipAnalyticalJobHandler")
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
//@RefreshScope
public class IPJobHandler extends IJobHandler {
    private final RestTemplate restTemplate;
    private final RegionFeign regionFeign;
    private final AppUserDetailBiz appUserDetailBiz;
    private static  final Integer PROVINCECODE = 440000;
    @Value("${ip.analytical.appId:xcjtqjromfuvjjtt}")
    private String  appId;
    @Value("${ip.analytical.secret:bzNRK3FUR2d3WGc0MmhKWGZINm5MQT09}")
    private String  secret;
    @Override
    public ReturnT<String> execute(String s) throws Exception {

        List<AppUserDetail> appUserDetails =  appUserDetailBiz.findAllUserDetailWithNoProinceCode();
        for (AppUserDetail appUserDetail : appUserDetails) {
              String crtHost = appUserDetail.getCrtHost();
        if (log.isDebugEnabled()) {
            log.debug("解析的地址：【{}】", crtHost + "---time===" + System.currentTimeMillis() / 1000L);
        }
        try {
            analyticalIPByWebSiteAndIPAddress(IPAddress.BASE_IP_PARSING_URL2, crtHost, appUserDetail);
        } catch (Exception e) {
            try {
                analyticalIPByWebSiteAndIPAddress(IPAddress.BASE_IP_PARSING_URL1, crtHost, appUserDetail);
            } catch (Exception ex) {
                appUserDetail.setProvinceCode(PROVINCECODE);
                log.error("解析地址失败：【{}】", ex.getMessage());
            }
        }
            appUserDetailBiz.updateSelectiveByIdRe(appUserDetail);
        }
        return ReturnT.SUCCESS;
    }

    private void analyticalIPByWebSiteAndIPAddress(String url, String crtHost, AppUserDetail appUserDetail) {
        String ipAddress = restTemplate.getForObject(String.format("%s%s&app_id=%s&app_secret=%s", url, crtHost,appId,secret), String.class);
        String data = JSONObject.parseObject(ipAddress).getString(IPAddress.BASE_DATA);
        JSONObject ipJsonObject = JSONObject.parseObject(data);
        String cityName = ipJsonObject.getString(IPAddress.CITY_NAME);
        RegionDTO regionDTO = regionFeign.getRegionByCityName(StringUtils.isEmpty(cityName) ? "东莞" : cityName);
        if (null != regionDTO) {
            appUserDetail.setProvinceCode(Integer.valueOf(String.valueOf(regionDTO.getParentId())));
            appUserDetail.setCityCode(Integer.valueOf(String.valueOf(regionDTO.getId())));
        }else{
            if (StringUtils.isNotEmpty(cityName)){
                appUserDetail.setProvinceCode(Integer.valueOf(ipJsonObject.get(IPAddress.RPOINCE_ID).toString()));
                appUserDetail.setCityCode(Integer.valueOf(ipJsonObject.get(IPAddress.CITY_ID).toString()));
            }
        }


    }

    /**
     * @author libin
     * @version 1.0.0
     * @dec ip 解析返回的地址信息
     */
    private static class IPAddress {
        public static final String BASE_IP_PARSING_URL1 = "http://ip.taobao.com/service/getIpInfo.php?ip=";
        public static final String BASE_IP_PARSING_URL2 = "https://www.mxnzp.com/api/ip/aim_ip?ip=";
        public static final String BASE_DATA = "data";
        public static final String CITY_NAME = "city";
        public static final String RPOINCE_ID="provinceId";
        public static final String CITY_ID="cityId";
    }
}
