package com.willalp.canteen.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.canteen.domain.HsGiftOrder;
import com.willalp.canteen.domain.HsGiftOrderDetail;
import com.willalp.canteen.mapper.HsGiftOrderMapper;
import com.willalp.canteen.service.IHsGiftOrderDetailService;
import com.willalp.canteen.service.IHsGiftOrderService;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.StringUtils;
import com.willalp.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 食堂订单Service业务层处理
 *
 * @author songyu
 * @date 2021-12-03
 */
@Service
public class HsGiftOrderServiceImpl extends ServiceImpl<HsGiftOrderMapper, HsGiftOrder> implements IHsGiftOrderService {

    @Resource
    private HsGiftOrderMapper hsGiftOrderMapper;

    @Resource
    private IHsGiftOrderDetailService codService;

    @Autowired
    ISysUserService sysUserService;

    /**
     * 查询食堂订单列表
     *
     * @param hsGiftOrder 食堂订单
     * @return 食堂订单
     */
    @Override
    public List<HsGiftOrder> selectHsCanteenOrderList(HsGiftOrder hsGiftOrder) {
        return hsGiftOrderMapper.selectHsCanteenOrderList(hsGiftOrder).stream().sorted(Comparator.comparing(HsGiftOrder::getPaytime).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<HsGiftOrder> exportSelectGiftOrderList(HsGiftOrder hsGiftOrder) {
        List<HsGiftOrder> giftOrders = hsGiftOrderMapper.selectHsCanteenOrderList(hsGiftOrder).stream().sorted(Comparator.comparing(HsGiftOrder::getPaytime).reversed()).collect(Collectors.toList());
        List<HsGiftOrderDetail> orderResps = codService.getBaseMapper().selectList(null);
        giftOrders.forEach(order -> {
            String orderNumber = order.getOrderNumber();
            if (StringUtils.isNotBlank(orderNumber)) {
                List<HsGiftOrderDetail> collect = orderResps.stream().filter(item ->
                        orderNumber.equals(item.getOrderNumber()) && StringUtils.isNotBlank(item.getGiftName()) && 0 != item.getAmount()
                ).collect(Collectors.toList());
                if (collect.size() > 0) {
                    StringBuilder gifts = new StringBuilder();
                    for (HsGiftOrderDetail detail : collect) {
                        gifts.append("【").append(detail.getGiftName()).append(" * ").append(detail.getAmount()).append("】");
                    }
                    order.setGiftsAndNum(gifts.toString());
                }
            }
        });
        return giftOrders;
    }

    /**
     * 首页金额总额
     *
     * @param hsGiftOrder
     * @return
     */
    @Override
    public String getSumpay(HsGiftOrder hsGiftOrder) {
        return hsGiftOrderMapper.getSumpay(hsGiftOrder);
    }

    /**
     * 作废食堂订单
     *
     * @param hsGiftOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getBack(HsGiftOrder hsGiftOrder) {
        BigDecimal total = hsGiftOrder.getOrderTotal();
        if (hsGiftOrder.getZfbz() == 1) {
            return AjaxResult.error("该订单已作废，不可重复作废");
        }
        if (StrUtil.isBlank(hsGiftOrder.getUserNumber())) {
            return AjaxResult.error("用户编号为空，请联系管理员");
        }
        if (hsGiftOrder.getZfbz() == 3) {
            return AjaxResult.error("因错退还订单不可作废");
        }
        try {
/*            SysUserOrganization user = new SysUserOrganization();
            user.setLoginName(hsGiftOrder.getUserNumber());
            user.setOrganizationCode(hsGiftOrder.getJgid());
            List<SysUserOrganization> userList = sysUserOrganizationService.selectSysUserOrganizationList(user);
            if (userList.size() == 0) {
                return AjaxResult.error("用户信息不存在");
            }
            user = userList.get(0);
            //消费记录
            Integral integral = new Integral();
            integral.setId(IdWorker.getIdStr());//积分主键
            integral.setMoneyType(Integer.valueOf(ConsumeChangeEnum.REFUND.getValue()));//退还
            integral.setRechargeEquipmentCode(hsGiftOrder.getDeviceNumber());//设备编号
            integral.setRechargeEquipmentName(hsGiftOrder.getDeviceName());//设备名称
            integral.setLoginName(hsGiftOrder.getUserNumber());//账号编号
            integral.setRechargeIntegral(hsGiftOrder.getOrderTotal());//积分(负数)
            integral.setIsDelete(0);//有效标志
            integral.setNickName(user.getNickName());
            integral.setOrganizationCode(hsGiftOrder.getJgid());//机构代码
            integral.setOrderNumber(hsGiftOrder.getOrderNumber());
            integral.setRechargeId(SecurityUtils.getLoginUser().getUserId());
            integral.setRechargeTime(DateUtils.getNowDate());
            if (hsGiftOrder.getConsumeSign() == 0) {//积分
                user.setIntegral(user.getIntegral().add(hsGiftOrder.getOrderTotal()));
            } else {//记账额度
                user.setQuota(user.getQuota().add(hsGiftOrder.getOrderTotal()));
            }
            integralService.save(integral);
            sysUserOrganizationService.updateById(user);
            hsGiftOrderMapper.updateCanteenOrderZfpb(hsGiftOrder.getJgid(), hsGiftOrder.getOrderId());//更新订单主表作废判别*/
        } catch (Exception e) {
            throw new BaseException("作废失败");
        }
        return AjaxResult.success();
    }

    @Override
    public void checkOrderTotal(HsGiftOrder hsGiftOrder) {
        if (hsGiftOrder.getZfbz() == 1) {
            throw new BaseException("该订单已作废，不可退还");
        } else if (hsGiftOrder.getZfbz() == 3) {
            throw new BaseException("该订单为因错退还，不可再次退还");
        }
/*        List<Map<String, Object>> zforderlist = hsGiftOrderMapper.checkSfzf(hsGiftOrder);
        BigDecimal totalpay = new BigDecimal(zforderlist.get(0).get("order_total") + "");
        BigDecimal partpay = BigDecimal.ZERO;
        if (zforderlist.get(1).size() > 0) {
            partpay = new BigDecimal(zforderlist.get(1).get("order_total") + "").add(hsGiftOrder.getOrderTotal());
        }
        if (totalpay.compareTo(partpay) < 0) {
            throw new BaseException("已超出最大退还金额，不可退还");
        }
        //积分退还
        SysUserOrganization user = new SysUserOrganization();
        user.setLoginName(hsGiftOrder.getUserNumber());
        user.setOrganizationCode(hsGiftOrder.getJgid());
        List<SysUserOrganization> userList = sysUserOrganizationService.selectSysUserOrganizationList(user);
        if (userList.size() == 0) {
            throw new BaseException("用户信息不存在");
        }
        user = userList.get(0);
        user.setIntegral(user.getIntegral().add(hsGiftOrder.getOrderTotal()));
        sysUserOrganizationService.updateById(user);*/
    }

    /**
     * 近一月订单量
     *
     * @param hsGiftOrder
     * @return
     */
    @Override
    public List<HsGiftOrder> selectHsCanteenOrderLists(HsGiftOrder hsGiftOrder) {
        return hsGiftOrderMapper.selectHsCanteenOrderLists(hsGiftOrder);
    }

    @Override
    public String getSumOrderNum(HsGiftOrder hsGiftOrder) {
        return hsGiftOrderMapper.getSumOrderNum(hsGiftOrder);
    }
}
