package com.izouma.dingdong.web;

import cn.hutool.core.util.StrUtil;
import com.izouma.dingdong.domain.OrderInfo;
import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.dto.UserOrderDTO;
import com.izouma.dingdong.enums.Identity;
import com.izouma.dingdong.enums.MerchantStatus;
import com.izouma.dingdong.enums.OrderStatus;
import com.izouma.dingdong.enums.RefundReason;
import com.izouma.dingdong.repo.UserRepo;
import com.izouma.dingdong.repo.rider.RiderRepo;
import com.izouma.dingdong.service.OrderInfoService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.OrderInfoRepo;
import com.izouma.dingdong.service.merchant.MerchantService;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orderInfo")
@AllArgsConstructor
public class OrderInfoController extends BaseController {
    private OrderInfoService orderInfoService;
    private OrderInfoRepo    orderInfoRepo;
    private UserRepo         userRepo;
    private MerchantService  merchantService;
    private RiderRepo        riderRepo;


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public OrderInfo save(@RequestBody OrderInfo record) {
        if (record.getId() != null) {
            OrderInfo orig = orderInfoRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return orderInfoRepo.save(orig);
        }
        return orderInfoRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<OrderInfo> all(PageQuery pageQuery) {
        return orderInfoRepo.findAll(toSpecification(pageQuery, OrderInfo.class), toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public OrderInfo get(@PathVariable Long id) {
        return orderInfoRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        orderInfoRepo.deleteById(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<OrderInfo> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }


    @PostMapping("/order")
    @ApiOperation("从购物车生成订单")
    public OrderInfo order(UserOrderDTO userOrderDTO) {
        return orderInfoService.userOrder(userOrderDTO);
    }

    @GetMapping("/my")
    @ApiOperation("个人订单")
    public Page<OrderInfo> my(PageQuery pageQuery) {
        //query.status 状态传入
        Map<String, Object> query = pageQuery.getQuery();
        Long id = SecurityUtils.getAuthenticatedUser().getId();
        User user = userRepo.findById(id).orElseThrow(new BusinessException("无用户"));
        if (user.getIdentity() == null) {
            throw new BusinessException("身份错误");
        }
        switch (user.getIdentity()) {
            case USER:
                query.put("userId", id);
                break;
            case MERCHANT:
                Long merchantId = merchantService.findMerchantId(id);
                query.put("merchantId", merchantId);
                break;
            case RIDER:
                Long riderId = riderRepo.findByUserId(id).orElseThrow(new BusinessException("无骑手")).getId();
                query.put("riderId", riderId);
                break;
        }
        return orderInfoRepo.findAll(toSpecification(pageQuery, OrderInfo.class), toPageRequest(pageQuery));

/*        List<OrderInfo> collect = orderInfoService.my(SecurityUtils.getAuthenticatedUser().getId());
        return new PageImpl<>(collect, toPageRequest(pageQuery), pageQuery.getSize());*/
    }


    @PostMapping("/list")
    @ApiOperation("/按userId查订单")
    public Page<OrderInfo> list(Long id, PageQuery pageQuery) {
        //        new PageImpl<>(list,toPageRequest(pageQuery),pageQuery.getSize())
        return new PageImpl<>(orderInfoService.my(id), toPageRequest(pageQuery), pageQuery.getSize());
    }

    @GetMapping("/received")
    @ApiOperation("商家手动接单")
    public OrderInfo received(Long orderId, Boolean pass) {
        return orderInfoService.merReceiveOrder(orderId, pass);
    }

    @PostMapping("/riderStatus")
    @ApiOperation("骑手改变状态")
    public void riderStatus(Long orderId, Boolean pass) {
//        orderInfoService.riderCarryOut(orderId, pass);
    }

    @GetMapping("/allAmount")
    @ApiOperation("消费金额")
    public BigDecimal allAmount(Long id) {
        return orderInfoRepo.sumRealAmountByUserId(id);
    }


    @GetMapping("/cancelOrder")
    @ApiOperation("取消订单")
    public OrderInfo cancel(Long id, RefundReason reason, String remark, String img) {
        //如果是骑手取消
        if (Identity.RIDER.equals(SecurityUtils.getAuthenticatedUser().getIdentity())) {
            if (StrUtil.isEmpty(img)) {
                throw new BusinessException("无联系信息截图");
            }
        }

        //订单id  理由  备注  图片
        return orderInfoService.cancel(id, reason, remark, img);
    }

    //@GetMapping("/cancelCancelOrder")

    @GetMapping("/missedOrder")
    @ApiOperation("骑手端，五分钟内未接单的订单")
    public List<OrderInfo> missedOrder() {
        return orderInfoRepo.findAllByStatusAndOrderTimeAfterAndMerchantStatus(OrderStatus.PAID, LocalDateTime.now()
                .plusMinutes(5), MerchantStatus.RECEIVED);
    }

    @GetMapping("/riderReceived")
    @ApiOperation("骑手端，未接单的订单")
    public List<OrderInfo> riderReceived() {
        return orderInfoRepo.findAllByStatusAndMerchantStatus(OrderStatus.PAID, MerchantStatus.RECEIVED);
    }

}

