package com.ruoyi.web.controller.wx;


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.domain.entity.SysUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.wx.AppletLoginForm;
import com.ruoyi.system.domain.wx.AppletSessionDTO;
import com.ruoyi.system.domain.wx.WxPayOrderReqVo;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWxPayService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @Author: tjf
 * @Date: 2024/1/17 14:10
 * @Describe:
 */
@RestController
@RequestMapping("/wx/pay")
public class WxPayController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @Resource
    private IWxPayService wxPayService;

    @ApiOperation(value = "微信预支付", notes = "微信预支付")
    @PostMapping("/createOrder")
    public AjaxResult createOrder(@RequestBody @Validated WxPayOrderReqVo req) throws Exception {
        return wxPayService.createOrder(req);
    }

    @ApiOperation(value = "微信支付回调", notes = "微信支付回调")
    @PostMapping("/payNotify")
    public AjaxResult payNotify(HttpServletRequest request) {
        //注意：回调接口需要暴露到公网上，且要放开token验证
        wxPayService.payNotify(request);
        return AjaxResult.success();
    }

    /**
     * 小程序登录
     *
     * @param form
     * @return
     */
    @PostMapping("/jsCode")
    public AjaxResult code2Session(@RequestBody AppletLoginForm form) {
        AjaxResult ajax = AjaxResult.success();
        AppletSessionDTO dto = wxPayService.jscode2Session(form);
        ajax.put(Constants.APPLETSESSIONDTO, dto);
        String phoneNumber = dto.getPhoneNumber();
        if (StringUtils.isBlank(phoneNumber)) {
            throw new BaseException("对不起，未获取到手机号");
        }
        SysUser user = userService.getByPhone(phoneNumber);
        if (user != null) {
            // 生成令牌
            String token = loginService.loginMiniPrograms(user.getUserName(), user.getPassword());
            ajax.put(Constants.TOKEN, token);
        }
        return ajax;
    }

    /**
     * 微信文本内容安全识别
     *
     * @return
     */
    @PostMapping("/msgSecCheck")
    public AjaxResult msgSecCheck(@RequestBody AppletSessionDTO dto) {
        return wxPayService.msgSecCheck(dto);
    }
}
