package com.jfinal.club._front;

import com.jfinal.club.common.controller.BaseController;
import com.jfinal.club.common.model.Product;
import com.jfinal.club.common.model.ProductType;
import com.jfinal.club.util.Cons;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @Auther: LiuChao
 * @Date: 2021/2/26 19:40
 * @Description:
 */
public class ProductController extends BaseController {

    public void index(){

        Integer pid = getInt("pid",1);

        Integer type = getInt("tp",0);
        Integer p = getInt("p", 1);
        if(p <= 0){
            p = 1;
        }

        List<ProductType> productTypes = ProductType.dao.find("select * from product_type order by sort desc,create_time desc");

        set("productTypesList",productTypes);

        if(type == 0){
            type = productTypes.get(0).getId();
        }

        Page<Product> page = Product.dao.paginate(p, 1000, "select * ", " from product where pid = ? and FIND_IN_SET(?,types) and start = 0", pid,type);

        set("page",page);

        set("pid",pid);
        set("type",type);
        render("product.html");

    }


    public void detail(){
        Integer id = getInt(0);
        Product product = Product.dao.findById(id);
        set("product",product);

        ArrayList<Object> list = new ArrayList<>();
        if(StringUtils.isNotBlank(product.getTypes())){

            List<ProductType> productTypes = ProductType.dao.find("select * from product_type order by sort desc,create_time desc");
            String[] types = StringUtils.splitPreserveAllTokens(product.getTypes(), ",");


            for (String typeId : types) {
                for (ProductType productType : productTypes) {
                    if(typeId.equals(productType.getId()+"")){
                        list.add(productType);
                    }
                }
            }
        }

        set("typeList",list);

        render("product_detail.html");
    }
}
