package com.fdage.service.impl;

import com.fdage.constant.ConfigConstant;
import com.fdage.dto.PageDto;
import com.fdage.mapper.IBaseMapper;
import com.fdage.entity.BaseEntity;
import com.fdage.service.IBaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Condition;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by owen on 2020/2/18 0018 11:22
 */
@Transactional
public abstract class IBaseServiceImpl<T extends BaseEntity, ID extends Serializable> implements IBaseService<T, ID> {


    @Autowired
    ConfigConstant configConstant;

    /**
     * 2021-04-20
     * 这里不能使用 @Autowired 注入HttpServletRequest 会报已注入的错误
     */
//    @Autowired
//    HttpServletRequest request;

    public abstract IBaseMapper<T, ID> getBaseMapper();

    private Class<T> entityClass;

    public IBaseServiceImpl(){
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        entityClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    @Override
    public T findById(ID id){
        Condition condition = new Condition(entityClass);
        condition.createCriteria().andEqualTo("id", id);
        condition.and().andEqualTo("isDelete", 0);
        List<T> ts = getBaseMapper().selectByCondition(condition);
        if (ts != null && ts.size() > 0){
            return ts.get(0);
        }else{
            return null;
        }
    }

    @Override
    public T findOne(T entity){
        entity.setIsDelete(0);
        return getBaseMapper().selectOne(entity);
    }

    @Override
    public List<T> findAll(){
        Condition condition = new Condition(entityClass);
        condition.and().andEqualTo("isDelete", 0);
        return getBaseMapper().selectByCondition(condition);
    }

//    public List<T> findAllDesc(){
//        Condition condition = new Condition(entityClass);
//        condition.and().andEqualTo("isDelete", 0);
//        condition.orderBy("createTime").desc();
//        return getBaseMapper().selectByCondition(condition);
//    }


    /**
     * 根据主键字符串进行查询，类中只有存在一个带有@Id注解的字段
     *
     * @param ids 如 "1,2,3,4"
     * @return
     */
    @Override
    public List<T> findByIds(String ids){
        return getBaseMapper().selectByIds(ids);
    }

    @Override
    public long count(){
        List<T> all = this.findAll();
        if (all != null && all.size() > 0){
            return all.size();
        }
        return 0;
    }

    @Override
    public boolean exists(ID id){
        return getBaseMapper().existsWithPrimaryKey(id);
    }

    @Override
    public int save(T entity) {
        //migration之后要删掉判断
        if (entity.getCreateTime() == null){
            entity.setCreateTime(LocalDateTime.now());
        }
        if (entity.getUpdateTime() == null){
            entity.setUpdateTime(LocalDateTime.now());
        }
        entity.setIsDelete(0);
        return getBaseMapper().insertSelective(entity);
    }

    @Override
    public int update(T entity) {
        //migration之后要删掉判断
        if (entity.getUpdateTime() == null){
            entity.setUpdateTime(LocalDateTime.now());
        }
        return getBaseMapper().updateByPrimaryKeySelective(entity);
    }

    @Override
    public int updateAll(T entity) {
        //migration之后要删掉判断
        if (entity.getUpdateTime() == null){
            entity.setUpdateTime(LocalDateTime.now());
        }
        return getBaseMapper().updateByPrimaryKey(entity);
    }

    @Override
    public int deleteById(ID id) {
        return getBaseMapper().deleteByPrimaryKey(id);
    }

    @Override
    public int deleteByIds(String ids){
        return getBaseMapper().deleteByIds(ids);
    }

    @Override
    public int delete(T entity){
        return getBaseMapper().delete(entity);
    }

    @Override
    public List<T> findAll(Condition condition){
        condition.and().andEqualTo("isDelete", 0);
        return getBaseMapper().selectByCondition(condition);
    }

    public List<T> findAll(Condition condition, String orderBy){
        condition.and().andEqualTo("isDelete", 0);
        if (!StringUtils.isEmpty(orderBy)){
            PageHelper.orderBy(orderBy);
        }
        return getBaseMapper().selectByCondition(condition);
    }

    public PageInfo<T> findAll(int pageNum, int pageSize){
        if (pageNum <= 0) {
            pageNum = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(this.findAll());
    }

    public PageInfo<T> findAll(int pageNum, int pageSize, String orderBy){
        if (pageNum <= 0) {
            pageNum = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        if (!StringUtils.isEmpty(orderBy)){
            PageHelper.orderBy(orderBy);
        }
        return new PageInfo<>(this.findAll());
    }

    public PageInfo<T> findAll(Condition condition, int pageNum, int pageSize){
        if (pageNum <= 0) {
            pageNum = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(this.findAll(condition));
    }

    public PageInfo<T> findAll(Condition condition, int pageNum, int pageSize, String orderBy){

        if (pageNum <= 0) {
            pageNum = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        if (!StringUtils.isEmpty(orderBy)){
            PageHelper.orderBy(orderBy);
        }
        return new PageInfo<>(this.findAll(condition));
    }


    /**
     * 设置请求分页数据
     */
    public void startPage(PageDto param){
        Integer pageNum = param.getPageNum();
        Integer pageSize = param.getPageSize();
        if (pageNum == null || pageNum <= 0) {
            pageNum = 0;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
    }

    /** 获取用户id*/
//    Long getTokenUserId(HttpServletRequest request){
//        return JwtUtil.getUserId(getToken(request));
//    }
//
//    String getTokenUserName(HttpServletRequest request){
//        return JwtUtil.getUsername(getToken(request));
//    }

    /** 获取header token */
    String getToken(HttpServletRequest request){
        return request.getHeader("token");
    }
}
