package com.ruoyi.web.controller.api.csMember;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.annotation.CSMemberUserLoginToken;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.ServiceResponseEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.securityContext.CsOrderMemberUserSecurityContext;
import com.ruoyi.common.utils.RSAUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.cs.domain.CsMemberNotice;
import com.ruoyi.cs.domain.dto.*;
import com.ruoyi.cs.domain.vo.CsOrderMemberUserVO;
import com.ruoyi.cs.service.ICsMemberNoticeService;
import com.ruoyi.cs.service.ICsOrderMemberUserService;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import io.swagger.annotations.Api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: cc
 * @Date: 2024/4/23
 * @Description:用户端登录
 */
@Api("用户端PC/登录注册")
@RestController
@RequestMapping("/api/cs/csUserLogin")
public class ApiCsUserInfoLoginController extends BaseController {


    @Resource
    private ICsOrderMemberUserService csOrderMemberUserInfoService;

    @Resource
    private RedisCache redisCache;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Resource
    private ISysNoticeService noticeService;

    @Resource
    private ICsMemberNoticeService csMemberNoticeService;

    /**
     * 生成图片验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode()
    {
        AjaxResult ajax = AjaxResult.success();

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        capStr = code = captchaProducer.createText();
        image = captchaProducer.createImage(capStr);

        if (image == null){
            throw new ServiceException(ServiceResponseEnum.CAPTCHA_GENERATION_FAILED);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }


    /**
     * 注册
     * @param registerDTO 参数
     * @return 结果
     */
    @RepeatSubmit
    @PostMapping("/csMemberUserRegister")
    @Log(title = "注册", businessType = BusinessType.INSERT)
    public AjaxResult csMemberUserRegister(@RequestBody @Validated({CsOrderMemberUserRegisterDTO.Register.class}) CsOrderMemberUserRegisterDTO registerDTO, BindingResult bindingResult){
        // 参数校验
        if (bindingResult.hasErrors()){
            return AjaxResult.allParameterErrors(bindingResult);
        }

        JSONObject result = csOrderMemberUserInfoService.csMemberUserLoginOrRegister(registerDTO);
        return AjaxResult.success(result);
    }

    /**
     * 绑定注册
     * @param registerDTO 参数
     * @return 结果
     */
    @RepeatSubmit
    @PostMapping("/csMemberUserBind")
    @Log(title = "绑定注册", businessType = BusinessType.INSERT)
    public AjaxResult csMemberUserBind(@RequestBody @Validated({CsOrderMemberUserRegisterDTO.Bind.class}) CsOrderMemberUserRegisterDTO registerDTO, BindingResult bindingResult){
        // 参数校验
        if (bindingResult.hasErrors()){
            return AjaxResult.allParameterErrors(bindingResult);
        }

        JSONObject result = csOrderMemberUserInfoService.csMemberUserLoginOrRegister(registerDTO);
        return AjaxResult.success(result);
    }

    /**
     * 登录
     * @param loginDTO 参数
     * @return 结果
     */
    @RepeatSubmit
    @PostMapping("/csUserLogin")
    @Log(title = "登录", businessType = BusinessType.GRANT)
    public AjaxResult csUserLogin(@RequestBody @Validated CsOrderMemberUserLoginDTO loginDTO, BindingResult bindingResult){
        // 参数校验
        if (bindingResult.hasErrors()){
            return AjaxResult.allParameterErrors(bindingResult);
        }

        JSONObject result = csOrderMemberUserInfoService.csUserLogin(loginDTO);
        return AjaxResult.success(result);
    }

    /**
     * 获取用户信息
     * @return 结果
     */
    @CSMemberUserLoginToken
    @GetMapping("/getCsMemberUserInfo")
    public AjaxResult getCsMemberUserInfo(){
        CsOrderMemberUserVO userInfo = csOrderMemberUserInfoService.getMemberUserInfo();
        return AjaxResult.success(userInfo);
    }

    /**
     * 发送邮箱验证码
     * @return 结果
     */
    @GetMapping("/sendEmailCode")
    public AjaxResult sendEmailCode(String emailTo){
        AjaxResult ajax = AjaxResult.success();
        if(StringUtils.isBlank(emailTo)){
            return AjaxResult.error("请填写邮箱");
        }
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.EMAIL_CAPTCHA_CODE_KEY + uuid;
        // 生成验证码
        String code = captchaProducer.createText();
        redisCache.setCacheObject(verifyKey, code, Constants.EMAIL_CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        csOrderMemberUserInfoService.sendEmailCode(emailTo,code);
        ajax.put("uuid", uuid);
        return ajax;
    }

    /**
     * 找回密码
     * @param resetPwdDTO 参数
     * @return 结果
     */
    @RepeatSubmit
    @PostMapping("/resetPwd")
    @Log(title = "找回密码", businessType = BusinessType.UPDATE)
    public AjaxResult resetPwd(@RequestBody @Validated CsOrderMemberUserReSetPwdDTO resetPwdDTO, BindingResult bindingResult){
        // 参数校验
        if (bindingResult.hasErrors()){
            return AjaxResult.allParameterErrors(bindingResult);
        }

        int i = csOrderMemberUserInfoService.resetPassword(resetPwdDTO);
        return AjaxResult.toAjax(i);
    }

    /**
     * 激活邮箱账号
     * @param  activationCode 参数
     * @return 结果
     */
    @RepeatSubmit
    @PostMapping("/activationAccount")
    @Log(title = "激活邮箱账号", businessType = BusinessType.UPDATE)
    public AjaxResult activationAccount(@RequestBody @Validated CsOrderMemberUserActivationAccountDTO activationCode, BindingResult bindingResult){
        // 参数校验
        if (bindingResult.hasErrors()){
            return AjaxResult.allParameterErrors(bindingResult);
        }
        return csOrderMemberUserInfoService.activationAccount(activationCode.getActivationCode());
    }

    /**
     * 修改操作指引状态
     * @return 结果
     */
    @RepeatSubmit
    @CSMemberUserLoginToken
    @PostMapping("/editGuideStatus")
    @Log(title = "修改操作指引状态", businessType = BusinessType.UPDATE)
    public AjaxResult editGuideStatus(){

        int result = csOrderMemberUserInfoService.editGuideStatus();
        return AjaxResult.success(result);
    }


    /**
     * 用户退出登录
     * @param request 请求
     * @return 结果
     */
    @CSMemberUserLoginToken
    @PostMapping("/memberUserLogout")
    @Log(title = "用户退出登录", businessType = BusinessType.FORCE)
    public AjaxResult memberUserLogout(HttpServletRequest request){
        // 获取头部信息-Authorization
        String userToken = request.getHeader("M-Authorization");
        redisCache.deleteObject(CacheConstants.CS_MEMBER_LOGIN_TOKEN_KEY + RSAUtils.privateDecrypt(userToken));
        return AjaxResult.success();

    }

    /**
     * 获取通知公告列表
     */
    @CSMemberUserLoginToken
    @GetMapping("/getSysNoticeList")
    public AjaxResult getSysNoticeList()
    {
        SysNotice sysNotice = new SysNotice();
        sysNotice.setStatus("0");
        return AjaxResult.success(noticeService.selectNoticeListFormMember(sysNotice));
    }

    /**
     * 获取通知公告详情
     */
    @GetMapping("/getSysNoticeInfo")
    public AjaxResult getSysNoticeInfo(Long noticeId, Integer visitsNum)
    {
        SysNotice sysNotice = noticeService.selectNoticeById(noticeId);
        if (sysNotice == null) {
            return AjaxResult.error("通知公告不存在");
        }
        if (visitsNum != null && visitsNum == 1) {
            // 浏览量+1
            noticeService.addNoticeVisitsNum(noticeId);
        }
        return AjaxResult.success(sysNotice);
    }

    /**
     * 获取通知公告弹窗列表
     */
    @CSMemberUserLoginToken
    @GetMapping("/getSysNoticePopList")
    public AjaxResult getSysNoticePopList()
    {
        SysNotice sysNotice = new SysNotice();
        sysNotice.setStatus("0");
        return AjaxResult.success(noticeService.selectSysNoticePopList(sysNotice));
    }

    /**
     * 已读通知公告弹窗
     * @param  csMemberNotice 参数
     * @return 结果
     */
    @CSMemberUserLoginToken
    @PostMapping("/readSysNoticePop")
    @Log(title = "已读通知公告弹窗", businessType = BusinessType.UPDATE)
    public AjaxResult addOrderApply(@RequestBody @Validated({CsMemberNotice.readSysNoticePop.class}) CsMemberNotice csMemberNotice, BindingResult bindingResult){
        // 参数校验
        if (bindingResult.hasErrors()){
            return AjaxResult.allParameterErrors(bindingResult);
        }

        CsMemberNotice memberNotice = new CsMemberNotice();
        csMemberNotice.setMemberUserId(CsOrderMemberUserSecurityContext.getMemberUserId());
        memberNotice.setResId(csMemberNotice.getNoticeId());
        List<CsMemberNotice> memberNoticeList = csMemberNoticeService.selectCsMemberNoticeList(memberNotice);

        if (memberNoticeList.size() < 1) {
            memberNotice.setIsRead("1");
            csMemberNoticeService.insertCsMemberNotice(memberNotice);
        }
        return AjaxResult.success();
    }
}
