package com.yunniu.farming.webadmin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yunniu.farming.util.StringHelper;
import com.yunniu.farming.webadmin.dao.*;
import com.yunniu.farming.webadmin.model.*;
import com.yunniu.farming.webadmin.service.GroupOrderService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zyf
 * @date 2023/5/16
 * @apiNote
 */
@Service
@Slf4j
public class GroupOrderServiceImpl implements GroupOrderService {

    @Autowired
    private GroupOrderDao orderDao;
    @Autowired
    private GroupBuyDao groupBuyDao;
    @Autowired
    private OrderMainDao orderMainDao;
    @Autowired
    private OrderSubDao orderSubDao;
    @Autowired
    private OrderRefundMapper refundMapper;

    /**
     * 保存团购订单
     *
     * @param item
     * @return
     */
    @Override
    public GroupOrder addGroupOrder(OrderMain item) {
        if (item.getAreaId() == null) {
            throw new RuntimeException("缺少小区id参数");
        }
        if (item.getGroupBuyId() == null) {
            throw new RuntimeException("缺少团购id参数");
        }
        // 查询此团购活动在此小区是否有待成团的订单
        GroupOrder groupOrder = orderDao.selectOne(Wrappers.<GroupOrder>lambdaQuery()
                .eq(GroupOrder::getAreaId, item.getAreaId())
                .eq(GroupOrder::getGroupBuyId, item.getGroupBuyId())
                .eq(GroupOrder::getGroupStatus, 0)
        );
        // 查询团购活动是否存在
        GroupBuy groupBuy = groupBuyDao.selectById(item.getGroupBuyId());
        if (ObjectUtils.isEmpty(groupBuy)) {
            throw new RuntimeException("团购活动不存在");
        }
        if (groupBuy.getEndTime().before(new Date())) {
            throw new RuntimeException("该团购已失效");
        }
        if (ObjectUtils.isEmpty(groupOrder)) {
            List<Long> list = JSON.parseArray(groupBuy.getAreaIds(), Long.class);
            if (!list.contains(item.getAreaId())) {
                throw new RuntimeException("小区不存在");
            }
            GroupOrder order = new GroupOrder();
            order.setOrderCode(StringHelper.getOrderno());
            order.setAreaId(item.getAreaId());
            order.setGroupBuyId(item.getGroupBuyId());
            order.setGroupSize(1);
            order.setGroupStatus("0");
            order.setCreateTime(new Date());
            orderDao.insert(order);
            return order;
        } else {
            groupOrder.setGroupSize(groupOrder.getGroupSize() + 1);
            if (Objects.equals(groupOrder.getGroupSize(), groupBuy.getGroupSize())) {
                groupOrder.setGroupStatus("1");
                groupOrder.setSuccessTime(new Date());
            }
            return groupOrder;
        }
    }

    /**
     * 查询团购订单列表
     *
     * @param item
     * @return
     */
    @Override
    public List<GroupOrder> findPageList(GroupOrder item) {

        return orderDao.findPageList(item);
    }

    /**
     * 团购订单详情
     *
     * @param id
     * @return
     */
    @Override
    public GroupOrder findById(Long id) {
        GroupOrder order = orderDao.detailById(id);
        if (order.getSuccessTime() != null) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setSuccessTimeStr(formatter.format(order.getSuccessTime()));
        }
        return order;
    }

    /**
     * 团购订单用户信息列表
     *
     * @param item
     * @return
     */
    @Override
    public List<OrderMain> userList(OrderMain item) {
        List<OrderMain> list = orderMainDao.getPageListByGroupOrderId(item);
        return list;
    }

    /**
     * 购买商品列表
     *
     * @param item 用户列表id
     * @return
     */
    @Override
    public List<OrderSub> productList(OrderSub item) {
        return orderSubDao.getPageListByOrderMianId(item);
    }

    /**
     * 退款回调修改退款状态
     *
     * @param outRefundNo
     * @return
     */
    @Override
    public boolean updateRefundStatus(String outRefundNo) {
        OrderRefund orderRefund = refundMapper.selectOne(Wrappers.<OrderRefund>lambdaQuery()
                .eq(OrderRefund::getRefundCode, outRefundNo)
                .eq(OrderRefund::getRefundStatus, 6));
        orderRefund.setRefundStatus("5");
        int update = refundMapper.updateById(orderRefund);
        OrderMain order = orderMainDao.selectById(orderRefund.getOrderMianId());
        if (orderRefund.getPortion().equals("1")) {
            order.setIrefundstatus(OrderMain.STATUS_REFUND_SUC);
            order.setIstatus(OrderMain.STATUS_COMPLETE);
            orderMainDao.updateById(order);
        }
        List<OrderSub> orderSubs = this.orderSubDao.selectList(Wrappers.<OrderSub>lambdaQuery().eq(OrderSub::getMainid, order.getId()).eq(OrderSub::getSdef1, 2));
        orderSubs.forEach(sub -> {
            sub.setSdef1("4");
            sub.setSdef2(sub.getSdef3());
            sub.setSdef3("0");
            orderSubDao.updateById(sub);
        });
        if (update > 0) {
            return true;
        }
        return false;
    }

    /**
     * 发货
     *
     * @param id
     * @param remark
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int sendOutGoods(Long id, String remark) {
        GroupOrder order = orderDao.selectById(id);
        order.setGroupStatus("2");
        order.setRemark(remark);
        int update = orderDao.updateById(order);
        if (update > 0) {
            OrderMain orderMain = new OrderMain();
            orderMain.setIstatus(OrderMain.STATUS_WAITING);
            orderMain.setGroupOrderId(id);
            orderMainDao.update(orderMain, Wrappers.<OrderMain>lambdaUpdate()
                    .set(OrderMain::getIstatus, OrderMain.STATUS_WAITING)
                    .eq(OrderMain::getGroupOrderId, id));
        }
        return update;
    }

    /**
     * 完成
     *
     * @param id
     * @return
     */
    @Override
    public int successOrder(Long id) {
        GroupOrder order = orderDao.selectById(id);
        order.setGroupStatus("3");
        return orderDao.updateById(order);
    }

    /**
     * 支付成功后判断团购订单是否成团
     *
     * @param curOrder
     */
    public void isSuccess(OrderMain curOrder) {
        GroupBuy groupBuy = orderDao.getGroupBuy(curOrder.getGroupOrderId());
        Long count = orderMainDao.selectCount(Wrappers.<OrderMain>lambdaQuery()
                .eq(OrderMain::getGroupOrderId, curOrder.getGroupOrderId())
                .eq(OrderMain::getIpaystatus, 1)
                .isNull(OrderMain::getIrefundstatus));

        if (groupBuy.getGroupSize() <= count) {
            orderDao.updateStatus(curOrder.getGroupOrderId());
        }

    }
}
