package com.sysu.admin.support.sms;

import com.alibaba.fastjson.JSON;
import com.github.zhangquanli.aliyun.sms.response.SendSmsResponse;
import com.google.common.collect.Maps;
import com.sysu.admin.support.base.BaseComponent;
import com.sysu.admin.support.base.ServiceContext;
import com.sysu.admin.support.sms.aliyun.AliSmsSenderHelper;
import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import com.xiesx.fastboot.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @title SmsController
 * @description
 * @author XIE
 * @date 2020年4月24日下午10:10:33
 */
@Validated
@RestController
@RequestMapping(value = "/api/sms")
public class SmsController extends BaseComponent {

    @Autowired
    SmsService mSmsService;

    @Autowired
    SmsRepository mSmsRepository;

    @Autowired
    AliSmsSenderHelper mSmsSenderHelper;

    /**
     * 发送短信
     *
     * @param data
     * @return
     */
    @RequestMapping("/test")
    public BaseResult test(@RequestBody String data) {
        SmsReqVo req = JSON.parseObject(data, SmsReqVo.class);
        super.validate(req, SmsReqVoValid.SmsSendValid.class);
        // 生成验证码
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        // 先把未使用的删除
        List<Sms> list = mSmsRepository.findByMobile(req.getMobile());
        for (Sms sms : list) {
            mSmsRepository.delete(sms);
        }
        // 存储到db，web、api都可以用，单纯web可以用session
        Sms sms = new Sms();
        sms.setMobile(req.getMobile());
        sms.setCode(code);
        sms.setIsUse(0);
        sms.setCreateDate(new Date());
        sms.setExpireDate(DateUtils.addMinutes(sms.getCreateDate(), 5));
        int row = mSmsRepository.insertOrUpdate(sms);
        Map<String, Object> map = Maps.newHashMap();
        map.put("code", code);
        map.put("date", new Date());
        // return (row >= 1) ? R.succ("发送成功:", map) : R.fail("发送失败", map);
        return (row >= 1) ? R.succ("发送成功",map) : R.fail("发送失败");
    }

    /**
     * 发送短信
     *
     * @param data
     * @return
     */
    @RequestMapping("/send")
    public BaseResult send(@RequestBody String data) {
        SmsReqVo req = JSON.parseObject(data, SmsReqVo.class);
        super.validate(req, SmsReqVoValid.SmsSendValid.class);
        // 生成验证码
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        // 发送验证码
        SendSmsResponse response = mSmsSenderHelper.sendSms(req.getMobile(), req.getTemplate(), code);
        if (response.getCode().equals("OK")) {
            // 先把未使用的删除
            List<Sms> list = mSmsRepository.findByMobile(req.getMobile());
            for (Sms sms : list) {
                mSmsRepository.delete(sms);
            }
            // 存储到db，web、api都可以用，单纯web可以用session
            Sms sms = new Sms();
            sms.setMobile(req.getMobile());
            sms.setCode(code);
            sms.setCreateDate(new Date());
            sms.setIsUse(0);
            sms.setExpireDate(DateUtils.addMinutes(sms.getCreateDate(), 5));
            int row = mSmsRepository.insertOrUpdate(sms);
            Map<String, Object> map = Maps.newHashMap();
            map.put("code", code);
            map.put("date", new Date());
            return (row >= 1) ? R.succ("发送成功", map) : R.fail("发送失败", map);
        } else {
            return R.fail("发送失败");
        }
    }

    /**
     * 查询短信
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping("/validate")
    public BaseResult validate(@Validated(value = SmsReqVoValid.SmsCheckValid.class) SmsReqVo req) {
        return mSmsService.validate(req.getMobile(), req.getCode());
    }
}
