/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.user.api.controller;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.UserExtension;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.PayManagerService;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.user.comment.model.UserLevel;
import com.yami.shop.user.comment.model.UserLevelLog;
import com.yami.shop.user.comment.param.PayUserLevelParam;
import com.yami.shop.user.comment.service.UserLevelLogService;
import com.yami.shop.user.comment.service.UserLevelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
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.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @author LHD on 2020/03/02.
 */
@Api(tags = "会员购买接口")
@RestController
@RequestMapping("/p/level")
@AllArgsConstructor
public class PayLevelController {

    /**
     * 会员信息
     */
    private final UserLevelService userLevelService;
    private final UserExtensionService userExtensionService;
    private final ApplicationContext applicationContext;
    private final Snowflake snowflake;
    private final UserLevelLogService userLevelLogService;
    private final PayManagerService payManagerService;
    /**
     * 会员支付接口
     */
    @PostMapping("/payLevel")
    @ApiOperation(value = "根据会员等级进行支付", notes = "根据会员等级进行支付")
    @SneakyThrows
    public ResponseEntity<?> payVip(HttpServletResponse httpResponse, @RequestBody PayUserLevelParam payCardParam) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.isEnabled()) {
            throw new GlobalException("您已被禁用，不能购买，请联系平台客服");
        }

        String openId = user.getBizUserId();
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>()
                                            .eq(UserExtension::getUserId, user.getUserId()));
        UserLevel userLevel = userLevelService.getById(payCardParam.getId());

        //如果会员等级为空
        if(userLevel == null || !Objects.equals(userLevel.getLevelType(),1)) {
            throw new GlobalException("会员等级不存在或当前等级不为付费会员等级！");
        }

        if(Objects.equals(userExtension.getLevelType(),1) && userExtension.getLevel() > userLevel.getLevel()){
            throw new GlobalException("用户无法在会员期间购买低等级会员！");
        }

        if(userExtension.getGrowth() < userLevel.getNeedGrowth()){
            throw new GlobalException("用户成长值不足，无法购买！");
        }




        // 使用雪花算法生成支付单号
        String payNo = String.valueOf(snowflake.nextId());
        Date now = new Date();
        //生成等级日志
        UserLevelLog userLevelLog = new UserLevelLog();
        userLevelLog.setGiftTime(now);
        userLevelLog.setCreateTime(now);
        userLevelLog.setLevel(userLevel.getLevel());
        userLevelLog.setState(0);
        userLevelLog.setPayNo(payNo);
        userLevelLog.setIsPayed(0);
        userLevelLog.setUserId(userExtension.getUserId());
        //插入一条等级日志
        userLevelLogService.save(userLevelLog);

        PayInfoDto payInfo = new PayInfoDto();
        payInfo.setBody("会员等级购买");
        payInfo.setPayAmount(userLevel.getNeedAmount());
        payInfo.setPayNo(payNo);
        payInfo.setBizUserId(openId);
        payInfo.setPayType(payCardParam.getPayType());
        payInfo.setApiNoticeUrl("/notice/levelPay/levelPayCallback/" + payCardParam.getPayType());
        payInfo.setReturnUrl(payCardParam.getReturnUrl());



        return payManagerService.doPay(httpResponse, payInfo);

//       //TODO 支付成功测试
//        userLevelService.paySuccess(payNo);
//        return ResponseEntity.ok().build();
    }

}
