package com.leromro.core.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.utils.SecurityUtils;
import com.leromro.core.domain.Address;
import com.leromro.core.domain.MainOrders;
import com.leromro.core.domain.SecondOrder;
import com.leromro.core.domain.vo.SecondOrderInfoVO;
import com.leromro.core.domain.vo.VolunteerOrderStatisticsVO;
import com.leromro.core.domain.vo.VolunteerOrdersVO;
import com.leromro.core.service.IAddressService;
import com.leromro.core.service.IMainOrderService;
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;
    @ApiOperation("志愿者查询小订单列表")
    @GetMapping("/volunteerOrderList")
    public R<List<VolunteerOrdersVO>> selectVolunteerList(Long orderStatus) {
        Long userId = SecurityUtils.getUserId();
        List<VolunteerOrdersVO> list = secondOrderService.selectOrderList(userId, orderStatus);
        list.forEach(volunteerOrdersVO -> volunteerOrdersVO.setServiceOnePrice(volunteerOrdersVO.getServiceOnePrice().multiply(new BigDecimal("0.85"))));
        return R.ok(list);
    }

    @ApiOperation("志愿者订单详情,（收货地址和状态）")
    @GetMapping("/volunteerOrderInfo")
    public R<SecondOrderInfoVO> selectVolunteerOrderInfo(String orderId) {
        QueryWrapper<SecondOrder> wrapper = new QueryWrapper<SecondOrder>().eq("second_order_id", orderId);
        SecondOrder secondOrderInfo = secondOrderService.list(wrapper).get(0);

        QueryWrapper<MainOrders> mainOrdersQueryWrapper = new QueryWrapper<MainOrders>().eq("main_order_id", secondOrderInfo.getMainOrderId());
        MainOrders mainOrder = mainOrderService.getOne(mainOrdersQueryWrapper);
        //地址都去主订单里面去获取
        Address address = Address.builder().address(mainOrder.getAddress()).name(mainOrder.getClientName()).telephone(mainOrder.getClientTelephone()).longitude(mainOrder.getAddressLongitude()).latitude(mainOrder.getAddressLatitude()).build();
        SecondOrderInfoVO secondOrderInfoVO = new SecondOrderInfoVO();
        secondOrderInfoVO.setSecondOrder(secondOrderInfo);
        secondOrderInfoVO.setAddress(address);
        return R.ok(secondOrderInfoVO);
    }

    @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());
        secondOrderService.update(updateWrapper);
        //订单开始 根据secondOrderId修改主订单状态 修改为3
        mainOrderService.startService(secondOrderId);
        // 通过websocket向客户发送消息，提示服务已开始

        return AjaxResult.success();
    }
    @ApiOperation(value = "志愿者滑动，结束订单并上传图片", notes = "传入seconderOrderId,以及图片拼接在一起的字符串 json对象参数")
/*    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "seconderOrderId", value = "志愿者订单id", required = true),
            @ApiImplicitParam(name = "serviceLog", value = "志愿者上传图片拼接的字符串", required = true),
            @ApiImplicitParam(name = "volunteerId", value = "志愿者的id", required = true)
    })*/
    @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);
    }

}
