package com.csnf;


import com.csnf.entity.Category;
import com.csnf.entity.Product;
import com.csnf.mapper.CategoryMapper;
import com.csnf.mapper.ProductMapper;
import com.csnf.util.PageUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class CategoryTest {
    @Test
    public void testSelectByPrimaryKey() throws IOException {
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        CategoryMapper mapper = builder.build(in).openSession().getMapper(CategoryMapper.class);
        Category category = mapper.selectByPrimaryKey(1);
        System.out.println(category.getCategory_name());
    }

    @Test
    public void testInsert() throws IOException {
        Category category = new Category();
        category.setCategory_name("手机");
        category.setCategoryImageSrc("http://localhost:8080/images/category/phone.jpg");
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSession session = builder.build(in).openSession();
        CategoryMapper mapper = session.getMapper(CategoryMapper.class);
        mapper.insert(category);
        session.commit();

    }

    @Test
    public void testSelectByConditional() throws IOException {
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSession session = builder.build(in).openSession();
        ProductMapper productMapper = session.getMapper(ProductMapper.class);
        PageUtil pageUtil = new PageUtil();
        pageUtil.setCurrentPage(2);
        pageUtil.setPageSize(10);
        pageUtil.setTotalCount(productMapper.selectAll().size());
        int totalPage = pageUtil.getTotalCount() % pageUtil.getPageSize() == 0 ? pageUtil.getTotalCount() / pageUtil.getPageSize() : pageUtil.getTotalCount() / pageUtil.getPageSize() + 1;
        pageUtil.setTotalPage(totalPage);
        pageUtil.setStartIndex((pageUtil.getCurrentPage() - 1) * pageUtil.getPageSize());
        List<Product> productList = productMapper.selectByConditional(null, null, null, null, null, pageUtil);
        for (Product product : productList) {
            System.out.println(product.getProduct_id() + "->>>" + product.getProduct_name());
        }
    }


}
