package com.yc.education.service.impl;

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

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yc.education.mapper.ProductMapper;
import com.yc.education.model.Product;
import com.yc.education.service.ProductService;
import com.yc.education.util.Pager;

@Service
@Transactional
public class ProductServiceImpl extends BaseService<Product> implements ProductService{

	
	@Autowired
	private ProductMapper productMapper;

	@Override
	public Pager<Product> findProductByPage(int count, int num, Integer typeid ,String name) {
		Pager<Product> pager = new Pager<Product>();
		// 封装每页显示数据条数
		pager.setLimit(num);
		// 封装当前页码
		pager.setPageNumber(count);
		// 封装当前商品类型id
		pager.setTypeid(typeid);
		// 获取总条数
		int total = 0;
		List<Product> list = new ArrayList<>();
		if(typeid==0) {
			total = productMapper.findCount(name);
			list = productMapper.findAllByName(name);
		}else {
			for (Product product : productMapper.findAllByName(name)) {
				String[] str = product.getClassifyid().split(",");
				for(int i = 0; i<str.length;i++) {
					if(Integer.valueOf(str[i])==typeid) {
						total++;
						list.add(product);//得到总的类型产品集合
					}
				}
			}
			
		}//total = productMapper.findCountByTypeid(typeid);数据库改变不能用了
		
		pager.setTotal(total);
		// 获取总页数
		int pages = (int) Math.ceil(total * 1.0 / num);
		pager.setPages(pages);
		// 获取当前页数据
		List<Product> proList = new ArrayList<>();
		for(int i=(count-1)*num;i<total&&i<num*count;i++) {
			proList.add(list.get(i));
		}//List<Product> list = productMapper.findProductByTypeid(count, num,typeid);
		pager.setList(proList);
		return pager;
	}

	@Override//根据分类编号查找商品集合
	public List<Product> findProductByClassify(Integer classifyid, String name) {
		List<Product> proList = new ArrayList<>();
		if(classifyid==0) {
			proList = productMapper.findAllByName(name);
		}else {
			for (Product product : productMapper.findAllByName(name)) {
				String[] str = product.getClassifyid().split(",");
				for(int i = 0; i<str.length;i++) {
					if(Integer.valueOf(str[i])==classifyid) {
						proList.add(product);//得到总的类型产品集合
					}
				}
			}
		} 
		return proList;
	}

	@Override
	public int fingdCount() {
		// TODO Auto-generated method stub
		return productMapper.fingdCount();
	}

	
}
