package com.lightinit.hsdataportal.controller.open;

import com.lightinit.hsdataportal.entity.Order;
import com.lightinit.hsdataportal.entity.UserAccount;
import com.lightinit.hsdataportal.model.LoginUser;
import com.lightinit.hsdataportal.model.ResultState;
import com.lightinit.hsdataportal.model.ResultStateCode;
import com.lightinit.hsdataportal.service.IBalancePAyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;

@Controller
@RequestMapping(value = "/open/balancePAy")
public class BalancePAyController {
    @Autowired
    private IBalancePAyService balancePAyService;

    @RequestMapping(value = "balancePAy.action/{orderNumber}")
    @ResponseBody
    public ResultState balancePAy(HttpSession session,@PathVariable String orderNumber ) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        //查询用户账户余额
        UserAccount useraccount = balancePAyService.selectBalance(loginUser.getId());
        //查询支付余额
        Order order = balancePAyService.selectBalance(orderNumber);
        ResultState resultState =new ResultState();
        if(useraccount!=null) {
            if(useraccount.getBalance().compareTo(order.getOrderAmount())>0) {
                 resultState =  balancePAyService.updateBalance(loginUser.getId(),order.getOrderAmount(),useraccount.getBalance(),order.getId());
            }else {
                resultState.setStateCode(ResultStateCode.INVALID_DATA);
                resultState.setMsg("余额不足");
            }
        }
        return resultState;
    }
    @RequestMapping(value = "toSuccess.htm")
    public ModelAndView toSuccess() {
        ModelAndView modelAndView = new ModelAndView("open/pay/feedback");
        return  modelAndView;
    }
}
