package com.leromro.core.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.WebMainOrdersInfoVO;
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 org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@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 VolunteerInfoMapper volunteerInfoMapper;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    private PlatformFinanceMapper platformFinanceMapper;
    @Autowired
    private AddressMapper addressMapper;

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

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



    /**
     * @param orderRequest
     */
    @Override
    @Transactional
    /*@Transactional*/
    public void createOrders(OrderRequestDTO orderRequest) {
        MainOrders orders = orderRequest.getOrders();
        List<VolunteerWorkDate> workDateList = orderRequest.getWorkDateList();
        Long userId = SecurityUtils.getUserId();
        long orderId = snowflake.nextId();


        //获取志愿者信息，同时服务时长和价格也都在志愿者id中进行获取
        VolunteerInfo info = volunteerInfoMapper.selectOne(new LambdaQueryWrapper<VolunteerInfo>()
                .eq(VolunteerInfo::getVolunteerInfoId, orders.getVolunteerInfoId()));
        BigDecimal serviceOnePrice = info.getBusinessPrice();
        Integer businessDurationMin = info.getBusinessDuration();
        String seconderStatus;
        // 判断支付方式，余额扣减余额。 1 余额 2 微信
        if (orders.getPaymentMethod().equals("1")){
            // 查看余额够不够  修改用户余额表
            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);
            }
            // 余额足够 直接支付 订单状态为已支付
            orders.setOrderStatus("1");
            seconderStatus = "1";

        }else if (orders.getPaymentMethod().equals("2")){
            //待完成 微信支付
            System.out.println("微信支付");

            //设置订单支付状态
            orders.setOrderStatus("0");
             seconderStatus = "0";

        }else {
            throw new RuntimeException("支付方式错误");
        }
        //创建订单主表
        //把地址信息也添加到数据里面
        Address address = addressMapper.selectAddressByAddressId(orders.getAddressId());
        //地址拼接信息+经纬度
        String OrderAddress = String.join("",
                Objects.toString(address.getProvinceName(), ""),
                Objects.toString(address.getCityName(), ""),
                Objects.toString(address.getDistrictName(), ""),
                Objects.toString(address.getAddress(), ""));
        orders.setAddressLongitude(address.getLongitude());
        orders.setAddressLatitude(address.getLatitude());
        orders.setAddress(OrderAddress);
        orders.setClientName(address.getName());
        orders.setClientTelephone(address.getTelephone());
        orders.setProvinceName(address.getProvinceName());
        orders.setProvinceCode(address.getProvinceCode());
        orders.setCityName(address.getCityName());
        orders.setCityCode(address.getCityCode());
        orders.setDistrictName(address.getDistrictName());
        orders.setDistrictCode(address.getDistrictCode());

        orders.setMainOrderId(orderId);
        orders.setServiceDuration(info.getBusinessDuration());
        orders.setFinishTimes(0L);
        orders.setUserId(userId);
        orders.setCreateTime(DateTimeUtil.getNowTime());
        orders.setServiceOnePrice(serviceOnePrice);
        orders.setServiceDuration(businessDurationMin);
        this.save(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(orderId).volunteerId(orders.getVolunteerId()).
                serviceCategory(orders.getServiceCategory()).serviceDuration(orders.getServiceDuration()).addressId(orders.getAddressId())
                .serviceOnePrice(orders.getServiceOnePrice()).volunteerInfoId(orders.getVolunteerInfoId()).orderStatus(seconderStatus)
                .provinceCode(address.getProvinceCode()).cityCode(address.getCityCode()).districtCode(address.getDistrictCode())
                .provinceName(address.getProvinceName()).cityName(address.getCityName()).districtName(address.getDistrictName())
                .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(secondOrderIdL);
            secondOrderList.add(secondOrder1);
            //向平台流水中添加数据
            PlatformFinance platformFinance1 = new PlatformFinance();
            BeanUtils.copyProperties(platformFinance,platformFinance1);
            platformFinance1.setSecondOrderId(secondOrderIdL);
            platformFinanceList.add(platformFinance1);
            //向志愿者预约时间表中添加数据
            int parts = businessDurationMin/30;
            if (businessDurationMin % 30!=0){
                parts++;
            }
            LocalTime workStartTime = workDate.getWorkStartTime();
            for (int i = 0; i < parts; i++) {
                VolunteerReservationTime reservationTime1 = new VolunteerReservationTime();
                BeanUtils.copyProperties(reservationTime,reservationTime1);
                reservationTime1.setReservationDate(workDate.getWorkDate());
                reservationTime1.setReservationTime(workStartTime);
                reservationTimes.add(reservationTime1);
                workStartTime = workStartTime.plusMinutes(30);
            }
            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;
    }

    /**
     * @param secondOrderId
     */
    @Override
    public void startService(Long secondOrderId) {
        mainOrdersMapper.startService(secondOrderId);
    }

    /**
     * @param mainOrderId
     * @return
     */
    @Override
    public WebMainOrdersInfoVO selectWebMainOrderInfoVO(Long mainOrderId) {
        WebMainOrdersInfoVO webMainOrderInfoVO = mainOrdersMapper.selectWebMainOrderInfoVO(mainOrderId);
        return webMainOrderInfoVO;
    }


}
