package com.leromro.core.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leromro.common.utils.SecurityUtils;
import com.leromro.core.domain.*;
import com.leromro.core.domain.dto.OrderRequestDTO;
import com.leromro.core.mapper.MainOrdersMapper;
import com.leromro.core.mapper.SecondOrdersMapper;
import com.leromro.core.mapper.ClientBalanceMapper;
import com.leromro.core.service.IMainOrderService;
import com.leromro.core.utils.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class MainOrderServiceImpl extends ServiceImpl<MainOrdersMapper, MainOrders> implements IMainOrderService{
    @Autowired
    private MainOrdersMapper mainOrdersMapper;
    @Autowired
    private SecondOrdersMapper secondOrdersMapper;
    @Autowired
    private ClientBalanceMapper clientBalanceMapper;
    @Autowired
    private VolunteerWorkDateServiceImpl workDateService;
    @Autowired
    private VolunteerReservationTimeServiceImpl volunteerReservationTimeService;
    @Autowired
    private Snowflake snowflake;

    /**
     * @param userId
     * @return
     */
    @Override
    public List<MainOrders> selectByUserId(Integer orderStatus,Long userId) {
        QueryWrapper<MainOrders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).eq("is_delete",0);
        if (orderStatus != null){
            wrapper.eq("order_status",orderStatus);
        }
        List<MainOrders> orders = mainOrdersMapper.selectList(wrapper);
        return  orders;
    }



    /**
     * @param orderRequest
     */
    @Override
    public void createOrders(OrderRequestDTO orderRequest) {
        MainOrders orders = orderRequest.getOrders();
        List<VolunteerWorkDate> workDateList = orderRequest.getWorkDateList();
        Long userId = SecurityUtils.getUserId();
        // 查看余额够不够  修改用户余额表
        BigDecimal totalPrice = orders.getServiceTotalPrice();
        ClientAccount clientAccount = clientBalanceMapper.selectBalanceByuserID(userId);
        BigDecimal balanceOld = clientAccount.getBalance();
        int compared = totalPrice.compareTo(balanceOld);
        if (compared>0){
            throw new RuntimeException("余额不足,支付失败");
        }else {
            BigDecimal balanceNew = balanceOld.subtract(totalPrice);
            clientAccount.setBalance(balanceNew);
            clientBalanceMapper.updateClientBalance(clientAccount);
        }
        //创建订单主表
        long orderId = snowflake.nextId();
        orders.setMainOrderId(String.valueOf(orderId));
        orders.setOrderStatus(1);
        orders.setFinishTimes(0L);
        orders.setPaymentMethod(0);
        orders.setUserId(userId);
        orders.setCreateTime(DateTimeUtil.getNowTime());
        mainOrdersMapper.insertMainOrders(orders);

        //修改志愿者预约时间表
        VolunteerReservationTime reservationTime =VolunteerReservationTime.builder().volunteerId(orders.getVolunteerId()).reservationTime(orders.getStartTime()).clientId(userId).build();
        reservationTime.setRemark(orders.getRemark());
        List<VolunteerReservationTime> reservationTimes = new ArrayList<>();

        //新增按次数的小订单表
        SecondOrder secondOrder = SecondOrder.builder().mainOrderId(String.valueOf(orderId)).volunteerId(orders.getVolunteerId()).
                serviceCategory(orders.getServiceCategory()).workStartTime(orders.getStartTime())
                .serviceDuration(orders.getServiceDuration()).addressId(orders.getAddressId()).serviceOnePrice(orders.getServiceOnePrice()).orderStatus(0).serviceType(orders.getServiceType()).serviceSubject(orders.getServiceSubject()).build();
        secondOrder.setRemark(orders.getRemark());
        List<SecondOrder> secondOrderList = new ArrayList<>();
        //修改志愿者预约时间表以及新增志愿者预约时间
        long number = 1;
        for (VolunteerWorkDate workDate : workDateList) {
            secondOrder.setWorkDate(workDate.getWorkDate());
            secondOrder.setWorkNumber(number);
            secondOrderList.add(secondOrder);
            reservationTime.setReservationDate(workDate.getWorkDate());
            reservationTimes.add(reservationTime);
            number++;
        }
        secondOrdersMapper.insertList(secondOrderList);
        volunteerReservationTimeService.insertVolunteerReservationTimeList(reservationTimes);
        //修改志愿者排班日期表
        workDateService.updateVolunteerWorkDate(workDateList);
    }


}
