package com.lightinit.hsdataportal.impl;

import com.lightinit.hsdataportal.dictionary.DicOrderState;
import com.lightinit.hsdataportal.entity.Order;
import com.lightinit.hsdataportal.entity.OrderExample;
import com.lightinit.hsdataportal.entity.UserAccount;
import com.lightinit.hsdataportal.entity.UserAccountExample;
import com.lightinit.hsdataportal.mapper.OrderMapper;
import com.lightinit.hsdataportal.mapper.UserAccountMapper;
import com.lightinit.hsdataportal.model.ResultState;
import com.lightinit.hsdataportal.model.ResultStateCode;
import com.lightinit.hsdataportal.service.IBalancePAyService;
import com.lightinit.hsdataportal.spring.DynamicDataContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class BalancePAyServiceImpl implements IBalancePAyService {
    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public UserAccount selectBalance(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return userAccountMapper.selectByPrimaryKey(id);
    }

    @Override
    public ResultState updateBalance(Long id, BigDecimal balance,BigDecimal userBalance,Long orderId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState resultState = new ResultState();
        int result = 0;
        UserAccount userAccount = new UserAccount();
        userAccount.setId(id);
        userAccount.setBalance(userBalance.subtract(balance));
//        UserAccountExample example =new UserAccountExample();
//        UserAccountExample.Criteria criteria = example.createCriteria();
//        criteria.andIdNotEqualTo(id);
        result = userAccountMapper.updateByPrimaryKeySelective(userAccount);
        Order order = new Order();
        order.setId(orderId);
        order.setOrderState(DicOrderState.PAY_SUCCESS);
        orderMapper.updateByPrimaryKeySelective(order);
        if(!(result>0)) {
            resultState.setMsg("余额支付失败");
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
        }
        resultState.setData(id);
        return resultState;
    }

    @Override
    public Order selectBalance(String orderNumber) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        OrderExample bizOrderExample = new OrderExample();
        bizOrderExample.createCriteria().andOrderNumberEqualTo(orderNumber);
        List<Order> list = orderMapper.selectByExample(bizOrderExample);
        if(list==null||list.size()!=1){
            return null;
        }
        return list.get(0);
    }
}
