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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qs.mp.admin.domain.excel.ChannelWithdrawExcel;
import com.qs.mp.admin.domain.excel.UserTicketOrderItemExcel;
import com.qs.mp.admin.domain.param.ChannelWithdrawQueryParam;
import com.qs.mp.channel.domain.ChannelOrder;
import com.qs.mp.channel.domain.ChannelOrderItem;
import com.qs.mp.channel.domain.ChannelWithdraw;
import com.qs.mp.channel.domain.vo.ChannelOrderVO;
import com.qs.mp.channel.domain.vo.ChannelWithdrawVO;
import com.qs.mp.channel.service.IChannelOrderItemService;
import com.qs.mp.channel.service.IChannelOrderService;
import com.qs.mp.channel.service.IChannelWithdrawService;
import com.qs.mp.common.annotation.Log;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.core.redis.RedisCache;
import com.qs.mp.common.enums.BusinessType;
import com.qs.mp.common.enums.ChannelWithdrawStatusEnum;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.common.utils.DateUtils;
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 java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang3.StringUtils;
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;


@RestController
@RequestMapping("/api/v1/mp/admin/channel/withdraw")
@Api(tags = "渠道提现申请管理接口")
@AllArgsConstructor
public class ChannelWithdrawMgrController extends BaseApiController {

  @Autowired
  private IChannelWithdrawService channelWithdrawService;

  @Autowired
  private MapperFacade mapperFacade;

  /**
   * 提现申请列表
   */
  @PostMapping("/list")
  @ApiOperation(value = "提现申请列表" , notes = "获取所有提现信息")
  @PreAuthorize("@ss.hasPermi('finance:withdraw:list')")
  public TableDataInfo list(@RequestBody JSONObject param) {
    Integer status = param.getInteger("status");
    String name = param.getString("name");
    Date startDay = param.getDate("startDay");
    Date endDay = param.getDate("endDay");

    startPage();
    List<ChannelWithdrawVO> withdrawList = channelWithdrawService.listWithdrawVO(new QueryWrapper<ChannelWithdraw>()
        .eq(null != status && status != 0, "t1.status", status)
        .like(StringUtils.isNotBlank(name), "t2.name", name)
        .ge(null != startDay, "t1.create_time", startDay)
        .lt(null != endDay, "t1.create_time", endDay)
        .orderByDesc("t1.create_time"));
    return getDataTable(withdrawList);
  }

  /**
   * 提现申请详情
   */
  @PostMapping("/detail")
  @PreAuthorize("@ss.hasPermi('finance:withdraw:query')")
  @ApiOperation(value = "申请详情" , notes = "在提现列表页面查看详情")
  public AjaxResult query(@RequestBody JSONObject param) {
    Long id = param.getLong("id");
    if (null == id || 0 == id) {
      return error(ErrorCodeEnum.ERROR_CODE_1001);
    }
    List<ChannelWithdrawVO> withdrawList = channelWithdrawService.listWithdrawVO(new QueryWrapper<ChannelWithdraw>()
        .eq("t1.id", id));
    return AjaxResult.success(withdrawList.get(0));
  }

  /**
   * 提现申请审核结果
   */
  @Log(title = "提现申请审核", businessType = BusinessType.UPDATE)
  @PostMapping("/verify")
  @ApiOperation(value = "申请审核" , notes = "在提现详情页面审核")
  @PreAuthorize("@ss.hasPermi('finance:withdraw:verify')")
  public AjaxResult verify(@RequestBody ChannelWithdraw withdraw) {
    if (null == withdraw.getId() || null == withdraw.getStatus()) {
      return error(ErrorCodeEnum.ERROR_CODE_1001);
    }
    ChannelWithdraw channelWithdraw = channelWithdrawService.getById(withdraw.getId());
    if (channelWithdraw.getStatus() != ChannelWithdrawStatusEnum.WITHDRAWING) {
      return error("提现申请状态异常，不是提现中");
    }
    channelWithdrawService.verify(channelWithdraw, withdraw.getStatus(), withdraw.getVerifyContent());
    return AjaxResult.success("操作成功");
  }


  @PostMapping("/export")
  @ApiOperation("提现申请导出")
  @PreAuthorize("@ss.hasPermi('finance:withdraw:export')")
  public AjaxResult export(@RequestBody ChannelWithdrawQueryParam param) {

    // 导出时间范围限制校验
    Date startTime = param.getStartDay();
    Date endTime = param.getEndDay();
    if (startTime == null || endTime == null) {
      return AjaxResult.error("导出数据必须设置日期范围");
    }
    if (DateUtils.diff(startTime, endTime) > 30) {
      return AjaxResult.error("导出的数据不能超过31天");
    }

    List<ChannelWithdrawVO> withdrawList = channelWithdrawService.listWithdrawVO(new QueryWrapper<ChannelWithdraw>()
            .eq(null != param.getStatus() && param.getStatus() != 0, "t1.status", param.getStatus())
            .like(StringUtils.isNotBlank(param.getName()), "t2.name", param.getName())
            .ge(null != param.getStartDay(), "t1.create_time", param.getStartDay())
            .lt(null != param.getEndDay(), "t1.create_time", param.getEndDay())
            .orderByDesc("t1.create_time"));

    if (CollectionUtils.isEmpty(withdrawList)) {
      return error("没有符合条件的记录");
    }

    List<ChannelWithdrawExcel> channelWithdrawExcelList = new ArrayList<>();
    for (ChannelWithdrawVO channelWithdrawVO : withdrawList) {
      ChannelWithdrawExcel channelWithdrawExcel = new ChannelWithdrawExcel();
        channelWithdrawExcel.setCreateTime(channelWithdrawVO.getCreateTime());
        channelWithdrawExcel.setTransferTime(channelWithdrawVO.getTransferTime());
        channelWithdrawExcel.setName(channelWithdrawVO.getName());
        channelWithdrawExcel.setMobile(channelWithdrawVO.getMobile());
        Integer money = channelWithdrawVO.getMoney();
        if (Objects.isNull(money)) {
          money = 0;
        }
        channelWithdrawExcel.setMoney(BigDecimal.valueOf(money).divide(BigDecimal.valueOf(100),2 ,RoundingMode.HALF_UP));
        if (Objects.nonNull(channelWithdrawVO.getLevel())) {
          if (channelWithdrawVO.getLevel() == 0) {
            channelWithdrawExcel.setLevel("经销商");
          } else {
            channelWithdrawExcel.setLevel("渠道商");
          }
        }
      if (Objects.nonNull(channelWithdrawVO.getStatus())) {
        channelWithdrawExcel.setStatus(channelWithdrawVO.getStatus().getDesc());
      }
      channelWithdrawExcelList.add(channelWithdrawExcel);
    }
    ExcelUtil<ChannelWithdrawExcel> util = new ExcelUtil<>(ChannelWithdrawExcel.class);
    return util.exportExcel(channelWithdrawExcelList, "提现申请导出", false);
  }


}
