package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.StaffManage;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.staffTrain.StaffTrainManual;
import com.ruoyi.system.mapper.StaffTrainManualMapper;
import com.ruoyi.system.service.IStaffTrainManualService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.ruoyi.common.constant.CacheConstants.READ_TRAIN;
import static com.ruoyi.common.constant.CacheConstants.READ_TRAIN_TIME;

/**
 * 员工培训手册Service业务层处理
 *
 * @author boman
 * @date 2025-02-18
 */
@Service
public class StaffTrainManualServiceImpl implements IStaffTrainManualService {
    @Autowired
    private StaffTrainManualMapper staffTrainManualMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询员工培训手册
     *
     * @param manualId 员工培训手册主键
     * @return 员工培训手册
     */
    @Override
    public StaffTrainManual selectStaffTrainManualByManualId(Long manualId) {

        //获取该培训手册对象阅读人员的value值
        List<String> valueList = redisCache.getCacheList(READ_TRAIN + manualId);
        //获取当前登录人的员工信息
        StaffManage staffManage = SecurityUtils.getLoginUser().getStaffManage();
        //获取员工姓名
        String staffName = "未知";
        if (staffManage != null) {
            staffName = staffManage.getStaffName();
        }
        //组装value值
        String value = SecurityUtils.getUserId() + ":" + staffName;
        if (valueList != null && valueList.size() > 0) {
            //如果value不重复则新增
            if (!valueList.contains(value)) {
                //阅读名单存储到redis key = read_train:manualId value = userId+":"+员工姓名
                valueList.add(value);
                redisCache.deleteObject(READ_TRAIN + manualId);
                redisCache.setCacheList(READ_TRAIN + manualId, valueList);
                //新增阅读时间
                //key = read_train_time:manualId:userId
                redisCache.setCacheObject(READ_TRAIN_TIME + manualId + ":" + SecurityUtils.getUserId(), DateUtils.getTime());
            }else {
                //更新阅读时间
                //key = read_train_time:manualId:userId
                redisCache.setCacheObject(READ_TRAIN_TIME + manualId + ":" + SecurityUtils.getUserId(), DateUtils.getTime());
            }
        }else {
            //新增第一个阅读人员
            List<String> stringList = new ArrayList<>();
            stringList.add(value);
            redisCache.setCacheList(READ_TRAIN + manualId, stringList);
            //key = read_train_time:manualId:userId
            redisCache.setCacheObject(READ_TRAIN_TIME + manualId + ":" + SecurityUtils.getUserId(), DateUtils.getTime());
        }
        StaffTrainManual staffTrainManual = staffTrainManualMapper.selectStaffTrainManualByManualId(manualId);
        Long viewCount = staffTrainManual.getViewCount();
        staffTrainManual.setViewCount(viewCount+1);
        staffTrainManualMapper.updateStaffTrainManual(staffTrainManual);
        return staffTrainManual;
    }
    /**
     * 查询员工培训手册列表
     *
     * @param staffTrainManual 员工培训手册
     * @return 员工培训手册
     */
    @Override
    public List<StaffTrainManual> selectStaffTrainManualList(StaffTrainManual staffTrainManual) {
        return staffTrainManualMapper.selectStaffTrainManualList(staffTrainManual);
    }

    /**
     * 新增员工培训手册
     *
     * @param staffTrainManual 员工培训手册
     * @return 结果
     */
    @Override
    public int insertStaffTrainManual(StaffTrainManual staffTrainManual) {
        staffTrainManual.setCreateTime(DateUtils.getNowDate());
        return staffTrainManualMapper.insertStaffTrainManual(staffTrainManual);
    }

    /**
     * 修改员工培训手册
     *
     * @param staffTrainManual 员工培训手册
     * @return 结果
     */
    @Override
    public int updateStaffTrainManual(StaffTrainManual staffTrainManual) {
        staffTrainManual.setUpdateTime(DateUtils.getNowDate());
        return staffTrainManualMapper.updateStaffTrainManual(staffTrainManual);
    }

    /**
     * 批量删除员工培训手册
     *
     * @param manualIds 需要删除的员工培训手册主键
     * @return 结果
     */
    @Override
    public int deleteStaffTrainManualByManualIds(Long[] manualIds) {
        return staffTrainManualMapper.deleteStaffTrainManualByManualIds(manualIds);
    }

    /**
     * 删除员工培训手册信息
     *
     * @param manualId 员工培训手册主键
     * @return 结果
     */
    @Override
    public int deleteStaffTrainManualByManualId(Long manualId) {
        return staffTrainManualMapper.deleteStaffTrainManualByManualId(manualId);
    }

    /**
     * 获取已读人员名单
     */
    @Override
    public AjaxResult getRead(StaffTrainManual staffTrainManual) {
        //定义返回值
        List<Map<String, String>> resultList = new ArrayList<>();
        //String searchValue = staffTrainManual.getSearchValue();
        String author = staffTrainManual.getAuthor();
        Date searchTime = staffTrainManual.getCreateTime();
        Long manualId = staffTrainManual.getManualId();

        List<String> valueList = redisCache.getCacheList(READ_TRAIN + manualId);
        if (valueList != null && valueList.size() > 0) {
            //value = userId+":"+员工姓名
            for (String value : valueList) {
                String[] split = value.split(":");
                //key = read_train:manualId:userId
                String readTime = redisCache.getCacheObject(READ_TRAIN_TIME  + manualId + ":" + split[0]);
                Map<String, String> map = new HashMap<>(2);
                if (StringUtils.isBlank(author) && searchTime == null) {
                    map.put("name", split[1]);
                    //key = read_train:manualId:userId
                    map.put("time", readTime);
                    resultList.add(map);
                }
                //如果搜索姓名不为空
                else if (StringUtils.isNotBlank(author)) {
                    //如果搜索日期不为空
                    if (searchTime != null) {
                        // 创建日期格式化对象
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        LocalDateTime dateTime = LocalDateTime.parse(readTime, formatter);
                        // 构造仅包含年月日的新时间字符串
                        LocalDate date = dateTime.toLocalDate();
                        String formattedDate = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        //split[1] = 员工姓名
                        if (split[1].contains(author) && sdf.format(searchTime).equals(formattedDate)) {
                            map.put("name", split[1]);
                            map.put("time", readTime);
                            resultList.add(map);
                        }
                    } else {
                        //搜索日期为空
                        if (split[1].contains(author)) {
                            map.put("name", split[1]);
                            map.put("time", readTime);
                            resultList.add(map);
                        }
                    }
                } else if (searchTime != null) {
                    // 创建日期格式化对象
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime dateTime = LocalDateTime.parse(readTime, formatter);
                    // 构造仅包含年月日的新时间字符串
                    LocalDate date = dateTime.toLocalDate();
                    String formattedDate = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    if (StringUtils.isNotBlank(author)) {
                        if (author.equals(split[1]) && sdf.format(searchTime).equals(formattedDate)) {
                            map.put("name", split[1]);
                            map.put("time", readTime);
                            resultList.add(map);
                        }
                    } else {
                        if (sdf.format(searchTime).equals(formattedDate)) {
                            map.put("name", split[1]);
                            map.put("time", readTime);
                            resultList.add(map);
                        }
                    }
                }else {
                    map.put("name", split[1]);
                    map.put("time", readTime);
                    resultList.add(map);
                }
            }
        }
        return AjaxResult.success(resultList);
    }
}
