package com.fs.app.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.R;
import com.fs.common.utils.IpUtil;
import com.fs.wx.miniapp.config.WxMaConfiguration;
import com.fs.wx.miniapp.config.WxMaProperties;
import com.fs.store.domain.FsUser;
import com.fs.store.param.FsStorePaymentPayParam;
import com.fs.store.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Api("支付接口")
@RestController
@RequestMapping("/app/payment")
public class PaymentController extends AppBaseController {
    @Autowired
    private WxMaProperties properties;
    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    private IFsStorePaymentService paymentService;
    @Autowired
    private IFsUserService userService;
    @ApiOperation("支付")
    @PostMapping("/payment")
    @RepeatSubmit
    public R payment(@Validated @RequestBody FsStorePaymentPayParam payment, HttpServletRequest request){
        final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
        try {
            String ip = IpUtil.getRequestIp();
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(payment.getCode());
            FsUser user=userService.selectFsUserByMaOpenId(session.getOpenid());
            if(user==null){
                //创建
                user=new FsUser();
                user.setUsername("");
                user.setNickname("微信用户");
                user.setStatus(1);
                user.setMaOpenId(session.getOpenid());
                user.setUnionId(session.getUnionid());
                user.setIsWeixinAuth(0);
                user.setLastIp(ip);
                user.setCreateTime(new Date());
                userService.insertFsUser(user);
            }
            payment.setUserId(user.getUserId());
            return paymentService.payment(payment);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }



    }

}
