package com.ruoyi.zzb.study.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.zzb.study.domain.StudyDocInfo;
import com.ruoyi.zzb.study.domain.StudyViewLogInfo;
import com.ruoyi.zzb.study.domain.UserSearchParam;
import com.ruoyi.zzb.study.domain.req.QueryInfoVO;
import com.ruoyi.zzb.study.domain.req.UpdatePageViewNumVO;
import com.ruoyi.zzb.study.mapper.StudyDocInfoMapper;
import com.ruoyi.zzb.study.mapper.StudyViewLogInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@DataSource(value = DataSourceType.SLAVE)
public class StudyService {

    @Autowired
    private StudyDocInfoMapper studyDocInfoMapper;

    @Autowired
    private StudyViewLogInfoMapper studyViewLogInfoMapper;



    public Page<StudyDocInfo>  findAllInfo(UserSearchParam searchParam) {
        //分页参数
        Page<StudyDocInfo> rowPage = new Page(searchParam.getPageIndex(), searchParam.getPageSize());

        //查询条件
        LambdaQueryWrapper<StudyDocInfo> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(searchParam.getTitle())){
            queryWrapper.like(StudyDocInfo::getTitle,searchParam.getTitle());
        }
        if (StringUtils.isNotBlank(searchParam.getDatasourceCode())) {
            queryWrapper.eq(StudyDocInfo::getDatasourceCode, searchParam.getDatasourceCode());
        }

        //排序
        queryWrapper.orderByAsc(StudyDocInfo::getOrderNum);
        queryWrapper.orderByAsc(StudyDocInfo::getCreateTime);
        //分页查询
        rowPage = studyDocInfoMapper.selectPage(rowPage, queryWrapper);
        log.info("============【学习助手】查询学习文章列表成功！============");
        return rowPage;

    }

    public StudyDocInfo findDocInfoById(String id) {
        LambdaQueryWrapper<StudyDocInfo>  queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(StudyDocInfo::getDocId,id);

        StudyDocInfo studyDocInfo= studyDocInfoMapper.selectOne(queryWrapper);

        if(studyDocInfo == null){
            throw new RuntimeException("文章详情查询失败，docId不存在:"+id);
        }
        log.info("============【学习助手】查询文章成功！{}============",id);
        return studyDocInfo;
    }

    public boolean saveDocInfo(StudyDocInfo studyDocInfo) {
        int i = studyDocInfoMapper.insert(studyDocInfo);
        if( i!=1 ){
            throw new RuntimeException("数据写入失败，成功0条,入参："+JSONObject.toJSONString(studyDocInfo));
        }
        log.info("============【学习助手】添加文章成功！============");
        return i == 1;
    }

    public boolean deleteById(String id) {
        int i = studyDocInfoMapper.deleteById(id);

        if( i!=1 ){
            throw new RuntimeException("数据删除失败，docId不存在:"+id);
        }
        log.info("============【学习助手】删除文章成功！{}============",id);
        return i == 1;
    }


    public boolean updatePageViewNumById(UpdatePageViewNumVO updatePageViewNumVO) {
        UpdateWrapper<StudyDocInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("DOC_ID",updatePageViewNumVO.getDocId()).set("PAGE_VIEW_NUM", updatePageViewNumVO.getPageViewNum());
        Integer i = studyDocInfoMapper.update(null, updateWrapper);

        if( i!=1 ){
            throw new RuntimeException("修改文章浏览量失败，docId不存在:"+updatePageViewNumVO.getDocId());
        }
        log.info("============【学习助手】修改文章浏览量成功！{}============",updatePageViewNumVO.getDocId());
        return i == 1;
    }

    @Transactional
    public boolean saveViewLogInfo(QueryInfoVO queryInfoVO, SysUser sysUser) {


        //记录浏览量+1
        UpdateWrapper<StudyDocInfo> updateDocWrapper = new UpdateWrapper<>();
        updateDocWrapper.eq("DOC_ID", queryInfoVO.getDocId());
        updateDocWrapper.setSql("PAGE_VIEW_NUM = PAGE_VIEW_NUM + 1");
        Integer j =   studyDocInfoMapper.update(null,updateDocWrapper);

        if(j != 1){
            throw new RuntimeException("记录浏览量更新异常，docId不存在："+ queryInfoVO.getDocId());
        }

        //保存访问记录
        StudyViewLogInfo studyViewLogInfo = new StudyViewLogInfo();
        studyViewLogInfo.setDocId(queryInfoVO.getDocId());
        studyViewLogInfo.setUserId(queryInfoVO.getUserId());
        studyViewLogInfo.setUserName(sysUser.getNickName());
        studyViewLogInfo.setUserIdcard(sysUser.getIdCard());
        studyViewLogInfo.setUserPoliceNo(sysUser.getPoliceNo());
        studyViewLogInfo.setParentDeptCode(sysUser.getDept().getParentId()+"");
        studyViewLogInfo.setParentDeptName(sysUser.getDept().getParentName());
        studyViewLogInfo.setDeptCode(sysUser.getDept().getDeptId()+"");
        studyViewLogInfo.setDeptName(sysUser.getDept().getDeptName());
        int i = studyViewLogInfoMapper.insert(studyViewLogInfo);

        if(i != 1){
            throw new RuntimeException("保存访问记录日志保存失败："+JSONObject.toJSONString(studyViewLogInfo));
        }

        log.info("============【学习助手】保存访问记录成功！{}============", queryInfoVO.getDocId());
        return i == 1 && j ==1;
    }



    /**
     * 分页查询用户列表
     */
    public Page<StudyDocInfo> findInfoByTitle(UserSearchParam searchParam)
    {
        //分页参数
        Page<StudyDocInfo> rowPage = new Page(searchParam.getPageIndex(), searchParam.getPageSize());

        //查询条件
        LambdaQueryWrapper<StudyDocInfo> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(searchParam.getTitle()))
        {
            queryWrapper.like(StudyDocInfo::getTitle,searchParam.getTitle());
        }

        //排序
        queryWrapper.orderByAsc(StudyDocInfo::getOrderNum);
        queryWrapper.orderByAsc(StudyDocInfo::getCreateTime);
        //分页查询
        rowPage = studyDocInfoMapper.selectPage(rowPage, queryWrapper);
        return rowPage;
    }



    public boolean updateById(StudyDocInfo studyDocInfo) {

        int i = studyDocInfoMapper.updateById(studyDocInfo);
        if(i != 1){
            throw new RuntimeException("docId不存在："+studyDocInfo.getDocId());
        }
        log.info("============【学习助手】更新文章成功！{}============",studyDocInfo.getDocId());

        return i == 1;
    }

}
