package com.hc.web.controller.browser.app;

import com.hc.business.dto.OrderRefundEntityDto;
import com.hc.business.model.*;
import com.hc.business.service.OrderRefundLogService;
import com.hc.business.service.OrderRefundService;
import com.hc.business.service.OrdersService;
import com.hc.business.service.UserInvoicesService;
import com.hc.core.utils.enums.InfoEnum;
import com.hc.core.utils.result.Result;
import com.hc.core.utils.tool.ResultUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 退费订单记录表(OrderRefund)表控制层
 *
 * @author makejava
 * @since 2024-01-20 11:50:55
 */

@RestController
@RequestMapping("/new/api/app/orderRefund")
public class AppOrderRefundController {

    /**
     * 服务对象
     */
    private final OrderRefundService orderRefundService;

    private final OrderRefundLogService orderRefundLogService;

    private final OrdersService ordersService;

    private final UserInvoicesService userInvoicesService;

    public AppOrderRefundController(OrderRefundService orderRefundService, OrderRefundLogService orderRefundLogService, OrdersService ordersService, UserInvoicesService userInvoicesService) {
        this.orderRefundService = orderRefundService;
        this.orderRefundLogService = orderRefundLogService;
        this.ordersService = ordersService;
        this.userInvoicesService = userInvoicesService;
    }



    /**
     * @Author ymnets
     * @Description 获取还可退费人员列表
     * @return com.hc.core.utils.result.Result
     **/
    @GetMapping("/getWaitingForRefundUser")
    @ApiOperation(value = "获取还可退费人员列表", response = Result.class)
    public Result getWaitingForRefundUser(@ApiParam(value = "订单ID") @RequestParam Integer orderId) {
        return Result.success(orderRefundLogService.getWaitingForRefundUser(orderId));
    }



    @PostMapping("/addRefund")
    @ApiOperation(value = "申请退费", response = Result.class)
    public Result addRefund(@RequestBody OrderRefundAdd orderRefundAdd) {
        Orders orders = ordersService.queryById(orderRefundAdd.getOrderId());
        //判断订单是否存在
        if(orders==null)
        {
            return Result.info(InfoEnum.ORDER_NO_EXIT);
        }
        //判断传入的数据是否完整
        List<Integer> userList = orderRefundAdd.getUserIds();
        Integer userCount = (int)userList.stream().count();
        if(userCount==0l)
        {
            return Result.info(InfoEnum.ORDER_USER_NO_EXIT);
        }

        //nono，发票所处状态-1不开只记录， 0申请中 10申请成功，20开票完成，30开票失败，40开票成功签章失败， 50作废申请，60未作废 70作废中 80作废失败 90作废成功
        //查询这个订单下是否存在未作废的发票
        List<UserInvoices> userInvoiceList = userInvoicesService.queryByOrderId(orderRefundAdd.getOrderId(),null);
        userInvoiceList = userInvoiceList.stream().filter(item -> item.getSyncStatus() != 90 && item.getSyncStatus() != 30).collect(Collectors.toList());
        if (userInvoiceList.stream().count() > 0) {
            return Result.exception(511, "此订单已经存在发票，需先作废");
        }


        //判断是否存在已经有退费单在处理中
        List<OrderRefundEntityDto> orderRefunds = orderRefundService.queryAll(orderRefundAdd.getOrderId(), "", 0, null, null, null, null);
        if(orderRefunds.stream().count()>0) {
            return Result.info(InfoEnum.ORDER_REFUND_ADD_ERROR);
        }

        //新增一张退费单
        OrderRefund orderRefund = new OrderRefund();
        orderRefund.setOrderId(orderRefundAdd.getOrderId());
        orderRefund.setReason(orderRefundAdd.getReason());
        orderRefund.setRemarks(orderRefundAdd.getRemarks());
        orderRefund.setTotoalAmount(userCount * orders.getPrice());
        orderRefund.setStatus(0);
        orderRefund.setCreateTime(System.currentTimeMillis());
        orderRefund.setClassId(orders.getClassId());
        orderRefund.setRefundNo(ResultUtils.generateUniqueNumber());

        OrderRefund entity = orderRefundService.insert(orderRefund);

        List<OrderRefundLog> orderRefundLogs = new ArrayList<>();
        for (Integer userId: userList) {
            OrderRefundLog orderRefundLog = new OrderRefundLog();
            orderRefundLog.setRefundId(entity.getRefundId());
            orderRefundLog.setUserId(userId);
            orderRefundLogs.add(orderRefundLog);
        }

        orderRefundLogs.forEach(orderRefundLogService::insert);
        return Result.success(entity);
    }


    @GetMapping("/getRefundOrderList")
    @ApiOperation(value = "获取订单下的所有退费单", response = Result.class)
    public Result getRefundOrderList(@ApiParam(value = "订单ID") @RequestParam Integer orderId) {
        return Result.success(orderRefundService.queryAll(orderId,"",null,null,null,null,null));
    }
}
