package com.leromro.core.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leromro.common.core.domain.AjaxResult;
import com.leromro.common.utils.DateUtils;
import com.leromro.common.utils.SecurityUtils;
import com.leromro.core.domain.MainOrders;
import com.leromro.core.domain.OrderFrozenFunds;
import com.leromro.core.domain.SecondOrder;
import com.leromro.core.domain.VolunteerAccount;
import com.leromro.core.domain.dto.UserOrderReviewDTO;
import com.leromro.core.domain.vo.VolunteerOrdersVO;
import com.leromro.core.mapper.MainOrdersMapper;
import com.leromro.core.mapper.OrderFrozenFundsMapper;
import com.leromro.core.mapper.SecondOrdersMapper;
import com.leromro.core.mapper.VolunteerAccountMapper;
import com.leromro.core.service.ISecondOrderService;
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.Date;
import java.util.List;

@Service
public class SecondOrdersServiceImpl extends ServiceImpl<SecondOrdersMapper, SecondOrder> implements ISecondOrderService {
    @Autowired
    private SecondOrdersMapper secondOrdersMapper;
    @Autowired
    private OrderFrozenFundsMapper orderFrozenFundsMapper;
    @Autowired
    private VolunteerAccountMapper volunteerAccountMapper;
    @Autowired
    private MainOrdersMapper mainOrdersMapper;

    /**
     * @param orderStatus
     * @return
     */
    @Override
    public List<VolunteerOrdersVO> selectOrderList(Long userId,Long orderStatus) {
        return secondOrdersMapper.selectVolunteerOrder( userId,orderStatus);
    }

    /**
     * @return
     */
    @Override
    public AjaxResult volunteerFinishWork(SecondOrder secondOrder) {

        String secondOrderId = secondOrder.getSecondOrderId();
        QueryWrapper<SecondOrder> SecondOrderWrapper = new QueryWrapper<SecondOrder>().eq("second_order_id", secondOrderId);
        SecondOrder secondOrderInfo = secondOrdersMapper.selectList(SecondOrderWrapper).get(0);
       // SecondOrder secondOrderInfo = secondOrdersMapper.selectById(secondOrderId);
        BigDecimal onePrice = secondOrderInfo.getServiceOnePrice();
        //默认平台佣金以及志愿者到手钱数
        BigDecimal volunteerMoney = onePrice.multiply(new BigDecimal("0.85"));
        BigDecimal platformBrokerage = onePrice.subtract(volunteerMoney);
        //计算结束冻结时间 默认开始时间+3天
        DateTime frozenStartTime = DateTimeUtil.getNowTime1();
        Date frozenEndTime = DateUtils.addDays(frozenStartTime, 3);
        OrderFrozenFunds orderFrozenFunds = OrderFrozenFunds.builder().volunteerMoney(volunteerMoney)
                .platformBrokerage(platformBrokerage).scoreMoney(BigDecimal.valueOf(0.00)).secondOrderMoney(onePrice)
                .status(0).secondOrderId(secondOrder.getSecondOrderId()).volunteerId(secondOrder.getVolunteerId())
                .frozenStartTime(frozenStartTime).frozenEndTime(frozenEndTime).build();
        //插入冻结资金表
        orderFrozenFundsMapper.insert(orderFrozenFunds);
        //更新secondOrder 表 不可以重复完成一个订单
        if (secondOrderInfo.getOrderStatus().equals(4)){
            throw new RuntimeException("订单已完成，请勿重复完成");
        }
        UpdateWrapper<SecondOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("second_order_id",secondOrder.getSecondOrderId()).set("order_status",2)
                .set("volunteer_review",secondOrder.getVolunteerReview()).set("volunteer_picture",secondOrder.getVolunteerPicture());
        secondOrdersMapper.update(null,updateWrapper);
        //更新志愿者账户中的冻结资金 =  之前的余额 + 志愿者 （先按照默认的比例，把默认的钱数，放入冻结资金表中）
        QueryWrapper<VolunteerAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("volunteer_id",secondOrder.getVolunteerId());
        VolunteerAccount volunteerAccount = volunteerAccountMapper.selectOne(queryWrapper);
        BigDecimal oldOrderFrozenBalance = volunteerAccount.getOrderFrozenBalance();
        BigDecimal newVolunteerFrozenBalance = oldOrderFrozenBalance.add(volunteerMoney);
        volunteerAccount.setOrderFrozenBalance(newVolunteerFrozenBalance);
        volunteerAccount.setUpdateTime(DateTimeUtil.getNowTime());
        volunteerAccountMapper.updateById(volunteerAccount);
        //判断是否完单
        String mainOrderId = secondOrderInfo.getMainOrderId();
        QueryWrapper<MainOrders> mainOrdersQueryWrapper = new QueryWrapper<MainOrders>().eq("main_order_id", mainOrderId);
        Long totalTimes = mainOrdersMapper.selectList(mainOrdersQueryWrapper).get(0).getTotalTimes();
        UpdateWrapper<MainOrders> mainOrdersUpdateWrapper = new UpdateWrapper<MainOrders>().eq("main_order_id", mainOrderId).setSql("finish_times = finish_times + 1");
        if (secondOrderInfo.getWorkNumber().equals(totalTimes)){
            mainOrdersUpdateWrapper.set("order_status", 4);
            mainOrdersMapper.update(null,mainOrdersUpdateWrapper);
        }else {
            mainOrdersMapper.update(null,mainOrdersUpdateWrapper);
        }
        return AjaxResult.success();
    }

    /**
     * @param reviewDTO
     */
    @Override
    public void userFinish(UserOrderReviewDTO reviewDTO) {
        //根据用户传来的评分 来设置需要计算的钱数
        //获取一次服务的钱数（！！   这一版先不改钱数的获取方式   ！！）
        BigDecimal serviceOnePrice = reviewDTO.getServiceOnePrice();
        BigDecimal volunteerMoney = serviceOnePrice.multiply(new BigDecimal("0.85"));
        BigDecimal scoreMoney = BigDecimal.valueOf(0);
        BigDecimal platformBrokerage = BigDecimal.valueOf(0);
        Integer score = reviewDTO.getScore();
        if  ( score.equals(1) ){
            //  1星85%
            scoreMoney = serviceOnePrice.multiply(new BigDecimal("0.85")).subtract(volunteerMoney);
            platformBrokerage = serviceOnePrice.subtract(volunteerMoney).subtract(scoreMoney);
        }
        else if ( score.equals(2) ){
            //  2星89%
            scoreMoney = serviceOnePrice.multiply(new BigDecimal("0.89")).subtract(volunteerMoney);
            platformBrokerage = serviceOnePrice.subtract(volunteerMoney).subtract(scoreMoney);
        } else if (score.equals(3)) {
            //  3星91%
            scoreMoney = serviceOnePrice.multiply(new BigDecimal("0.91")).subtract(volunteerMoney);
            platformBrokerage = serviceOnePrice.subtract(volunteerMoney).subtract(scoreMoney);
        } else if (score.equals(4)) {
            //  4星93%
            scoreMoney = serviceOnePrice.multiply(new BigDecimal("0.93")).subtract(volunteerMoney);
            platformBrokerage = serviceOnePrice.subtract(volunteerMoney).subtract(scoreMoney);
        } else if (score.equals(5)) {
            //  5星95%
            scoreMoney = serviceOnePrice.multiply(new BigDecimal("0.95")).subtract(volunteerMoney);
            platformBrokerage = serviceOnePrice.subtract(volunteerMoney).subtract(scoreMoney);
        }
        //修改冻结表：
        UpdateWrapper<OrderFrozenFunds> orderFrozenFundsUpdateWrapper = new UpdateWrapper<OrderFrozenFunds>().eq("second_order_id", reviewDTO.getSecondOrderId()).set("platform_brokerage", platformBrokerage).set("score_money", scoreMoney).set("update_time", DateTimeUtil.getNowTime());
        orderFrozenFundsMapper.update(null,orderFrozenFundsUpdateWrapper);
        //修改志愿者账户表，向其中添加内容
        UpdateWrapper<VolunteerAccount> volunteerAccountUpdateWrapper = new UpdateWrapper<VolunteerAccount>().eq("volunteer_id", reviewDTO.getVolunteerId()).setSql("order_frozen_balance = order_frozen_balance + " + scoreMoney);
        volunteerAccountMapper.update(null,volunteerAccountUpdateWrapper);
        //更改订单状态：
        UpdateWrapper<SecondOrder> updateWrapper = new UpdateWrapper<SecondOrder>().eq("second_order_id", reviewDTO.getSecondOrderId())
                .set("score",score).set("user_review",reviewDTO.getUserReview()).set("user_picture",reviewDTO.getUserPicture());
        secondOrdersMapper.update(null,updateWrapper);
    }
}
