package com.qs.mp.web.controller.api.channel.mall;

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.TicketBox;
import com.qs.mp.admin.domain.vo.TicketBoxListVO;
import com.qs.mp.admin.domain.param.TicketBoxParam;
import com.qs.mp.admin.domain.vo.TicketBoxVO;
import com.qs.mp.admin.service.ITicketAwardsPrizeService;
import com.qs.mp.admin.service.ITicketBoxService;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.TicketBoxSaleChannelTypeEnum;
import com.qs.mp.common.enums.TicketBoxStatusEnum;
import com.qs.mp.common.enums.TicketTypeEnum;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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/channel/mall")
@Api(tags = "渠道盲票商城接口")
@AllArgsConstructor
public class ChannelTicketController extends BaseApiController {


  @Autowired
  private ITicketBoxService ticketBoxService;

  @Autowired
  private ITicketAwardsPrizeService ticketAwardsPrizeService;

  @Autowired
  private MapperFacade mapperFacade;

  @Autowired
  private IChannelService channelService;

  /**
   * 盲票进货列表
   */
  @PostMapping("/ticket/list")
  @ApiOperation(value = "盲票组列表" , notes = "获取所有盲票信息")
  @ApiResponses(
          @ApiResponse(code = 200, message = "success", response = TicketBoxListVO.class)
  )
  public TableDataInfo list(@RequestBody TicketBoxParam param) {


    Long channelId = SecurityUtils.getLoginUser().getChannelId();
    Channel channel = channelService.getById(channelId);
    List<Long> channelIds = new ArrayList<>();
    if (StringUtils.isNotBlank(channel.getChannelNo())) {
      String[] split = StringUtils.split(channel.getChannelNo(), ".");
      for (String s : split) {
        channelIds.add(Long.valueOf(s));
      }
    }
    QueryWrapper<TicketBox> queryWrapper = new QueryWrapper<>();

    if (Objects.nonNull(param.getIsPre()) && param.getIsPre() == 1) {
      queryWrapper.gt("t1.pre_price", 0);
    }
    if (Objects.nonNull(param.getType())) {
      queryWrapper.eq("t1.type",param.getType());
    }
    if (Objects.nonNull(param.getCategoryId()) && param.getCategoryId() != 0) {
      queryWrapper.eq("t1.category_id",param.getCategoryId());
    }
    queryWrapper.eq("t1.status", TicketBoxStatusEnum.PUT_ON);


    if (param.getSaleQtySort() != null) {
      if (param.getSaleQtySort() == 1) {
        queryWrapper.orderByAsc("t1.sale_qty");
      } else if (param.getSaleQtySort() == 2) {
        queryWrapper.orderByDesc("t1.sale_qty");
      }
    }

    if (param.getSalePriceSort() != null) {
      if (param.getSalePriceSort() == 1) {
        queryWrapper.orderByAsc("t1.sale_price");
      } else if (param.getSalePriceSort() == 2) {
        queryWrapper.orderByDesc("t1.sale_price");
      }
    }

    queryWrapper.orderByDesc("t1.sort_weight");

    queryWrapper.nested(wrapper -> {
      wrapper.eq("t1.sale_channel_type", TicketBoxSaleChannelTypeEnum.ALL.getValue());
      if (channelIds.size() != 0) {
        wrapper.or().in("t2.channel_id",channelIds);
      }
    });
    startPage();
    List<TicketBox> ticketBoxes  = ticketBoxService.listBySaleChannel(queryWrapper);

//    List<TicketBox> ticketBoxes = ticketBoxService.list(
//        new LambdaQueryWrapper<TicketBox>().eq(TicketBox::getType, param.getType())
//            .eq(null != param.getCategoryId() && 0 != param.getCategoryId(), TicketBox::getCategoryId, param.getCategoryId())
//            .eq(TicketBox::getStatus, TicketBoxStatusEnum.PUT_ON)
//            .orderByDesc(TicketBox::getSortWeight));
    List<TicketBoxListVO> ticketBoxListVOList = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(ticketBoxes)) {
      for (TicketBox ticketBox : ticketBoxes) {
        TicketBoxListVO ticketBoxListVO = new TicketBoxListVO();
        BeanUtils.copyProperties(ticketBox, ticketBoxListVO);
        // 设置经销商分佣比
        ticketBoxListVO.setChannelCommRate(channel.getCommRate());
        ticketBoxListVOList.add(ticketBoxListVO);
      }
    }
    TableDataInfo rspData = getDataTable(ticketBoxes);
    rspData.setRows(ticketBoxListVOList);
    return rspData;
  }


  /**
   * 查看盲票详情
   */
  @PostMapping("/ticket/detail")
  @ApiResponses(
          @ApiResponse(code = 200, message = "success", response =  TicketBoxVO.class)
  )
  @ApiOperation(value = "查看盲票详情" , notes = "根据盲票组ID，获取盲票信息")
  public AjaxResult getInfo(@RequestBody TicketBoxParam param) {
    if (StringUtils.isBlank(param.getBoxId())) {
      return AjaxResult.error("参数异常，盲票组ID缺失");
    }
    TicketBox ticketBox = ticketBoxService.getById(param.getBoxId());
    TicketBoxVO ticketBoxVO = mapperFacade.map(ticketBox, TicketBoxVO.class);
    ticketBoxVO.setPrizeList(ticketAwardsPrizeService.listPrizeVO(ticketBox.getBoxId()));
    return AjaxResult.success(ticketBoxVO);
  }

}
