package com.leromro.core.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.leromro.common.core.controller.BaseController;
import com.leromro.common.core.domain.AjaxResult;
import com.leromro.common.core.domain.R;
import com.leromro.common.core.page.TableDataInfo;
import com.leromro.common.utils.SecurityUtils;
import com.leromro.core.domain.PlatformFinance;
import com.leromro.core.domain.SecondOrder;
import com.leromro.core.domain.vo.AppSecoundOrderInfoVO;
import com.leromro.core.domain.vo.VolunteerOrderStatisticsVO;
import com.leromro.core.domain.vo.VolunteerOrdersVO;
import com.leromro.core.domain.vo.WebSecondOrderInfoVO;
import com.leromro.core.service.IAddressService;
import com.leromro.core.service.IMainOrderService;
import com.leromro.core.service.IPlatformFinanceService;
import com.leromro.core.service.ISecondOrderService;
import com.leromro.core.utils.DateTimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 订单主Controller
 *
 * @author ruoyi
 * @date 2025-04-09
 */
@RestController
@Api(tags = "志愿者订单")
@RequestMapping("/core/volunteer/orders")
public class volunteerOrderController extends BaseController {
    @Autowired
    private ISecondOrderService secondOrderService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IMainOrderService mainOrderService;
    @Autowired
    private IPlatformFinanceService platformFinanceService;

    @ApiOperation("志愿者查询小订单列表")
    @GetMapping("/volunteerOrderList")
    public TableDataInfo<VolunteerOrdersVO> selectVolunteerList(Long orderStatus) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<VolunteerOrdersVO> list = secondOrderService.selectOrderList(userId, orderStatus);
        list.forEach(volunteerOrdersVO -> volunteerOrdersVO.setServiceOnePrice(volunteerOrdersVO.getServiceOnePrice().multiply(BigDecimal.valueOf(volunteerOrdersVO.getSingleQuantity())).multiply(new BigDecimal("0.85"))));
        return getDataTable(list);
    }

    @ApiOperation("小程序 志愿者订单详情, 传入订单id")
    @GetMapping("/volunteerOrderInfo")
    public R<AppSecoundOrderInfoVO> selectVolunteerOrderInfo(Long secondOrderId) {
        AppSecoundOrderInfoVO appSecoundOrderInfoVO = secondOrderService.selectAppSecondOrderInfo(secondOrderId);
        return R.ok(appSecoundOrderInfoVO);
    }

    @ApiOperation("web 志愿者订单详情, 传入订单id")
    @GetMapping("/web/volunteerOrderInfo")
    public R<WebSecondOrderInfoVO> selectWebVolunteerOrderInfo(Long secondOrderId) {
        WebSecondOrderInfoVO webSecondOrderInfo = secondOrderService.selectWebAppSecondOrderInfo(secondOrderId);
        return R.ok(webSecondOrderInfo);
    }

    @ApiOperation(value = "志愿者滑动，开始订单", notes = "目前只传secondOrderId（第二版再根据地址判断）")
    @GetMapping("/getTimesByDate/{secondOrderId}")
    public AjaxResult volunteerStartWork(@PathVariable Long secondOrderId){
        UpdateWrapper<SecondOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("second_order_id",secondOrderId).set("order_status","3").set("update_time", DateTimeUtil.getNowTime()).set("service_start_time",DateTimeUtil.getNowTime());
        secondOrderService.update(updateWrapper);
        //订单开始 根据secondOrderId修改主订单状态 修改为3
        mainOrderService.startService(secondOrderId);
        // 通过websocket向客户发送消息，提示服务已开始

        return AjaxResult.success();
    }

    @ApiOperation(value = "志愿者滑动，结束订单并上传图片", notes = "传入seconderOrderId,以及图片拼接在一起的字符串 json对象参数")
    @PostMapping("/volunteerFinishSecondOrder")
    public AjaxResult volunteerFinishWork(@RequestBody SecondOrder secondOrder){
        return  secondOrderService.volunteerFinishWork(secondOrder);
    }

    /**
     * 志愿者订单统计
     */
    @ApiOperation("志愿者订单统计")
    @GetMapping("/volunteerOrderStatistics")
    public R<VolunteerOrderStatisticsVO> volunteerOrderStatistics() {
        List<SecondOrder> orderList = secondOrderService.list(new LambdaQueryWrapper<SecondOrder>()
                .eq(SecondOrder::getVolunteerId, getUserId()));
        VolunteerOrderStatisticsVO vo = VolunteerOrderStatisticsVO.builder()
                .orderCount(orderList.size())
                .reservationCount((int) orderList.stream().filter(secondOrder -> Objects.equals(secondOrder.getOrderStatus(), "1")).count())
                .doingCount((int) orderList.stream().filter(secondOrder -> Objects.equals(secondOrder.getOrderStatus(), "3")).count())
                .finishedCount((int) orderList.stream().filter(secondOrder -> Objects.equals(secondOrder.getOrderStatus(), "4")).count())
                .cancelCount((int) orderList.stream().filter(secondOrder -> Objects.equals(secondOrder.getOrderStatus(), "2")).count())
                .build();
        return R.ok(vo);
    }

    /**
     * 分配订单到服务中心，并且在分配后就直接计算金额，
     */
    @ApiOperation("分配订单到服务中心，并且直接算出服务中心的抽成金额 传入分配到的服务中心的id 和小订单的id")
    @PostMapping("allotSCandAmount")
    public R allotSeconderToServiceCenterAndGetAmount(@RequestBody SecondOrder secondOrder){
        SecondOrder secondOrder1 = secondOrderService.getById(secondOrder.getSecondOrderId());
        PlatformFinance platformFinance = platformFinanceService.getOne(new LambdaQueryWrapper<PlatformFinance>().eq(PlatformFinance::getSecondOrderId, secondOrder.getSecondOrderId()));
        BigDecimal ServiceCentreDistributionAmount = secondOrder1.getServiceCentreDistributionRatio().multiply(platformFinance.getChangeMoney());
        return R.ok( secondOrderService.update(new LambdaUpdateWrapper<SecondOrder>().eq(SecondOrder::getSecondOrderId, secondOrder.getSecondOrderId()).set(SecondOrder::getServiceCentreDistributionAmount, ServiceCentreDistributionAmount)
                .set(SecondOrder::getAllotStatus,"20").set(SecondOrder::getServiceCenterId,secondOrder.getServiceCenterId()).set(SecondOrder::getUpdateTime,DateTimeUtil.getNowTime()))
        );
    }

}
