package com.qs.mp.web.controller.api.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qs.mp.admin.domain.excel.UserExchangeOrderExcel;
import com.qs.mp.admin.domain.excel.UserTicketOrderExcel;
import com.qs.mp.admin.domain.param.UserExchangeOrderQueryParam;
import com.qs.mp.admin.domain.vo.UserExchangeOrderVO;
import com.qs.mp.admin.domain.vo.UserTicketOrderListVO;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.user.domain.UserExchangeOrder;
import com.qs.mp.user.domain.UserTicketOrder;
import com.qs.mp.user.service.IUserExchangeOrderService;
import com.qs.mp.utils.ExcelUtil;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 用户兑换订单管理相关API
 * @author Cup
 * @date 2022/5/10
 */
@Api(tags = "用户兑换订单管理相关API")
@RestController
@RequestMapping("/api/v1/mp/admin/exchange/order/*")
public class UserExchangeOrderMgrController extends BaseApiController {


    @Autowired
    private IUserExchangeOrderService userExchangeOrderService;

    @PostMapping("/list")
    @ApiOperation("用户兑换订单列表")
    @PreAuthorize("@ss.hasPermi('order:exchange:list')")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = UserExchangeOrderVO.class)
    )
    public TableDataInfo list(@RequestBody UserExchangeOrderQueryParam userExchangeOrderQueryParam) {

        startPage();

        QueryWrapper<UserExchangeOrder> queryWrapper = new QueryWrapper<>();

        // 封装条件
        if (StringUtils.isNotBlank(userExchangeOrderQueryParam.getGoodsName())) {
            queryWrapper.like("t2.title", userExchangeOrderQueryParam.getGoodsName());
        }

        if (StringUtils.isNotBlank(userExchangeOrderQueryParam.getPhone())) {
            queryWrapper.eq("t4.phonenumber", userExchangeOrderQueryParam.getPhone());
        }

        if (Objects.nonNull(userExchangeOrderQueryParam.getMinExchangePrice()) && Objects.nonNull(userExchangeOrderQueryParam.getMaxExchangePrice())) {
            queryWrapper.between("t1.order_coin", userExchangeOrderQueryParam.getMinExchangePrice(), userExchangeOrderQueryParam.getMaxExchangePrice());
        }

        if (Objects.nonNull(userExchangeOrderQueryParam.getStartTime()) && Objects.nonNull(userExchangeOrderQueryParam.getEndTime())) {
            queryWrapper.between("t1.created_time", userExchangeOrderQueryParam.getStartTime(), userExchangeOrderQueryParam.getEndTime());
        }

        queryWrapper.orderByDesc("t1.created_time");

        List<UserExchangeOrderVO> list =  userExchangeOrderService.listUserExchangeOrderByWrapper(queryWrapper);

        return getDataTable(list);
    }

    @PostMapping("/export")
    @PreAuthorize("@ss.hasPermi('order:exchange:export')")
    @ApiOperation("用户兑换订单导出")
    public AjaxResult export(@RequestBody UserExchangeOrderQueryParam userExchangeOrderQueryParam) {
        // 导出时间范围限制校验
        Date startTime = userExchangeOrderQueryParam.getStartTime();
        Date endTime = userExchangeOrderQueryParam.getEndTime();
        if (startTime == null || endTime == null) {
            return AjaxResult.error("导出数据必须设置日期范围");
        }
        if (DateUtils.diff(startTime, endTime) > 30) {
            return AjaxResult.error("导出的数据不能超过31天");
        }

        QueryWrapper<UserExchangeOrder> queryWrapper = new QueryWrapper<>();

        // 封装条件
        if (StringUtils.isNotBlank(userExchangeOrderQueryParam.getGoodsName())) {
            queryWrapper.like("t2.title", userExchangeOrderQueryParam.getGoodsName());
        }

        if (StringUtils.isNotBlank(userExchangeOrderQueryParam.getPhone())) {
            queryWrapper.eq("t4.phonenumber", userExchangeOrderQueryParam.getPhone());
        }

        if (Objects.nonNull(userExchangeOrderQueryParam.getMinExchangePrice()) && Objects.nonNull(userExchangeOrderQueryParam.getMaxExchangePrice())) {
            queryWrapper.between("t2.exchange_price", userExchangeOrderQueryParam.getMinExchangePrice(), userExchangeOrderQueryParam.getMaxExchangePrice());
        }

        if (Objects.nonNull(userExchangeOrderQueryParam.getStartTime()) && Objects.nonNull(userExchangeOrderQueryParam.getEndTime())) {
            queryWrapper.between("t1.created_time", userExchangeOrderQueryParam.getStartTime(), userExchangeOrderQueryParam.getEndTime());
        }
        queryWrapper.orderByDesc("t1.created_time");
        int totalSize = userExchangeOrderService.countUserExchangeOrderByWrapper(queryWrapper);
        if (totalSize == 0) {
            return AjaxResult.error("没有符合条件的用户订单");
        }
        int pageSize = 2000;
        List<UserExchangeOrderVO> userExchangeOrderVOList = new ArrayList<>();
        if (totalSize > pageSize) {
            int totalPage = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
            for (int i = 0; i < totalPage; i++) {
                queryWrapper.last("limit " + (i * pageSize) + ", " + pageSize);
                List<UserExchangeOrderVO> list = userExchangeOrderService.listUserExchangeOrderByWrapper(queryWrapper);
                if (CollectionUtils.isNotEmpty(list)) {
                    userExchangeOrderVOList.addAll(list);
                }
            }
        } else {
            userExchangeOrderVOList = userExchangeOrderService.listUserExchangeOrderByWrapper(queryWrapper);
        }
        List<UserExchangeOrderExcel> excelList = userExchangeOrderVOList.stream().map(userExchangeOrderVO -> {
            UserExchangeOrderExcel userExchangeOrderExcel = new UserExchangeOrderExcel();
            BeanUtils.copyProperties(userExchangeOrderVO, userExchangeOrderExcel);
            return userExchangeOrderExcel;
        }).collect(Collectors.toList());

        ExcelUtil<UserExchangeOrderExcel> util = new ExcelUtil<>(UserExchangeOrderExcel.class);
        return util.exportExcel(excelList, "用户兑换订单导出", false);
    }
}
