package com.willalp.canteen.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.canteen.domain.HsCanteenOrder;
import com.willalp.canteen.service.IIntegralSer2;
import com.willalp.common.enums.RechargeEnum;
import com.willalp.common.enums.ReturnEnum;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.SecurityUtils;
import com.willalp.canteen.mapper.HsCanteenOrderMapper;
import com.willalp.canteen.service.IHsCanteenOrderService;
import com.willalp.integral.domain.Integral;
import com.willalp.integral.mapper.IntegralMapper;
import com.willalp.system.domain.SysCardInfo;
import com.willalp.system.domain.SysUserOrganization;
import com.willalp.system.mapper.SysCardInfoMapper;
import com.willalp.system.mapper.SysUserOrganizationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IntegralSer2Impl extends ServiceImpl<IntegralMapper, Integral> implements IIntegralSer2 {

    @Autowired
    SysUserOrganizationMapper sysUserOrganizationMapper;

    @Autowired
    SysCardInfoMapper sysCardInfoMapper;

    @Autowired
    IntegralMapper integralMapper;

    @Autowired
    HsCanteenOrderMapper hsCanteenOrderMapper;

    @Autowired
    IHsCanteenOrderService hsCanteenOrderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveInfo(Integral integral) {
//        List<SysUserOrganization> list = sysUserOrganizationMapper.queryOrganizationByLoginName(SecurityUtils.getUsername());
//        if (!list.isEmpty()) {
//            list = list.stream().filter(e -> e.getIsDefault() != null && e.getIsDefault() == 1).collect(Collectors.toList());
//            if (!list.isEmpty()) {
//                integral.setOrganizationCode(list.get(0).getOrganizationCode());
//            }
//        }
        SysCardInfo cardInfo = new SysCardInfo();
        cardInfo.setUserId(integral.getLoginName());
        List<SysCardInfo> cardInfoList = sysCardInfoMapper.selectSysCardInfoList(cardInfo);
        if (!cardInfoList.isEmpty()) {
            integral.setCardNumber(cardInfoList.get(0).getCardCode());
            integral.setCardName(cardInfoList.get(0).getCardUsername());
        }

        while (true) {
            String idStr = IdWorker.getIdStr();
            Integral byId = integralMapper.selectById(idStr);
            if (null == byId) {
                integral.setId(idStr);
                break;
            }
        }
        integral.setIsDelete(0);
        integral.setRechargeTime(DateUtils.getNowDate());
        integral.setRechargeId(SecurityUtils.getLoginUser().getUserId());
        //账户
        SysUserOrganization organization = new SysUserOrganization();
        organization.setLoginName(integral.getLoginName());
        organization.setOrganizationCode(integral.getOrganizationCode());
        List<SysUserOrganization> organs = sysUserOrganizationMapper.selectSysUserOrganizationList(organization);
        if (organs.size() > 0) {
            organization = organs.get(0);
        } else {
            throw new BaseException("当前用户不存在机构权限");
        }
        //账户增加余额
        if (integral.getMoneyType() == Integer.valueOf(RechargeEnum.ORGANRECHARGE.getValue())
                || integral.getMoneyType() == Integer.valueOf(RechargeEnum.PERSONRECHARGE.getValue())) {
            organization.setIntegral(organization.getIntegral().add(integral.getRechargeIntegral()));
        }else if (integral.getMoneyType() == Integer.valueOf(RechargeEnum.KEEPRECHARGE.getValue())){//记账
            organization.setQuota(organization.getQuota().add(integral.getRechargeIntegral()));
        }else if (integral.getMoneyType() == Integer.valueOf(RechargeEnum.DEPOSITRECHARGE.getValue())){//押金
            organization.setDeposit(organization.getDeposit().add(integral.getRechargeIntegral()));
        }else if(integral.getMoneyType() == Integer.valueOf(ReturnEnum.RETURN.getValue())){//余额退还
            if (organization.getIntegral().compareTo(integral.getRechargeIntegral()) < 0){
                throw new BaseException("余额不足");
            }
            organization.setIntegral(organization.getIntegral().subtract(integral.getRechargeIntegral()));
            integral.setRechargeIntegral(integral.getRechargeIntegral().negate());
        }else if (integral.getMoneyType() == Integer.valueOf(ReturnEnum.KEEPRETURN.getValue())){//记账额度退还
            if (organization.getQuota().compareTo(integral.getRechargeIntegral()) < 0){
                throw  new BaseException("记账额度不足");
            }
            organization.setQuota(organization.getQuota().subtract(integral.getRechargeIntegral()));
            integral.setRechargeIntegral(integral.getRechargeIntegral().negate());
        }else if (integral.getMoneyType() == Integer.valueOf(ReturnEnum.DEPOSITRETURN.getValue())){//押金
            if (organization.getDeposit().compareTo(integral.getRechargeIntegral()) < 0){
                throw new BaseException("押金不足");
            }
            organization.setDeposit(organization.getDeposit().subtract(integral.getRechargeIntegral()));
            integral.setRechargeIntegral(integral.getRechargeIntegral().negate());
        }else if (integral.getMoneyType() == Integer.valueOf(5)){//因错退还
            HsCanteenOrder order = new HsCanteenOrder();
            order.setOrderNumber(integral.getOrderNumber());
            order.setJgid(integral.getOrganizationCode());
            List<HsCanteenOrder> orders = hsCanteenOrderMapper.selectHsCanteenOrderList(order);
            orders = orders.stream().filter(o -> o.getZfbz() ==2).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(orders)){
                throw new BaseException("订单信息不存在");
            }
            order = orders.get(0);
            order.setOrderTotal(integral.getRechargeIntegral());
            order.setOrderId(IdWorker.getIdStr());
            hsCanteenOrderService.checkOrderTotal(order);
            order.setZfbz(3);
            order.setPaytime(new Date());
            hsCanteenOrderService.save(order);
        }
        sysUserOrganizationMapper.updateById(organization);
        return integralMapper.insert(integral);
    }
}
