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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qs.mp.admin.domain.Marketing;
import com.qs.mp.admin.domain.MarketingAwards;
import com.qs.mp.admin.domain.MarketingAwardsPrize;
import com.qs.mp.admin.domain.excel.MarketingHitPrizeExcel;
import com.qs.mp.admin.domain.param.MarketingCreateParam;
import com.qs.mp.admin.domain.param.MarketingHitPrizeExportParam;
import com.qs.mp.admin.domain.param.MarketingQueryParam;
import com.qs.mp.admin.domain.param.MarketingUpdateParam;
import com.qs.mp.admin.domain.vo.*;
import com.qs.mp.admin.service.IMarketingAwardsPrizeService;
import com.qs.mp.admin.service.IMarketingAwardsService;
import com.qs.mp.admin.service.IMarketingService;
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.enums.BusinessType;
import com.qs.mp.common.enums.MarketingStatusEnum;
import com.qs.mp.common.enums.UserTypeEnum;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.user.domain.MarketingHitPrize;
import com.qs.mp.user.domain.MarketingUserCode;
import com.qs.mp.user.service.IMarketingHitPrizeService;
import com.qs.mp.user.service.IMarketingUserCodeService;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * 营销活动管理相关接口
 *
 * @author Cup
 * @date 2022/5/16
 */
@RestController
@RequestMapping("/api/v1/mp/admin/marketing")
@Api(tags = "营销活动管理相关接口")
public class MarketingMgrController extends BaseApiController {

    @Autowired
    private IMarketingService marketingService;

    @Autowired
    private IMarketingAwardsService marketingAwardsService;

    @Autowired
    private IMarketingAwardsPrizeService marketingAwardsPrizeService;

    @Autowired
    private IMarketingUserCodeService marketingUserCodeService;

    @Autowired
    private IMarketingHitPrizeService marketingHitPrizeService;

    @PreAuthorize("@ss.hasPermi('business:marketing:copy')")
    @PostMapping("/copy/{marketingId}")
    @ApiOperation("拷贝营销活动")
    public AjaxResult copy(@PathVariable("marketingId") Long marketingId) {

        marketingService.copyById(marketingId);

        return AjaxResult.success();
    }


    @Log(title = "营销活动新增", businessType = BusinessType.INSERT)
    @ApiOperation(value = "营销活动新增")
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermi('business:marketing:add')")
    public AjaxResult create(@Validated @RequestBody MarketingCreateParam marketingCreateParam) {
        marketingService.createMarketing(marketingCreateParam);
        return AjaxResult.success();
    }

    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermi('business:marketing:edit')")
    @ApiOperation("修改营销活动")
    public AjaxResult update(@Validated @RequestBody MarketingUpdateParam marketingUpdateParam) {
        marketingService.updateMarketing(marketingUpdateParam);
        return AjaxResult.success();
    }

    @PostMapping("/list")
    @PreAuthorize("@ss.hasPermi('business:marketing:list')")
    @ApiOperation("营销活动列表")
    @ApiResponses(
            @ApiResponse(code = 200, message = "营销活动列表", response = MarketingListVO.class)
    )
    public TableDataInfo list(@RequestBody MarketingQueryParam marketingQueryParam) {
        startPage();
        List<Marketing> marketingList = marketingService.listMarketing(marketingQueryParam);
        List<MarketingListVO> marketingListVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(marketingList)) {
            marketingListVOS = marketingList.stream().map(marketing -> {
                MarketingListVO marketingListVO = new MarketingListVO();
                BeanUtils.copyProperties(marketing, marketingListVO);
                marketingListVO.setRealNum(marketingUserCodeService.countRealUserNumByMarketingId(marketing.getId()));
                return marketingListVO;
            }).collect(Collectors.toList());
        }
        TableDataInfo res = getDataTable(marketingList);
        res.setRows(marketingListVOS);

        return res;
    }

    @PostMapping("/detail/{id}")
    @PreAuthorize("@ss.hasPermi('business:marketing:query')")
    @ApiOperation("活动详情")
    @ApiResponses(
            @ApiResponse(code = 200, message = "活动详情", response = MarketingVO.class)
    )
    public AjaxResult detail(@PathVariable("id") Long id) {
        MarketingVO marketingVO = new MarketingVO();
        Marketing marketing = marketingService.getById(id);
        if (Objects.isNull(marketing)) {
            return AjaxResult.error("活动信息不存在");
        }
        BeanUtils.copyProperties(marketing, marketingVO);

        // 获取奖级信息
        List<MarketingAwards> marketingAwardsList = marketingAwardsService.list(new LambdaQueryWrapper<MarketingAwards>()
                .eq(MarketingAwards::getMarketingId, id)
                .orderByAsc(MarketingAwards::getSort));

        List<MarketingAwardsVO> marketingAwardsVOS = marketingAwardsList.stream().map(marketingAwards -> {
            MarketingAwardsVO marketingAwardsVO = new MarketingAwardsVO();
            BeanUtils.copyProperties(marketingAwards, marketingAwardsVO);
            List<MarketingAwardsPrize> marketingAwardsPrizeList = marketingAwardsPrizeService.list(new LambdaQueryWrapper<MarketingAwardsPrize>()
                    .eq(MarketingAwardsPrize::getAwardsId, marketingAwards.getId()));
            marketingAwardsVO.setPrizeList(marketingAwardsPrizeList);
            return marketingAwardsVO;
        }).collect(Collectors.toList());

        marketingVO.setAwardsList(marketingAwardsVOS);

        return AjaxResult.success(marketingVO);
    }


    @PostMapping("/on/{id}")
    @PreAuthorize("@ss.hasPermi('business:marketing:on')")
    @ApiOperation("开启活动")
    public AjaxResult putOn(@PathVariable("id") Long id) {
        Marketing marketing = marketingService.getById(id);
        if (Objects.isNull(marketing)) {
            return AjaxResult.error("活动信息不存在");
        }
        if (MarketingStatusEnum.CLOSE.getValue().equals(marketing.getIsOn())) {
            return AjaxResult.error("已关闭的活动不支持开启");
        }

        if (MarketingStatusEnum.ON.getValue().equals(marketing.getIsOn())) {
            return AjaxResult.error("频繁操作,请刷新后重试");
        }

        // 开启活动
        marketingService.update(new LambdaUpdateWrapper<Marketing>()
                .set(Marketing::getIsOn, MarketingStatusEnum.ON.getValue())
                .eq(Marketing::getId, id));

        return AjaxResult.success();
    }

    @PostMapping("/off/{id}")
    @PreAuthorize("@ss.hasPermi('business:marketing:off')")
    @ApiOperation("关闭活动")
    public AjaxResult putOff(@PathVariable("id") Long id) {
        Marketing marketing = marketingService.getById(id);
        if (Objects.isNull(marketing)) {
            return AjaxResult.error("活动信息不存在");
        }
        if (MarketingStatusEnum.CLOSE.getValue().equals(marketing.getIsOn())) {
            return AjaxResult.error("频繁操作,请刷新后重试");
        }

        // 关闭活动
        marketingService.update(new LambdaUpdateWrapper<Marketing>()
                .set(Marketing::getIsOn, MarketingStatusEnum.CLOSE.getValue())
                .eq(Marketing::getId, id));

        return AjaxResult.success();
    }

    @PostMapping("/delete/{id}")
    @PreAuthorize("@ss.hasPermi('business:marketing:remove')")
    @ApiOperation("删除活动")
    public AjaxResult delete(@PathVariable("id") Long id) {
        Marketing marketing = marketingService.getById(id);
        if (Objects.isNull(marketing)) {
            return AjaxResult.error("活动信息不存在");
        }

        if (!MarketingStatusEnum.OFF.getValue().equals(marketing.getIsOn())) {
            return AjaxResult.error("频繁操作,请刷新后重试");
        }
        marketingService.deleteById(id);
        return AjaxResult.success();
    }

    @PostMapping("/data/{id}")
    @PreAuthorize("@ss.hasPermi('business:marketing:queryData')")
    @ApiOperation("活动数据")
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MarketingDataVO.class)
    )
    public AjaxResult dataInfo(@PathVariable("id") Long id) {
        MarketingDataVO marketingDataVO = new MarketingDataVO();
        Marketing marketing = marketingService.getById(id);
        if (Objects.isNull(marketing)) {
            return AjaxResult.error("活动信息不存在");
        }
        marketingDataVO.setTitle(marketing.getTitle());
        marketingDataVO.setRealNum(marketingUserCodeService.countRealUserNumByMarketingId(id));


        int codeCount = marketingUserCodeService.count(new LambdaQueryWrapper<MarketingUserCode>()
                .eq(MarketingUserCode::getMarketingId, id)
                .eq(MarketingUserCode::getUserType, UserTypeEnum.ORDINARY.getValue()));
        marketingDataVO.setCodeCount(codeCount);


        int newUserCount = marketingUserCodeService.count(new LambdaQueryWrapper<MarketingUserCode>()
                .eq(MarketingUserCode::getMarketingId, id)
                .eq(MarketingUserCode::getUserType, UserTypeEnum.ORDINARY.getValue())
                .ne(MarketingUserCode::getHelpUserId, -1));

        marketingDataVO.setNewUserCount(newUserCount);

        return AjaxResult.success(marketingDataVO);
    }

    @PostMapping("/data/codeList/{id}")
    @PreAuthorize("@ss.hasPermi('business:marketing:queryData')")
    @ApiOperation("活动抽奖码数据")
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MarketingUserCodeListVO.class)
    )
    public TableDataInfo dataCodeList(@PathVariable("id") Long id) {
        startPage();
        QueryWrapper<MarketingUserCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("t1.marketing_id", id);
        queryWrapper.eq("t1.user_type", UserTypeEnum.ORDINARY.getValue());

        queryWrapper.orderByDesc("t1.created_time");

        List<MarketingUserCodeListVO> list = marketingUserCodeService.listMarketingUserCodeByQueryWrapper(queryWrapper);
        return getDataTable(list);
    }


    @PostMapping("/export")
    @PreAuthorize("@ss.hasPermi('business:marketing:export')")
    @ApiOperation("活动中奖数据导出")
    public AjaxResult export(@RequestBody MarketingHitPrizeExportParam marketingHitPrizeExportParam) {
        QueryWrapper<MarketingHitPrize> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(marketingHitPrizeExportParam.getTitle())) {
            queryWrapper.like("t2.title", marketingHitPrizeExportParam.getTitle());
        }
        queryWrapper.eq("t5.user_type", UserTypeEnum.ORDINARY.getValue());

        List<MarketingHitPrizeExcel> exportList = marketingHitPrizeService.listHitPrizeExportByQueryWrapper(queryWrapper);
        if (CollectionUtils.isEmpty(exportList)) {
            return AjaxResult.error("没有符合条件的活动中奖数据");
        }
        ExcelUtil<MarketingHitPrizeExcel> util = new ExcelUtil<>(MarketingHitPrizeExcel.class);
        return util.exportExcel(exportList, "活动中奖数据导出", false);


    }

}
