package com.gree.mall.miniapp.logic.acitivy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.gree.mall.miniapp.bean.promotion.PromotionQuestionnaireAddBean;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.plus.entity.PromotionActivity;
import com.gree.mall.miniapp.plus.entity.PromotionQuestionnaire;
import com.gree.mall.miniapp.plus.entity.PromotionQuestionnaireItem;
import com.gree.mall.miniapp.plus.entity.PromotionQuestionnaireUser;
import com.gree.mall.miniapp.plus.service.PromotionActivityService;
import com.gree.mall.miniapp.plus.service.PromotionQuestionnaireItemService;
import com.gree.mall.miniapp.plus.service.PromotionQuestionnaireService;
import com.gree.mall.miniapp.plus.service.PromotionQuestionnaireUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * 问卷活动业务
 * @author ：lijh
 * @description：TODO
 * @date ：2024/5/7 10:31
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PromotionQuestionnaireLogic {

    private final CommonLogic commonLogic;

    private final PromotionQuestionnaireService promotionQuestionnaireService;
    private final PromotionQuestionnaireItemService promotionQuestionnaireItemService;
    private final PromotionQuestionnaireUserService promotionQuestionnaireUserService;

    private final PromotionActivityService promotionActivityService;

    /**
     * 问卷活动列表
     * @param status 1=进行中 2=已过期 9=我参与的
     * @return
     */
    public List<PromotionQuestionnaire> list(Integer status){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();

        List<PromotionActivity> promotionActivities = promotionActivityService.lambdaQuery().eq(PromotionActivity::getUserId, currentCompanyWechat.getUserId()).list();
        if(CollectionUtils.isEmpty(promotionActivities) && status != null && status == 9){
            return new ArrayList<>();
        }
        List<String> ids = promotionActivities.stream().map(PromotionActivity::getPromotionQuestionnaireId).collect(Collectors.toList());

        List<PromotionQuestionnaire> list = promotionQuestionnaireService.lambdaQuery()
                .eq(PromotionQuestionnaire::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .eq(PromotionQuestionnaire::getIsShow,true)
                .le(status == null || status == 1,PromotionQuestionnaire::getStartTime, new Date())
                .ge(status == null || status == 1,PromotionQuestionnaire::getEndTime, new Date())
                .eq(status == null || status == 1,PromotionQuestionnaire::getIsStop, false)
                .and(status != null && status == 2,
                        v -> v.lt(PromotionQuestionnaire::getEndTime,new Date())
                        .or().eq(PromotionQuestionnaire::getIsStop,true)
                )
                .in(status != null && status == 9,PromotionQuestionnaire::getId,ids)
                .orderByDesc(PromotionQuestionnaire::getCreateTime)
                .list();
        return list;
    }


    /**
     * 问卷活动详情
     * @param id
     * @return
     */
    public PromotionQuestionnaireAddBean detail(String id){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        PromotionQuestionnaire promotionQuestionnaire = promotionQuestionnaireService.getById(id);
        PromotionQuestionnaireAddBean bean = BeanUtil.copyProperties(promotionQuestionnaire, PromotionQuestionnaireAddBean.class);
        if(!promotionQuestionnaire.getIsShow()){
            throw new RemoteServiceException("当前活动已结束");
        }
        //提交记录
        List<PromotionQuestionnaireUser> trueUserList = new ArrayList<>();
        //真实的提交记录
        List<PromotionActivity> activityList = promotionActivityService.lambdaQuery()
                .eq(PromotionActivity::getPromotionQuestionnaireId, id)
                .ge(PromotionActivity::getCreateTime,DateUtil.offsetMinute(new Date(),-10))
                .orderByDesc(PromotionActivity::getCreateTime).last("limit 100").list();
        for(PromotionActivity promotionActivity : activityList){
            PromotionQuestionnaireUser pu = new PromotionQuestionnaireUser();
            pu.setName(promotionActivity.getUserName());
            pu.setMobile(promotionActivity.getUserMobile());
            pu.setRemark(promotionQuestionnaire.getTitle());
            pu.setMin((int) DateUtil.between(new Date(),promotionActivity.getCreateTime(), DateUnit.MINUTE));
            pu.setCreateTime(promotionActivity.getCreateTime());
            trueUserList.add(pu);
        }

        List<PromotionQuestionnaireUser> promotionQuestionnaireUsers = promotionQuestionnaireUserService.lambdaQuery().eq(PromotionQuestionnaireUser::getPromotionQuestionnaireId, id).list();
        trueUserList.addAll(promotionQuestionnaireUsers);

        for(PromotionQuestionnaireUser pu : trueUserList){
            if(pu.getName() != null && pu.getName().length() > 1) {
                pu.setName(pu.getName().substring(0,1) + "**");
            }
            if(pu.getMobile() != null && pu.getMobile().length() == 11) {
                pu.setMobile(pu.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
        }
        bean.setPromotionQuestionnaireUsers(trueUserList);
        //题目
        List<PromotionQuestionnaireItem> promotionQuestionnaireItems = promotionQuestionnaireItemService.lambdaQuery().eq(PromotionQuestionnaireItem::getPromotionQuestionnaireId, id).list();
        bean.setPromotionQuestionnaireItems(promotionQuestionnaireItems);
        //状态
        if(bean.getIsStop()){
            bean.setStatus(3);
        }else {
            if (bean.getStartTime().getTime() > new Date().getTime()) {
                bean.setStatus(0);
            } else if (bean.getEndTime().getTime() < new Date().getTime()) {
                bean.setStatus(2);
            } else {
                bean.setStatus(1);
            }
        }
        //已提交次数
        Integer count = promotionActivityService.lambdaQuery()
                .eq(PromotionActivity::getPromotionQuestionnaireId, id)
                .eq(PromotionActivity::getUserId, currentCompanyWechat.getUserId()).count();
        //剩余可提交次数
        bean.setLimit(bean.getSubmitLimit() - count < 0 ? 0 : bean.getSubmitLimit() - count);
        return bean;
    }

}
