package com.xhkjedu.sstudy.service.subjectbook;

import com.xhkjedu.sstudy.mapper.subjectbook.PointMapper;
import com.xhkjedu.sstudy.model.subjectbook.TPoint;
import com.xhkjedu.sstudy.utils.StudyUtil;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.sstudy.vo.subjectbook.PointVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName PointService
 * Description TODO
 * Author WN
 * Date 2020/6/3 11:56
 **/
@Service
public class PointService {
    @Autowired
    private PointMapper pointMapper;

    /**
     *功能描述 新增
     * @author WN
     * @date 2020/6/3
     * @param  * @param point
     * @return java.lang.Integer
     */
    public Integer addPoint(TPoint point){
        String id = StudyUtil.getId();
        point.setPointid(id);
        if ("".equals(point.getPointpid())) {
            point.setPointpid(null);
        }
        point.setCreatetime(N_Utils.getSecondTimestamp());
        return pointMapper.insertSelective(point);
    }

    /**
     *功能描述 修改
     * @author WN
     * @date 2020/6/3
     * @param  * @param point
     * @return java.lang.Integer
     */
    public Integer updatePoint(TPoint point){
        point.setCreatetime(N_Utils.getSecondTimestamp());
        return pointMapper.updateByPrimaryKeySelective(point);
    }

    /**
     *功能描述  删除
     * @author WN
     * @date 2020/6/3
     * @param  * @param point
     * @return java.lang.Integer
     */
    public Integer delPoint(TPoint point){
        return pointMapper.deleteByPrimaryKey(point.getPointid());
    }

    //获取科目下知识点数
    public List<TPoint> listPoints(TPoint point){
        List<TPoint> lst = pointMapper.listPoints(point);

        List<TPoint> points = new ArrayList<>();
        for (TPoint p:lst){
            if(p.getPointpid() == null){
                List<TPoint> childPoints = listChildePoint(p,lst);
                p.setChildren(childPoints);
                points.add(p);

            }
        }

        return points;
    }

    //获取子知识点
    private List<TPoint> listChildePoint(TPoint point,List<TPoint> points){
        List<TPoint> rtnPoints = new ArrayList<>();
        for(TPoint p : points){
            if(point.getPointid().equals(p.getPointpid())){
                List<TPoint> childPoints = listChildePoint(p,points);
                p.setChildren(childPoints);
                rtnPoints.add(p);
            }
        }
        return rtnPoints;
    }

    //搜索知识点
    public List<PointVo> listPointsForSearch(TPoint point){
        return pointMapper.listPointsForSearch(point);
    }

    //查找使用知识点的模块
    public String findUseModule(String pointid) {
        String useModule = pointMapper.findUseModule(pointid);
        if (useModule.startsWith(",")) {
            useModule = useModule.substring(1);
        }
        return useModule;
    }
}

