package com.hzs.activity.draw.controller.manage;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.activity.base.param.AcDrawRuleConfigParam;
import com.hzs.activity.base.param.ActivityParam;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.service.IAcGoalMemberConfigService;
import com.hzs.activity.draw.param.DrawGiftConfigParam;
import com.hzs.activity.draw.service.IAcDrawGiftRuleConfigService;
import com.hzs.activity.draw.service.IAcDrawRuleConfigService;
import com.hzs.activity.draw.vo.AcDrawGiftRuleConfigVo;
import com.hzs.activity.pick.service.IAcPickUpConfigService;
import com.hzs.activity.recommend.param.AcRecommendParam;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ActivityMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.activity.base.AcBaseConfig;
import com.hzs.common.domain.activity.base.AcGoalMemberConfig;
import com.hzs.common.domain.activity.base.AcPickUpConfig;
import com.hzs.common.domain.activity.base.ext.AcGiftConfigExt;
import com.hzs.common.domain.activity.draw.AcDrawGiftRuleConfig;
import com.hzs.common.domain.activity.draw.AcDrawRuleConfig;
import com.hzs.common.domain.activity.draw.ext.AcDrawGiftRuleConfigExt;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 抽奖活动配置 前端控制器
 * </p>
 *
 * @author hzs
 * @since 2023-04-21
 */
@RestController
@RequestMapping("/manage/draw-gift-config")
public class AcDrawGiftRuleConfigController extends BaseController {
    @Autowired
    private IAcGiftConfigService waresGiftConfigService;
    @Autowired
    private IAcPickUpConfigService pickUpConfigService;
    @Autowired
    private IAcGoalMemberConfigService goalMemberConfigService;
    @Autowired
    private IAcBaseConfigService baseConfigService;
    @Autowired
    private IActivityService IActivityService;
    @Autowired
    private IAcDrawRuleConfigService drawRuleConfigService;
    @Autowired
    private IAcDrawGiftRuleConfigService drawGiftConfigService;

    @Autowired
    private UserTokenService userTokenService;
    /**
     * 新增抽奖活动配置
     */
    @PostMapping("raffle-activity")
    public AjaxResult saveRaffleActivity(ActivityParam activityParam){
        activityParam.setPkCountry(SecurityUtils.getPkCountry());
        activityParam.setPkCreator(SecurityUtils.getUserId());
        IActivityService.saveRaffleActivity(activityParam);
        return AjaxResult.success();
    }

    /**
     * 在线签呈
     *
     * @param recommendParam 直推参数
     * @return AjaxResult
     */
    @Log(module = EOperationModule.AC_RECOMMEEND_CONFIG, method = EOperationMethod.INSERT, remark = "抽奖在线配置")
    @PostMapping("/online-petition")
    public AjaxResult onLinePetition(@RequestBody AcRecommendParam recommendParam) {
        if (recommendParam.getActivityParam().getDrawGiftConfigList() != null){
            for (AcDrawGiftRuleConfigVo acDrawGiftRuleConfigVo : recommendParam.getActivityParam().getDrawGiftConfigList()) {
                if (StringUtils.isBlank(acDrawGiftRuleConfigVo.getGiftName()) || StringUtils.isBlank(acDrawGiftRuleConfigVo.getGiftCover())){
                    return AjaxResult.error(ActivityMsgConstants.DRAW_RULE_COMPLETE_INFO);
                }
            }
        }
        recommendParam.setPkCountry(SecurityUtils.getPkCountry());
        recommendParam.setPkMember(SecurityUtils.getUserId());
        recommendParam.setLoginUser(userTokenService.getLoginUser());
        return toAjax(drawGiftConfigService.onLinePetition(recommendParam));
    }

    /**
     * 抽奖列表
     * @return
     */
    @GetMapping("list")
    public TableDataInfo list(DrawGiftConfigParam drawGiftConfigParam){
        drawGiftConfigParam.setActType(EActType.LOTTERY_DRAW.getValue());
        drawGiftConfigParam.setPkCountry(SecurityUtils.getPkCountry());
 //       startPage();
        List<AcDrawGiftRuleConfigExt> drawGiftConfigList = drawGiftConfigService.queryList(drawGiftConfigParam);
        for (AcDrawGiftRuleConfigExt acDrawGiftRuleConfigExt : drawGiftConfigList) {
            // 判断活动状态
            // 开始时间
            long startTime = acDrawGiftRuleConfigExt.getActStartDate().getTime();
            // 结束时间
            long endTime = acDrawGiftRuleConfigExt.getActEndDate().getTime();
            // 当前时间
            long currentTime = DateUtils.currentDate().getTime();
            if (currentTime >= startTime && currentTime < endTime) {
                // 当前时间大于开始 小于结束
                acDrawGiftRuleConfigExt.setStatus(EActivityStatus.IN_PROGRESS.getLabel());
            } else if (currentTime < startTime) {
                // 当前时间小于开始时间
                acDrawGiftRuleConfigExt.setStatus(EActivityStatus.NOT_STARTED.getLabel());
            } else {
                // 当前时间大于结束时间
                acDrawGiftRuleConfigExt.setStatus(EActivityStatus.EXPIRED.getLabel());
            }
            // 抽奖奖品发放方式
            if (acDrawGiftRuleConfigExt.getGrantWay() != null){
                acDrawGiftRuleConfigExt.setGrantWayStr(EGrantWay.getEGrantWay(acDrawGiftRuleConfigExt.getGrantWay()));
            }

        }
        return getDataTable(drawGiftConfigList);
    }
    /**
     * 抽奖配置导出
     */
    @PostMapping("export")
    public  void export(DrawGiftConfigParam drawGiftConfigParam, HttpServletResponse response){
        drawGiftConfigParam.setActType(EActType.LOTTERY_DRAW.getValue());
        drawGiftConfigParam.setPkCountry(SecurityUtils.getPkCountry());
        //       startPage();
        List<AcDrawGiftRuleConfigExt> drawGiftConfigList = drawGiftConfigService.queryList(drawGiftConfigParam);
        for (AcDrawGiftRuleConfigExt acDrawGiftRuleConfigExt : drawGiftConfigList) {
            // 判断活动状态
            // 开始时间
            long startTime = acDrawGiftRuleConfigExt.getActStartDate().getTime();
            // 结束时间
            long endTime = acDrawGiftRuleConfigExt.getActEndDate().getTime();
            // 当前时间
            long currentTime = DateUtils.currentDate().getTime();
            if (currentTime >= startTime && currentTime < endTime) {
                // 当前时间大于开始 小于结束
                acDrawGiftRuleConfigExt.setStatus(EActivityStatus.IN_PROGRESS.getLabel());
            } else if (currentTime < startTime) {
                // 当前时间小于开始时间
                acDrawGiftRuleConfigExt.setStatus(EActivityStatus.NOT_STARTED.getLabel());
            } else {
                // 当前时间大于结束时间
                acDrawGiftRuleConfigExt.setStatus(EActivityStatus.EXPIRED.getLabel());
            }
            // 抽奖奖品发放方式
            if (acDrawGiftRuleConfigExt.getGrantWay() != null){
                acDrawGiftRuleConfigExt.setGrantWayStr(EGrantWay.getEGrantWay(acDrawGiftRuleConfigExt.getGrantWay()));
            }
        }
        for (AcDrawGiftRuleConfigExt acDrawGiftRuleConfigExt : drawGiftConfigList) {
            acDrawGiftRuleConfigExt.setCreationTimeCopy(acDrawGiftRuleConfigExt.getCreationTime());
        }
        ExcelUtil<AcDrawGiftRuleConfigExt> util = new ExcelUtil<>(AcDrawGiftRuleConfigExt.class);
        util.exportExcel(response, drawGiftConfigList, "抽奖配置导出");
    }
    /**
     * 查询抽奖信息详情
     * @param pkId
     * @return
     */
    @GetMapping("detail")
    public AjaxResult detail(Long pkId){
        AcBaseConfig baseConfig = baseConfigService.getById(pkId);
        ActivityParam activityParam = BeanUtil.copyProperties(baseConfig, ActivityParam.class);
        //查询目标群体
        QueryWrapper<AcGoalMemberConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_BASE_ID",baseConfig.getPkId());
        List<AcGoalMemberConfig> goalMemberConfigList = goalMemberConfigService.list(queryWrapper);
        activityParam.setGoalMemberConfigList(goalMemberConfigList);
        // 抽奖活动赠品配置
        QueryWrapper<AcDrawGiftRuleConfig> qu = new QueryWrapper<>();
        qu.eq("PK_BASE_ID",baseConfig.getPkId());
        List<AcDrawGiftRuleConfig> drawGiftConfigList = drawGiftConfigService.list(qu);
        List<AcDrawGiftRuleConfigVo> dgList = drawGiftConfigList.stream().map(dg -> {
            AcDrawGiftRuleConfigVo acDrawGiftRuleConfigVo = BeanUtil.copyProperties(dg, AcDrawGiftRuleConfigVo.class);
//            QueryWrapper<AcGiftConfig> wr = new QueryWrapper<>();
//            wr.eq("PK_RULE_ID",dg.getPkId());
//            List<AcGiftConfig> list = waresGiftConfigService.list(wr);
            List <AcGiftConfigExt> list =  waresGiftConfigService.queryListByRuleIdList(dg.getPkId(),SecurityUtils.getPkCountry());
            acDrawGiftRuleConfigVo.setGiftConfigList(list);
            return acDrawGiftRuleConfigVo;
        }).collect(Collectors.toList());
        activityParam.setDrawGiftConfigList(dgList);
        // 抽奖赠送次数规则配置表
        List<AcDrawRuleConfigParam> drawRuleConfigParamList = new ArrayList<>();
        for (ESpecialArea value : ESpecialArea.values()) {

            QueryWrapper<AcDrawRuleConfig> qe = new QueryWrapper<AcDrawRuleConfig>();
            qe.eq("PK_BASE_ID",baseConfig.getPkId());
            qe.eq("ORDER_TYPE",value.getValue());
            List<AcDrawRuleConfig> drawRuleConfigList = drawRuleConfigService.list(qe);
            if (drawRuleConfigList.size() > 0){
                AcDrawRuleConfigParam drawRuleConfigParam = new AcDrawRuleConfigParam();
                drawRuleConfigParam.setOrderType(value.getValue());
                drawRuleConfigParam.setDrawRuleConfigList(drawRuleConfigList);
                drawRuleConfigParamList.add(drawRuleConfigParam);
            }
        }
        activityParam.setDrawRuleConfigParam(drawRuleConfigParamList);
        QueryWrapper<AcPickUpConfig> qwe = new QueryWrapper<>();
        qwe.eq("PK_BASE_ID",pkId);
        AcPickUpConfig pickUpConfig = pickUpConfigService.getOne(qwe);
        if (pickUpConfig != null){
            activityParam.setAcPickUpConfig(pickUpConfig);
        }
        return AjaxResult.success(activityParam);
    }


    /**
     * 删除
     * @param pkId
     * @return
     */
    @DeleteMapping("/{pkId}")
    public AjaxResult remove(@PathVariable Integer pkId) {

        drawGiftConfigService.removeDrawGiftConfig(pkId);
        return AjaxResult.success();
    }



}
