package com.leromro.core.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.Update;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leromro.core.domain.*;
import com.leromro.core.domain.vo.OrderRefundVO;
import com.leromro.core.mapper.*;
import com.leromro.core.utils.DateTimeUtil;
import org.apache.commons.math3.stat.inference.OneWayAnova;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.leromro.core.service.IOrderRefundService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单取消/退款Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-21
 */

@Service
public class OrderRefundServiceImpl extends ServiceImpl<OrderRefundMapper, OrderRefund> implements IOrderRefundService
{
    @Autowired
    private OrderRefundMapper lOrderRefundMapper;
    @Autowired
    private SecondOrdersMapper secondOrdersMapper;
    @Autowired
    private PlatformFinanceMapper platformFinanceMapper;
    @Autowired
    private ClientAccountMapper clientAccountMapper;
    @Autowired
    private VolunteerReservationTimeMapper reservationTimeMapper;
    @Autowired
    private VolunteerWorkDateMapper workDateMapper;
    @Autowired
    private MainOrdersMapper mainOrdersMapper;

    /**
     * 查询订单取消/退款
     * 
     * @param orderRefundId 订单取消/退款主键
     * @return 订单取消/退款
     */
    @Override
    public OrderRefund selectLOrderRefundByOrderRefundId(Long orderRefundId)
    {
        return lOrderRefundMapper.selectLOrderRefundByOrderRefundId(orderRefundId);
    }

    /**
     * 查询订单取消/退款列表
     * 
     * @param orderRefund 订单取消/退款
     * @return 订单取消/退款
     */
    @Override
    public List<OrderRefund> selectLOrderRefundList(OrderRefund orderRefund)
    {
        return lOrderRefundMapper.selectLOrderRefundList(orderRefund);
    }

    /**
     * 新增订单取消/退款
     * 
     * @param orderRefund 订单取消/退款
     * @return 结果
     */
    @Override
    public Boolean insertLOrderRefund(OrderRefund orderRefund)
    {
        //如果订单，一次都没完成，那就直接不用审批，直接退。
        String mainOrderId = orderRefund.getMainOrderId();

        //修改，用户账户表
        //修改，用主订单表
        //修改，小订单表
        //平台资金流水表
        //志愿者预约时间表
        //志愿者排版日期表

        orderRefund.setStatus(0);
        return this.save(orderRefund);
    }

    /**
     * 修改订单取消/退款
     * 
     * @param orderRefund 订单取消/退款
     * @return 结果
     */
    @Override
    public Boolean updateLOrderRefund(OrderRefund orderRefund)
    {
        return this.updateById(orderRefund);
    }

    /**
     * 批量删除订单取消/退款
     * 
     * @param orderRefundIds 需要删除的订单取消/退款主键
     * @return 结果
     */
    @Override
    public int deleteLOrderRefundByOrderRefundIds(Long[] orderRefundIds)
    {
        return lOrderRefundMapper.deleteLOrderRefundByOrderRefundIds(orderRefundIds);
    }

    /**
     * 删除订单取消/退款信息
     * 
     * @param orderRefundId 订单取消/退款主键
     * @return 结果
     */
    @Override
    public int deleteLOrderRefundByOrderRefundId(Long orderRefundId)
    {
        return lOrderRefundMapper.deleteLOrderRefundByOrderRefundId(orderRefundId);
    }

    /**
     * @param mainOrderId
     * @return
     */
    @Override
    public OrderRefundVO selectOrderRefundByMainOrderId(Long mainOrderId) {
        //根据mainID 取出
        OrderRefundVO refundVO = lOrderRefundMapper.selectOrderRefundInfoByMainOrderId(mainOrderId);
        refundVO.setRefundAmount(refundVO.getServiceOnePrice().multiply(new BigDecimal(refundVO.getTotalTimes()-refundVO.getFinishTimes())));

        QueryWrapper<SecondOrder> mainOrderQueryWrapper = new QueryWrapper<SecondOrder>().eq("main_order_id", mainOrderId).eq("order_status",0);
        List<SecondOrder> secondOrderList = secondOrdersMapper.selectList(mainOrderQueryWrapper);
        refundVO.setSecondOrder(secondOrderList);
        return refundVO;
    }

    /**
     * @param
     */
    @Override
    @Transactional
    public void checkOrderRefund(OrderRefund orderRefund) {
        //只能单独审核
        //更改状态 更改更新时间，更改审批状态、退款钱数、原因、图片。
        orderRefund.setUpdateTime(DateTimeUtil.getNowTime());
        lOrderRefundMapper.updateLOrderRefund(orderRefund);
        //小订单修改状态，并且
        QueryWrapper<SecondOrder> secondOrderQueryWrapper = new QueryWrapper<SecondOrder>().eq("main_order_id", orderRefund.getMainOrderId()).eq("order_status",0);
        List<SecondOrder> secondOrderList = secondOrdersMapper.selectList(secondOrderQueryWrapper);
        List<String> secondOrderIdList = secondOrderList.stream().map(SecondOrder::getSecondOrderId).collect(Collectors.toList());
        UpdateWrapper<SecondOrder> secondOrderUpdateWrapper = new UpdateWrapper<SecondOrder>().in("second_order_id", secondOrderIdList).eq("order_status",0).set("order_status", 3);
        secondOrdersMapper.update(null,secondOrderUpdateWrapper);
        //根据小订单，删除志愿者预约时间表
        List<VolunteerReservationTime> volunteerReservationTimeList = secondOrderList.stream().map(secondOrder -> {
            new VolunteerReservationTime();
            return VolunteerReservationTime.builder().volunteerId(secondOrder.getVolunteerId()).reservationDate(secondOrder.getWorkDate()).reservationTime(secondOrder.getWorkStartTime()).build();
        }).collect(Collectors.toList());
        reservationTimeMapper.deleteVolunteerReservationTimeList(volunteerReservationTimeList);
        //修改志愿者工作日的预约状态。 1先把志愿者预约状态全部设置为0 然后在查哪一天有预约，然后再把有的设置为1
        UpdateWrapper<VolunteerWorkDate> volunteerWorkDateUpdateWrapper = new UpdateWrapper<VolunteerWorkDate>().eq("volunteer_id", orderRefund.getVolunteerId()).set("has_reservation", 0);
        workDateMapper.update(null,volunteerWorkDateUpdateWrapper);
        QueryWrapper<VolunteerReservationTime> reservationTimeQueryWrapper = new QueryWrapper<VolunteerReservationTime>().eq("volunteer_id", orderRefund.getVolunteerId());
        List<VolunteerReservationTime> reservationTimes = reservationTimeMapper.selectList(reservationTimeQueryWrapper);
        List<LocalDate> reservationDate = reservationTimes.stream().map(VolunteerReservationTime::getReservationDate).collect(Collectors.toList());
        UpdateWrapper<VolunteerWorkDate> volunteerWorkDateUpdateWrapper1 = new UpdateWrapper<VolunteerWorkDate>().eq("volunteer_id", orderRefund.getVolunteerId()).in("work_date", reservationDate).set("has_reservation", 0);
        workDateMapper.update(null,volunteerWorkDateUpdateWrapper1);
        //恢复余额，以及向平台流水表更改，减少其中的流水;
        List<PlatformFinance> platformFinanceList = secondOrderList.stream().map(secondOrder -> {
            new PlatformFinance();
            return PlatformFinance.builder()
                    .changeMoney(secondOrder.getServiceOnePrice()).changeType(0).moneyType(1).sourceType(2).secondOrderId(secondOrder.getSecondOrderId()).volunteerId(secondOrder.getVolunteerId())
                    .build();
        }).collect(Collectors.toList());
        platformFinanceMapper.insertPlatformFinanceList(platformFinanceList);
        //恢复用户余额,用户账户表增加钱数
        UpdateWrapper<ClientAccount> clientAccountUpdateWrapper = new UpdateWrapper<ClientAccount>().eq("user_id", orderRefund.getUserId()).setSql("balance = balance + " + orderRefund.getRefundAmount());
        clientAccountMapper.update(null,clientAccountUpdateWrapper);
        //主订单修改状态
        UpdateWrapper<MainOrders> mainOrdersMapperUpdateWrapper = new UpdateWrapper<MainOrders>().eq("main_order_id", orderRefund.getMainOrderId()).set("order_status", 7);
        mainOrdersMapper.update(null,mainOrdersMapperUpdateWrapper);



    }
}
