package com.jeequan.jeepay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ip.IpAddressResult;
import com.jeequan.jeepay.core.utils.ip.AddressUtils;
import com.jeequan.jeepay.db.entity.IpLocation;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.service.mapper.IpLocationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * ip关联地区缓存表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2024-03-21
 */
@Service
public class IpLocationService extends ServiceImpl<IpLocationMapper, IpLocation>{

    @Autowired private MchConfigService mchConfigService;

    /**
     * 获取ip关联的信息
     * @return
     */
    public IpLocation getIpInfo(String ip){
        IpLocation ipLocation = baseMapper.selectById(ip);
        if(ipLocation == null){
            IpAddressResult addressResult = AddressUtils.getRealAddressByIP(ip);
            ipLocation = new IpLocation(addressResult);
            save(ipLocation);
        }
        return ipLocation;
    }

    /**
     * 校验ip
     * @param ip
     * @param mchApplyment
     */
    public void preCheck(String ip, MchApplyment mchApplyment){
        String regionLock = mchConfigService.getRegionLock(mchApplyment);
        if(MchConfig.AREA_LOCAK_OPEN.equals(regionLock)){
            IpLocation ipInfo = getIpInfo(ip);
            if(ipInfo.getState() != null && IpAddressResult.SUCCESS != ipInfo.getState()){
                throw new BizException("付款距离过远");
            }
            if(AddressUtils.LOCATION_TEXT.equals(ipInfo.getAddress())){
                return;
            }
            JSONObject result = JSON.parseObject(mchApplyment.getApplyDetailInfo());
            JSONArray areaName = result.getJSONArray("areaName");
            if(areaName == null){
                throw new BizException("商户经营区域异常");
            }
            String provinceName = areaName.getString(0);
            String cityName = areaName.getString(1);
            if(!cityName.equals(ipInfo.getCityName()) && !provinceName.equals(ipInfo.getProvinceName())){
                throw new BizException("付款用户和商户经营区域距离过远");
            }
        }
    }
}
