package com.template.controller;


import com.template.api.SmartScreenshotRecordControllerAPI;
import com.template.common.utils.TimeExchange;
import com.template.common.utils.paramUtils;
import com.template.mapper.SmartFreezeRecordMapper;
import com.template.model.pojo.*;
import com.template.model.pojo.SmartScreenshotRecord;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.ScreenshotRecordPageVo;
import com.template.services.SmartFreezeRecordService;
import com.template.services.SmartScreenshotRecordService;
import com.template.services.SmartScreenshotService;
import com.template.services.SmartUserService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-12-04
 */
@RestController
public class SmartScreenshotRecordController implements SmartScreenshotRecordControllerAPI {

    @Autowired
    private SmartScreenshotRecordService smartScreenshotRecordService;
    @Autowired
    private SmartFreezeRecordService smartFreezeRecordService;
    @Autowired
    private SmartScreenshotService smartScreenshotService;
    @Autowired
    private SmartUserService smartUserService;

    /**
     * 新增截屏记录
     *
     * @param smartApply    截屏记录数据
     * @param bindingResult
     * @return
     */
    @Override
    public CommonResult insertSmartScreenshotRecord(SmartScreenshotRecord smartApply, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        int result = smartScreenshotRecordService.insertSmartScreenshotRecord(smartApply);

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

    /**
     * 更新截屏记录
     *
     * @param sa            截屏记录数据
     * @param bindingResult
     * @return
     */
    @Override
    public CommonResult updateSmartScreenshotRecordById(SmartScreenshotRecord sa, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        int result = smartScreenshotRecordService.updateSmartScreenshotRecord(sa);
        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
    }

    /**
     * 截屏记录分页数据查询
     *
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @param name        查询名称
     * @return
     */
    @Override
    public CommonResult queryPageSmartScreenshotRecord(int currentPage, int pageCount, String name) {
        PageUtils<SmartScreenshotRecord> result = smartScreenshotRecordService.queryPageSmartScreenshotRecords(currentPage, pageCount, name);

        return CommonResult.ok(result);
    }


    @Override
    public CommonResult deleteSmartScreenshotRecordById(int id) {

        SmartScreenshotRecord data = smartScreenshotRecordService.getSmartById(id);

        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = smartScreenshotRecordService.deleteSmartScreenshotRecordById(id);

        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult userScreenshotRecord(int userId) throws Exception {
        //查找用户信息是否存在
        SmartUser result = smartUserService.getSmartById(userId);
        if (result == null) {
            return CommonResult.fail("用户信息无效，无法记录截屏操作");
        }

        //如果是在被冻结的情况下就不处理
        int count = smartFreezeRecordService.getSmartByUserId(userId);
        if (count > 0) {
            return CommonResult.fail("冻结期间，无法记录截屏操作");
        }

        //需要查看是否触发惩罚规则 触发了就去进行惩罚相关操作 将记录写进冻结记录表中
        //当前用户的截屏记录次数
        int screenshotNum = smartScreenshotRecordService.querySmartScreenshotRecords(userId);
        SmartScreenshot existData = smartScreenshotService.getSmartLastOneByTimes(screenshotNum + 1);

        SmartFreezeRecord sfr = null;

        if (existData != null) {
            sfr = new SmartFreezeRecord();
            sfr.setUserId(userId);
            sfr.setType(1);
            switch (existData.getTriggers()) {
                case 0:
                    //身份码提醒：提醒当前用户还有多少次就会触发冻结操作
                    sfr = null;
                    break;
                case 1:
                    //冻结1小时
                    sfr.setDeadline(DateUtils.addHours(new Date(), 1));
                    sfr.setReason("触发截屏"+(screenshotNum + 1)+"次数规则，冻结1小时");
                    break;
                case 2:
                    //冻结2小时
                    sfr.setDeadline(DateUtils.addHours(new Date(), 2));
                    sfr.setReason("触发截屏"+(screenshotNum + 1)+"次数规则，冻结1小时");
                    break;
                case 3:
                    //冻结4小时
                    sfr.setDeadline(DateUtils.addHours(new Date(), 4));
                    sfr.setReason("触发截屏"+(screenshotNum + 1)+"次数规则，冻结4小时");
                    break;
                case 4:
                    //冻结8小时
                    sfr.setDeadline(DateUtils.addHours(new Date(), 8));
                    sfr.setReason("触发截屏"+(screenshotNum + 1)+"次数规则，冻结8小时");
                    break;
                case 5:
                    //冻结1天
                    sfr.setDeadline(DateUtils.addHours(new Date(), 24));
                    sfr.setReason("触发截屏"+(screenshotNum + 1)+"次数规则，冻结1天");
                    break;
                default:
                    sfr = null;
                    break;
            }
        }

        SmartScreenshotRecord ssr = new SmartScreenshotRecord();
        ssr.setUserId(userId);
        ssr.setIsFreeze(1);

        try {
            int insertSsr = smartScreenshotRecordService.insertSmartScreenshotRecord(ssr);
            if (insertSsr <= 0) {
                throw new Exception("记录失败");
            }

            if (sfr != null) {
                int insertSfr = smartFreezeRecordService.insertSmartFreezeRecord(sfr);
                if (insertSfr <= 0) {
                    throw new Exception("记录失败");
                }
            }

        } catch (Exception e) {
            throw new Exception("记录失败");
        }

        return CommonResult.ok("记录成功");
    }

    /**
     * 截屏记录分页数据查询
     *
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @return
     */
    @Override
    public CommonResult queryScreenshotRecordPageList(int currentPage, int pageCount) {
        PageUtils<ScreenshotRecordPageVo> result = smartScreenshotRecordService.queryScreenshotRecordPageList(currentPage, pageCount);

        if (result.getList() != null && result.getList().size() > 0) {
            List<Integer> userIds = result.getList().stream().map(ScreenshotRecordPageVo::getUserId).distinct().collect(Collectors.toList());
            List<SmartFreezeRecord> freezeRecords = smartFreezeRecordService.getSmartByUserIds(userIds);
            for (ScreenshotRecordPageVo data : result.getList()) {
                long count = freezeRecords.stream().filter(e -> e.getUserId().equals(data.getUserId())).count();
                data.setIsShow(count > 0 ? 0 : 1);
            }
        }

        return CommonResult.ok(result);
    }

}

