package com.dgtly.wxportal.controller;


import com.alibaba.fastjson2.JSON;
import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.core.controller.ApiBaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.ParameterObject;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.system.domain.*;
import com.dgtly.system.service.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.ApiOperation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 弹框日志Controller
 *
 * @author chenyn
 * @date 2023-06-13
 */
@Api(tags = "微信弹框相关接口")
@RestController
@RequestMapping("/wxAlert")
@ApiPassToken
@Slf4j
public class WxAlertLogController  extends ApiBaseController {
    @Autowired
    private IAlertLogService alertLogService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserExtService sysUserExtService;
    @Autowired
    private IAlertConfigurationService alertConfigurationService;
    @Autowired
    private IAlertUpvoteLogService alertUpvoteLogService;

    @Autowired
    private ISysUserShopExtService sysUserShopExtService;


    @ApiOperation(value = "微信弹框",notes = "参数：{userId:1}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/getAlert")
    public Object getAlertLog() throws ParseException {
        ParameterObject obj = getParameterObject();
        Long userId = Long.valueOf(obj.getString("userId"));
        String userTp = obj.getString("userType");
        log.info("当前系统进来为{}",userTp);
        AlertConfiguration alertConfiguration1 = alertConfigurationService.selectAlert(userTp);
        //是否有启动弹窗
        log.info("本次匹配的弹窗:{}",JSON.toJSON(alertConfiguration1));
        if (alertConfiguration1 != null){
            //有启动
            alertConfiguration1.setIsClearCache(false);
            Date datez = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String now = sdf.format(datez);
            Date date = sdf.parse(now);
            int i = date.compareTo(alertConfiguration1.getAlertStartTime());
            int i1 = date.compareTo(alertConfiguration1.getAlertEndTime());
            if (i >= 0 && i1 < 0) {
                AlertLog alertLog = alertLogService.selectAlertLogByUserIdAndAlertId(userId, alertConfiguration1.getAlertId(),userTp,userTp);
                if (alertLog!=null){
                    if (alertLog.getAlertNum()<alertConfiguration1.getAlertNum()){
                        updateAlertLog(alertConfiguration1,alertLog,sdf,"1");
                        return AjaxResult.success(alertConfiguration1);
                    }else {
                        return AjaxResult.warning("每日弹出次数已满");
                    }
                }else {
                    intAlertLog(alertConfiguration1,"1",now,sdf,userId,userTp);
                    return AjaxResult.success(alertConfiguration1);
                }
            } else {
                //超时
                return AjaxResult.warning("时间超时");
            }
        }else {
            //无启动
            return AjaxResult.warning("没有启动的弹框");
        }
    }

    public void  updateAlertLog(AlertConfiguration alertConfiguration,AlertLog alertLog,SimpleDateFormat sdf,String isClearCache)throws ParseException {
        Long count =alertLog.getAlertNum()+1;
        // 创建两个日期对象
        Date date1 = getTimeStampV1(null,sdf,alertLog.getCreateTime());
        Date date2 = getTimeStampV2(sdf,alertConfiguration.getAlertEndTime());
        int clearT = date1.compareTo(date2);
        if(count == alertConfiguration.getAlertNum() && clearT==0){
            alertConfiguration.setIsClearCache(true);
            alertLog.setIsClearCache(isClearCache);
        }
        alertLog.setAlertNum(count);
        alertLogService.updateAlertLog(alertLog);
    }
    //初始化AlertLog对象
    public  void intAlertLog(AlertConfiguration alertConfiguration,String isClearCache,String now,SimpleDateFormat sdf,Long userId,String userType) throws ParseException {
        //加数据
        AlertLog alertLog1 = initAlertLog(userId,alertConfiguration.getAlertId());
        alertLog1.setUserType(userType);
        // 创建两个日期对象
        Date date1 = getTimeStampV1(now,null,null);
        Date date2 = getTimeStampV2(sdf,alertConfiguration.getAlertEndTime());
        int clearT = date1.compareTo(date2);
        if(clearT==0 && alertConfiguration.getAlertNum() == 1){
            alertConfiguration.setIsClearCache(true);
            alertLog1.setIsClearCache(isClearCache);
        }
        alertLogService.insertAlertLog(alertLog1);
    }

    //创建两个日期对象1
    public static Date getTimeStampV1(String now,SimpleDateFormat sdf,Date lertEndTime) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 设置时间部分为零点
        Calendar calendar = Calendar.getInstance();
        if (StringUtils.isEmpty(now)){
            calendar.setTime(dateFormat.parse(sdf.format(lertEndTime)));
        }else {
            calendar.setTime(dateFormat.parse(now));
        }
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date date = calendar.getTime();
        return date;
    }

    //创建两个日期对象2
    public static Date getTimeStampV2(SimpleDateFormat sdf,Date lertEndTime) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateFormat.parse(sdf.format(lertEndTime)));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date date = calendar.getTime();
        return date;
    }
    //封装相同逻辑
    public AlertLog initAlertLog(Long userId,Long alertId){
        AlertLog alertLog1 = new AlertLog();
        alertLog1.setAlertId(alertId);
        alertLog1.setUserId(userId);
        alertLog1.setAlertNum(1L);
        return alertLog1;
    }


    @ApiOperation(value = "点赞状态",notes = "参数：{userId:1,alertId:1,status:1}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("/getUpvoteStatus")
    public Object getUpvoteStatus() throws ParseException {
        ParameterObject obj = getParameterObject();
        Long userId = Long.valueOf(obj.getString("userId"));//用户ID
//        String loginName = String.valueOf(obj.getString("loginName"));//用户账号
//        String userName = String.valueOf(obj.getString("userName"));//用户姓名
        Long alertId = Long.valueOf(obj.getString("alertId"));//弹框ID
//        String alertContent = String.valueOf(obj.getString("alertContent"));//弹框内容
//        String photoUrl = String.valueOf(obj.getString("photoUrl"));//弹框图片
        Integer status=3;//如果没有传status，为查询
        if (obj.getString("status")!=null){
            status = Integer.valueOf(obj.getString("status"));//状态
        }
        //根据用户ID、弹框ID查询是否有记录，，没有新增记录
        AlertUpvoteLog alertUpvoteLog = alertUpvoteLogService.selectUpvoteByUidAndAid(userId, alertId);
        if (alertUpvoteLog!=null){
            //如果有 修改记录
            if (status!=3) {
                alertUpvoteLog.setStatus(status);
            }
//            alertUpvoteLog.setLoginName(loginName);
//            alertUpvoteLog.setUserName(userName);
//            alertUpvoteLog.setAlertContent(alertContent);
//            alertUpvoteLog.setPhotoUrl(photoUrl);
            alertUpvoteLogService.updateAlertUpvoteLog(alertUpvoteLog);
            return AjaxResult.success(alertUpvoteLog);
        }else {
            //没有新增记录
            AlertUpvoteLog upvoteLog = new AlertUpvoteLog();
            upvoteLog.setUserId(userId);
            upvoteLog.setAlertId(alertId);
//            upvoteLog.setLoginName(loginName);
//            upvoteLog.setUserName(userName);
//            upvoteLog.setAlertContent(alertContent);
//            upvoteLog.setPhotoUrl(photoUrl);
            if (status!=3) {
                upvoteLog.setStatus(status);
            }else{
                upvoteLog.setStatus(0);
            }
            alertUpvoteLogService.insertAlertUpvoteLog(upvoteLog);
            return AjaxResult.success(upvoteLog);
        }
    }
}
