package com.sysu.admin.support.sms;

import com.alibaba.fastjson.JSONObject;
import com.github.zhangquanli.aliyun.sms.response.SendSmsResponse;
import com.google.common.collect.Maps;
import com.sysu.admin.support.base.BaseService;
import com.sysu.admin.support.sms.aliyun.AliSmsSenderHelper;
import com.sysu.admin.support.system.config.SConfig;
import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import com.xiesx.fastboot.core.jpa.JpaPlusRepository;
import com.xiesx.fastboot.utils.DateUtils;
import lombok.NonNull;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @title GameServiceImpl.java
 * @description 游戏表 业务类
 * @author 谢思贤
 * @date 2020-04-30
 */
@Service
public class SmsService extends BaseService<Sms, Long> {

    @Lazy
    @Autowired
    AliSmsSenderHelper aliSmsSenderHelper;


    @Lazy
    @Autowired
    SmsRepository mSmsRepository;

    public BaseResult validate(@NonNull String mobile, @NonNull String code) {

        SConfig config = serviceContext.mSConfigService.get("test");
        if(config != null && config.getRemark().equals("1")){
            JSONObject jsonObject = JSONObject.parseObject(config.getV());
            String testUser = jsonObject.getString("user");
            if(testUser.equals(mobile)){
                String testCode = jsonObject.getString("code");
                if(testUser.equals(mobile) && testCode.equals(code)) {
                    return R.succ("操作成功");
                }else{
                    return R.fail("验证码不匹配！");
                }
            }
        }

        Sms sms = mSmsRepository.lastSend(mobile);
        if (StringUtils.isEmpty(code)) {
            return R.fail("验证码不能为空");
        } else if (ObjectUtils.isEmpty(sms)) {
            return R.fail("请先获取验证码");
        } else if (!StringUtils.equals(sms.getCode(), code)) {
            return R.fail("验证码不匹配");
        } else if (sms.isExpried()) {
            mSmsRepository.expire(sms.getId());
            return R.fail("验证码已过期");
        } else {
            mSmsRepository.delete(sms);
            return R.succ("操作成功");
        }
    }

    public BaseResult send(String mobile, String template){
        // 生成验证码
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        // 发送验证码
        SendSmsResponse response = aliSmsSenderHelper.sendSms(mobile, template, code);
        if (response.getCode().equals("OK")) {
            // 先把未使用的删除
            List<Sms> list = findByMobile(mobile);
            for (Sms sms : list) {
                mSmsRepository.delete(sms);
            }
            // 存储到db，web、api都可以用，单纯web可以用session
            Sms sms = new Sms();
            sms.setMobile(mobile);
            sms.setCode(code);
            sms.setCreateDate(new Date());
            sms.setExpireDate(DateUtils.addMinutes(sms.getCreateDate(), 5));
            mSmsRepository.save(sms);
            Map<String, Object> map = Maps.newHashMap();
            map.put("code", response.getCode());
            map.put("date", new Date());
            return R.succ("发送成功", map);
        } else {
            Map<String, Object> map = Maps.newHashMap();
            map.put("code", response.getCode());
            map.put("date", new Date());
            return R.fail(AliSmsSenderHelper.getMessage(response.getMessage()), map);
        }
    }

    public List<Sms> findByMobile(String mobile){
        return mSmsRepository.findByMobile(mobile);
    }

    public Sms lastSend(String mobile){
        return mSmsRepository.lastSend(mobile);
    }

    public int expire(Long id){
        return mSmsRepository.expire(id);
    }

    @Override
    public JpaPlusRepository<Sms, Long> r() {
        return mSmsRepository;
    }
}
