package com.xunwang.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunwang.commonutils.JwtUtils;
import com.xunwang.commonutils.RedisIdWorker;
import com.xunwang.education.entity.StuNeeds;
import com.xunwang.education.entity.dto.MyPublishStuNeedsDto;
import com.xunwang.education.entity.dto.MyStuNeedsDto;
import com.xunwang.education.entity.vo.StuNeedsVo;
import com.xunwang.education.mapper.StudentRequirementsMapper;
import com.xunwang.education.service.StudentRequirementsService;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 需求表 服务实现类
 * </p>
 *
 * @author Long
 * @since 2022-11-16
 */
@Service
public class StudentRequirementsServiceImpl extends ServiceImpl<StudentRequirementsMapper, StuNeeds> implements StudentRequirementsService {

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发布学生需求
     * @param requirements
     * @param request
     * @return
     */
    @Override
    public boolean publishRequirements(StuNeeds requirements, HttpServletRequest request) {
        String uid = JwtUtils.getUIdByJwtToken(request);
        long next = redisIdWorker.nextId("require_id");
        String requireId = String.valueOf(next);

        String courseWeekday = requirements.getCourseWeekday();
        ArrayList<String> list = new ArrayList<>();
        if (courseWeekday.contains("A")) {
            list.add("上午");
        }
        if (courseWeekday.contains("P")) {
            list.add("下午");
        }
        if (courseWeekday.contains("E")) {
            list.add("晚上");
        }
        requirements.setCourseTimetype(list.toString());

        StuNeeds stuNeeds = requirements.setUid(uid).setRequireId(requireId);

        boolean save = save(stuNeeds);
        return save;
    }

    /**
     * 个人发布的需求
     * @param request
     * @return
     */
    @Override
    public HashMap<String, Object> getPersonCourse(HttpServletRequest request) {
        String uid = JwtUtils.getUIdByJwtToken(request);
        List<MyPublishStuNeedsDto> list = baseMapper.getPersonCourse(uid);
        int count = 0;
        for (MyPublishStuNeedsDto item : list) {
            if ("上架".equals(item.getDisplay())) {
                count++;
            }
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("publishCounts", count);
        hashMap.put("list", list);
        return hashMap;
    }

    /**
     * 更新个人需求上下架
     * @param request
     */
    @Override
    public boolean updatePersonDisplay(HttpServletRequest request) {
        String display = request.getParameter("display");
        String requireId = request.getParameter("requireId");
        StuNeeds stuNeeds = new StuNeeds();
        stuNeeds.setDisplay(display).setRequireId(requireId);
        if ("下架".equals(display)) {
            String key = "viewCount:stuNeed";
            Long rank = stringRedisTemplate.opsForZSet().rank(key, requireId);
            if (rank != null) {
                // 有访问量
                // 1.更新viewCount到数据库
                Double score = stringRedisTemplate.opsForZSet().score(key, requireId);
                if (score != null) {
                    stuNeeds.setViewedCount(score.intValue());
                }
                // 2.删除redis中存的viewCount数据
                stringRedisTemplate.opsForZSet().remove(key, requireId);
            }
        }

        LambdaQueryWrapper<StuNeeds> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StuNeeds::getRequireId, requireId);
        int update = baseMapper.update(stuNeeds, wrapper);
        return update == 1;
    }

    /**
     * 分页查询所有需求
     * @return
     */
    @Override
    public Map<String, Object> getAllRequirements(StuNeedsVo stuNeedsVo) {
        String money = stuNeedsVo.getMoney();
        if (!"".equals(money)) {
            String[] moneyArr = money.split("-");
            stuNeedsVo.setMoneyLeft(moneyArr[0]).setMoneyRight(moneyArr[1]);
        }
        Integer startIndex = (stuNeedsVo.getPageNum() - 1) * stuNeedsVo.getPageSize();
        stuNeedsVo.setPageNum(startIndex);

        List<MyStuNeedsDto> list = baseMapper.selectAllStuNeed(stuNeedsVo);
        Integer total = baseMapper.selectCount(new LambdaQueryWrapper<StuNeeds>().eq(StuNeeds::getDisplay, "上架").eq(StuNeeds::getLocked, "未锁"));
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("total", total);
        hashMap.put("list", list);
        return hashMap;
    }

    /**
     * 根据需求id查询需求是否上锁或下架
     * @param needId
     * @return
     */
    @Override
    public String queryLockOrDisplay(String needId) {
        StuNeeds stuNeeds = getOne(new LambdaQueryWrapper<StuNeeds>().eq(StuNeeds::getRequireId, needId));
        if (stuNeeds.getDisplay().equals("下架")) {
            return "该需求已下架";
        }
        if (stuNeeds.getLocked().equals("已锁")) {
            return "该需求已锁,请30分钟后查看";
        }
        String version = stuNeeds.getVersion();
        return "需求ok "+version;
    }

    /**
     * 锁定需求号
     * @param needId
     * @param version
     * @return
     */
    @Override
    public boolean lockStuNeedId(String needId, String version) {
        StuNeeds stuNeeds = new StuNeeds();
        stuNeeds.setLocked("已锁");
        stuNeeds.setVersion((Integer.parseInt(version) + 1) + "");
        return update(stuNeeds, new LambdaQueryWrapper<StuNeeds>().eq(StuNeeds::getRequireId, needId).eq(StuNeeds::getVersion, version));
    }

    /**
     * 获取需求详情
     * @param request
     * @return
     */
    @Override
    public StuNeeds getStuNeedDetail(HttpServletRequest request) {
        String requireId = request.getParameter("requireId");
        LambdaQueryWrapper<StuNeeds> wrapper = new LambdaQueryWrapper<StuNeeds>().eq(StuNeeds::getRequireId, requireId);
        return getOne(wrapper);
    }

}
