package io.renren.modules.admin.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.admin.dao.DataBaseDao;
import io.renren.modules.admin.entity.DataBaseEntity;
import io.renren.modules.admin.service.DataBaseService;

@Service("dataBaseService")
public class DataBaseServiceImpl extends ServiceImpl<DataBaseDao, DataBaseEntity> implements DataBaseService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Long categoryId = params.containsKey("categoryId") ? Long.valueOf(params.get("categoryId").toString()) : 0L;

        String key = params.containsKey("key") ? (String) params.get("key") : null;

        IPage<DataBaseEntity> page = this.page(new Query<DataBaseEntity>().getPage(params),
                new QueryWrapper<DataBaseEntity>().eq((categoryId != 0L), "category_id", categoryId)
                        .like(StringUtils.isNotBlank(key), "code", key).or()
                        .like(StringUtils.isNotBlank(key), "keyword", key));

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryAppPage(Map<String, Object> params) {
        Long categoryId = params.containsKey("categoryId") ? Long.valueOf(params.get("categoryId").toString()) : 0L;
        String key = params.containsKey("key") ? (String) params.get("key") : null;
        String orderBy = params.containsKey("orderBy") ? (String) params.get("orderBy") : null;
        Integer orderType = params.containsKey("orderType") ? Integer.valueOf(params.get("orderType").toString()) : 0;
        boolean isAsc = true;
        if (orderType == 1) {
            isAsc = false;
        }

        IPage<DataBaseEntity> page = this.page(new Query<DataBaseEntity>().getPage(params),
                new QueryWrapper<DataBaseEntity>().eq((categoryId != 0L), "category_id", categoryId)
                        .like(StringUtils.isNotBlank(key), "code", key).or()
                        .like(StringUtils.isNotBlank(key), "keyword", key)
                        .orderBy(StringUtils.isNotBlank(orderBy), isAsc, orderBy));

        return new PageUtils(page);
    }

    @Override
    public void addFavorite(Long id) {
        baseMapper.addFavorite(id);
    }

    @Override
    public List<DataBaseEntity> getSimilarityList(Long cid) {
        return this.list(new QueryWrapper<DataBaseEntity>().eq("category_id", cid).last("limit 6"));
    }
}