package com.hzs.member.sms.controller.api;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.sms.service.IApiCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 短信处理控制器
 */
@RequestMapping("/api/sms")
@RestController
public class ApiSmsController extends BaseController {

    @Autowired
    private IApiCodeService iApiCodeService;
    @Autowired
    private ICuMemberService iCuMemberService;

    /**
     * 验证码
     *
     * @param phone 手机号码
     * @return
     */
    @RepeatSubmitSimple
    @GetMapping("/verification")
    public AjaxResult verification(@RequestParam(required = false) String phone) {
        return toAjax(iApiCodeService.sendCode(phone, null, null));
    }

    /**
     * 忘记密码验证码
     *
     * @param memberCode 会员编号
     * @param phone      手机号码
     * @return
     */
    @RepeatSubmitSimple
    @GetMapping("/forget-verification")
    public AjaxResult forgetVerification(@RequestParam String memberCode, @RequestParam String phone) {
        List<CuMemberExt> cuMemberList = iCuMemberService.listMemberByPhone(phone);
        if (CollectionUtil.isEmpty(cuMemberList)) {
            return AjaxResult.error("会员联系方式不存在");
        }
        return toAjax(iApiCodeService.sendRecoverCode(phone));
    }

    /**
     * 登录用户发送短信
     * 使用： 重置密码
     *
     * @return
     */
    @RepeatSubmitSimple
    @GetMapping("/self-verification")
    public AjaxResult selfVerification() {
        CuMemberExt cuMemberExt = iCuMemberService.getMemberById(SecurityUtils.getUserId());
        if (null == cuMemberExt) {
            // 会员不存在
            return AjaxResult.error("会员信息不存在");
        }

        return toAjax(iApiCodeService.resetPayPasswordCode(cuMemberExt.getPhone()));
    }

}
