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.domain.vo.MainOrdersVO;
import com.leromro.core.domain.vo.webMainOrderListVO;
import com.leromro.core.mapper.*;
import com.leromro.core.service.IMainOrderService;
import com.leromro.core.utils.DateTimeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalTime;
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 ClientAccountMapper clientAccountMapper;
    @Autowired
    private VolunteerWorkDateMapper workDateMapper;
    @Autowired
    private VolunteerReservationTimeServiceImpl volunteerReservationTimeService;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    private PlatformFinanceMapper platformFinanceMapper;

    /**
     * @param userId
     * @return
     */
    @Override
    public List<MainOrdersVO> selectByUserId(Integer orderStatus, Long userId) {

        List<MainOrdersVO> ordersVOS = mainOrdersMapper.selectByUserId(orderStatus,userId);
        return  ordersVOS;
    }



    /**
     * @param orderRequest
     */
    @Override
    /*@Transactional*/
    public void createOrders(OrderRequestDTO orderRequest) {
        MainOrders orders = orderRequest.getOrders();
        List<VolunteerWorkDate> workDateList = orderRequest.getWorkDateList();
        Long userId = SecurityUtils.getUserId();
        // 查看余额够不够  修改用户余额表
        BigDecimal totalPrice = orders.getServiceTotalPrice();
        ClientAccount clientAccount = clientAccountMapper.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);
            clientAccountMapper.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()).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()).serviceSubject(orders.getServiceSubject()).serviceType(orders.getServiceType())
                .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<>();
        //添加平台
        //创建平台流水模板
        PlatformFinance platformFinance =  PlatformFinance.builder().changeMoney(orders.getServiceOnePrice()).changeType(1).moneyType(1)
                .sourceType(1).volunteerId(orders.getVolunteerId()).build();
        platformFinance.setCreateTime(DateTimeUtil.getNowTime());
        List<PlatformFinance> platformFinanceList = new ArrayList<>();
        //workDate 去计算 更新有预约 为1
        //修改志愿者预约时间表以及新增志愿者预约时间
        long number = 1;
        //
        List<VolunteerWorkDate> volunteerWorkDates = new ArrayList<>();
        //
        for (VolunteerWorkDate workDate : workDateList) {
            //向secondOrder中添加数据
            long secondOrderIdL = snowflake.nextId();
            SecondOrder secondOrder1 = new SecondOrder();
            BeanUtils.copyProperties(secondOrder,secondOrder1);
            secondOrder1.setWorkDate(workDate.getWorkDate());
            secondOrder1.setWorkStartTime(workDate.getWorkStartTime());
            secondOrder1.setWorkEndTime(workDate.getWorkStartTime().plus(Duration.ofMinutes(orders.getServiceDuration())));
            secondOrder1.setWorkNumber(number);
            secondOrder1.setSecondOrderId(String.valueOf(secondOrderIdL));
            secondOrderList.add(secondOrder1);
            //向平台流水中添加数据
            PlatformFinance platformFinance1 = new PlatformFinance();
            BeanUtils.copyProperties(platformFinance,platformFinance1);
            platformFinance1.setSecondOrderId(String.valueOf(secondOrderIdL));
            platformFinanceList.add(platformFinance1);
            //向志愿者预约时间表中添加数据
            VolunteerReservationTime reservationTime1 = new VolunteerReservationTime();
            BeanUtils.copyProperties(reservationTime,reservationTime1);
            reservationTime1.setReservationDate(workDate.getWorkDate());
            reservationTime1.setReservationTime(workDate.getWorkStartTime());
            reservationTimes.add(reservationTime1);
            number++;
            workDate.setVolunteerId(orders.getVolunteerId());
            LocalTime workEndTime = workDate.getWorkStartTime().plus(Duration.ofHours(orders.getServiceDuration()));
            workDate.setWorkEndTime(workEndTime);
            workDate.setHasReservation(1);
            workDate.setUpdateTime(DateTimeUtil.getNowTime());
            volunteerWorkDates.add(workDate);
        }
        //新增公司资金流水表N个
        platformFinanceMapper.insertPlatformFinanceList(platformFinanceList);
        //新增志愿者订单小表N个
        secondOrdersMapper.insertList(secondOrderList);
        //新增志愿者预约时间表
        volunteerReservationTimeService.insertVolunteerReservationTimeList(reservationTimes);

      //修改志愿者排班日期表
        workDateMapper.updateVolunteerWorkDatebyVolunteerId(volunteerWorkDates);

    }

    @Override
    public List<webMainOrderListVO> webMainOrderList(MainOrdersVO mainOrdersVO) {
        List<webMainOrderListVO> vos = baseMapper.webMainOrderList(mainOrdersVO);
        return vos;
    }


}
