package com.bohuikeji.delivery.backstage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TCustomer;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.service.IGmsService;
import com.bohuikeji.delivery.backstage.service.ITCustomerService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.service.ITWarehouseService;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信发送业务实现类
 * @author sjh
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class GmsServiceImpl implements IGmsService {
    final RedisUtil redisUtil;
    final ITCustomerService customerService;
    final ITOrderService orderService;
    final ITWarehouseService warehouseService;
    @Override
    public String sendCode(String phone, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String code=NumberUtils.getRandom(6);
        log.error("短信验证码发送失败:ip:{},手机号：{}",IpUtil.getIpAddr(request),phone);
        JSONObject ips= (JSONObject) redisUtil.get("gms:ip:times:"+IpUtil.getIpAddr(request));
        log.error("短信验证码缓存信息:JSONObject:{}",ips);
        if(ips != null){
            ips.put("times",ips.getInteger("times")+1);
            log.error("短信验证码发送次数:次数:{}",ips.put("times",ips.getInteger("times")+1));
            if(ips.getInteger("times")-1>3){
                ips.put("timing",24);
                redisUtil.set("gms:ip:times:"+IpUtil.getIpAddr(request),ips,Duration.ofHours(24).getSeconds());
                return ips.getString("keys");
            }
            if(ips.getInteger("times")-1>10){
                ips.put("timing",3);
                redisUtil.set("gms:ip:times:"+IpUtil.getIpAddr(request),ips,Duration.ofDays(3).getSeconds());
                return ips.getString("keys");
            }
            return ips.getString("keys");
        }
        jsonObject.put("keys",code);
        jsonObject.put("times",1);
        redisUtil.set("gms:ip:times:"+IpUtil.getIpAddr(request),jsonObject,Duration.ofMinutes(10).getSeconds());
        return code;
        /*Object times=redisUtil.get("gms:code:times:"+phone);
        String code=NumberUtils.getRandom(6);
        if(times!=null){
            int count=Integer.parseInt(times.toString());
            if(count>200){
                redisUtil.set("gms:code:times:"+phone,count+1,-1);
                log.warn("【短信验证码发送失败】，手机号：{}，发送次数 已达{}次。",phone,count+1);
                return code;
            }
            if(count>150){
                redisUtil.set("gms:code:times:"+phone,count+1, Duration.ofDays(30).getSeconds());
                log.warn("【短信验证码发送失败】，手机号：{}，发送次数 已达{}次。",phone,count+1);
                return code;
            }
            //15天内发送超过100次
            if(count>100){
                redisUtil.set("gms:code:times:"+phone,count+1, Duration.ofDays(15).getSeconds());
                log.warn("【短信验证码发送失败】，手机号：{}，发送次数 已达{}次。",phone,count+1);
                return code;
            }
            if(count>50){
                redisUtil.set("gms:code:times:"+phone,count+1, Duration.ofDays(7).getSeconds());
                log.warn("【短信验证码发送失败】，手机号：{}，发送次数 已达{}次。",phone,count+1);
                return code;
            }
            //24小时内发送超过20次
            if(count>20){
                redisUtil.set("gms:code:times:"+phone,count+1, Duration.ofHours(24).getSeconds());
                log.warn("【短信验证码发送失败】，手机号：{}，发送次数 已达{}次。",phone,count+1);
                return code;
            }
            if(count>10){
                redisUtil.set("gms:code:times:"+phone,count+1, Duration.ofHours(8).getSeconds());
                log.warn("【短信验证码发送失败】，手机号：{}，发送次数 已达{}次。",phone,count+1);
                return code;
            }
            //3小时以内，3次以内,正常发送
            else {
                YiXunGmsUtils.sendMsg(phone,"SMS_184115918","code", code);
                redisUtil.set("gms:code:times:"+phone,count+1,Duration.ofHours(1).getSeconds());
                return code;
            }
        }
        //没有发送记录,正常发送
        YiXunGmsUtils.sendMsg(phone,"SMS_184115918","code", code);
        redisUtil.set("gms:code:times:"+phone,1,Duration.ofHours(1).getSeconds());
        redisUtil.set("gms:code:txt:"+phone,code,Duration.ofMinutes(10).getSeconds());
        return code;*/
    }

    @Override
    public boolean verifyCode(String phone, String code) {
        Object saveCode=redisUtil.get("gms:code:txt:"+phone);
        if (code!=null&&code.equals(saveCode)){
            return true;
        }
        return false;
    }

    @Override
    public boolean sendOrderReceipt(String phone, String orderNum) {
        Map<String,Object> params=new HashMap<>(1);
        params.put("order",orderNum);
        if(redisUtil.get("gms:order:receipt_"+orderNum+"_"+phone)==null){
            if(thirdMessage(phone,orderNum,"SMS_185560837",params)){
                redisUtil.set("gms:order:receipt_"+orderNum+"_"+phone,orderNum,60*10);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean sendOrderSign(String phone, String orderNum) {
        Map<String,Object> params=new HashMap<>(1);
        params.put("order",orderNum);
        if(redisUtil.get("gms:order:sign_"+orderNum+"_"+phone)==null){
            if(thirdMessage(phone,orderNum,"SMS_185560840",params)){
                redisUtil.set("gms:order:sign_"+orderNum+"_"+phone,orderNum,60*10);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean sendOrderSend(String phone, String orderNum) {
        Map<String,Object> params=new HashMap<>(1);
        params.put("order",orderNum);
        if(redisUtil.get("gms:order:send_"+orderNum+"_"+phone)==null){
            if(thirdMessage(phone,orderNum,"SMS_192835835",params)){
                redisUtil.set("gms:order:send_"+orderNum+"_"+phone,orderNum,60*10);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean sendOrderEnd(String phone, String orderNum) {
        Map<String,Object> params=new HashMap<>(1);
        params.put("order",orderNum);
        if(redisUtil.get("gms:order:end_"+orderNum+"_"+phone)==null){
            if(thirdMessage(phone,orderNum,"SMS_192835836",params)){
                redisUtil.set("gms:order:end_"+orderNum+"_"+phone,orderNum,60*10);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean sendNoServerMsg(String phone, String region) {
        Map<String,Object> params=new HashMap<>(1);
        params.put("region",region);
        if(thirdMessage(phone,null,"SMS_190265757",params)){
            return true;
        }
        return false;
    }

    @Override
    public boolean sendCancelMsg(String phone, String orderNum) {
        Map<String,Object> params=new HashMap<>(1);
        params.put("order",orderNum);
        if(thirdMessage(phone,orderNum,"SMS_210705215",params)){
            return true;
        }
        return false;
    }

    @Override
    public boolean sendMarketMsg(String phone) {
        if(AliGmsUtils.sendMsg(phone,"SMS_220601364","order","1024")){
            return true;
        }
        return false;
    }

    @Override
    public boolean sendOrderSupply(String phone, String orderNum,BigDecimal price, String url) {
        Map<String,Object> params=new HashMap<>(3);
        params.put("order",orderNum);
        params.put("price",price.setScale(2, RoundingMode.DOWN));
        params.put("url",url);
        if(YiXunGmsUtils.sendMsg(phone,"SMS_ORDER_SUPPLY_H5",params,true)){
            return true;
        }
        return false;
    }

    /**
     * 发送支付超时取消通知
     *
     * @param phone    手机号
     * @param orderNum 订单号
     * @return
     */
    @Override
    public boolean sendOrderPayTimeOut(String phone, String orderNum) {
        Map<String,Object> params=new HashMap<>(1);
        params.put("order",orderNum);
        return YiXunGmsUtils.sendMsg(phone,"SMS_ORDER_PAY_TIMEOUT_JD",params,true);
    }

    @Override
    public boolean sendTxt(String phone, String txt) {
        return YiXunGmsUtils.sendTxt(phone,txt);
    }

    @Override
    public boolean thirdMessage(String phone,String num,String templateCode, Map<String, Object> params) {
        TCustomer customer;
        if(StringUtils.isNotBlank(num)){
            TOrder order = orderService.getByNum(num);
            customer = customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_id",order.getPlayerId()));
        }else {
            customer = customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_phone",phone));
        }
        if(customer != null && "关闭".equals(customer.getMessageSwitch())){
            return false;
        }
        return YiXunGmsUtils.sendMsg(phone,templateCode,params);
    }
}
