package com.jfinal.club._admin.product;

import com.jfinal.club.common.controller.BaseController;
import com.jfinal.club.common.model.Files;
import com.jfinal.club.common.model.Product;
import com.jfinal.club.common.model.ProductType;
import com.jfinal.club.common.model.Product;
import com.jfinal.club.util.CommonUtil;
import com.jfinal.club.util.Cons;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @descriptions:
 * @author: lc
 * @date: 2020-05-11 11:38:30
 * @Version: 1.0
 **/
@Log4j
public class AdminProductController extends BaseController {

    /**
     * 列表
     */
    public void index( ) {

        keepPara("text");
        Integer p = getInt("p", 1);
        if(p <= 0){
            p = 1;
        }
        String text = get("text","");
        set("text",text);
        Integer types = getInt("types",0);

        String sql = " from product where 1=1 ";
        ArrayList<Object> param = new ArrayList<>();

        if(types > 0){
            sql += " and FIND_IN_SET(?,types) ";
            param.add(types);
        }
        if(StringUtils.isNotBlank(text)){
            text = "%"+text+"%";
            sql += " and title like ? ";
            param.add(text);
        }
        sql += " order by sort desc,create_time desc";

        Page< Product > page = Product.dao.paginate(p, getInt("s",10), "select * ", sql,param.toArray());

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

        set("productTypeList",productTypes);

        page.getList().forEach(a->{
            if(StringUtils.isNotBlank(a.getTypes())){
                String[] split = a.getTypes().split(",");

                String tempStr = "";

                for (ProductType ps : productTypes) {
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];
                        if(ps.getId().toString().equals(s)){
                            tempStr += ps.getTitle()+"、";
                        }

                    }
                }

                a.put("areaApp",tempStr);

            }
        });

        page.getList().forEach(a->{
            List<Files> filesList = Files.dao.find("select * from files where pid = ? ", a.getId());
            a.put("fileNumber",filesList.size());
        });

        setAttr("page", page);

        set("types",types);


        render("index.html");
    }

    public void add( ) {


        keepPara("p");
        set("productTypeList",ProductType.dao.find("select * from product_type order by sort desc,create_time desc"));
        render("add_edit.html");
    }

    public void save( ) {
        
        UploadFile filepath = getFile("filepath", Cons.IDEAS);
        Product model = getModel(Product.class);
        String path = null;
        if(filepath != null){
            path = "/upload"+Cons.IDEAS+filepath.getFileName();
            model.setCoverImg(path);
        }

        String[] types = getRequest( ).getParameterValues("product.types");
        if(types != null){
            String join = StringUtils.join(types, ",");
            model.setTypes(join);
        }

        model.setCreateTime(new Date());
        model.save();
        renderJson(Ret.ok("msg","添加成功!"));
    }

    public void edit( ) {
        keepPara("p");
        Integer id = getInt("id");
        Product product = Product.dao.findById(id);
        setAttr("product",product);

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

        if(StringUtils.isNotBlank(product.getTypes())){
            List< String > list = Arrays.asList(StringUtils.splitPreserveAllTokens(product.getTypes( ), ","));
            productTypes.forEach(a->{
                list.forEach(b->{
                    if(a.getId().equals(Integer.valueOf(b))){
                        a.put("active",1);
                    }
                });
            });
        }
        render("add_edit.html");
    }

    public void update( ) {
        UploadFile filepath = getFile("filepath", Cons.IDEAS);
        Product model = getModel(Product.class);

        String path = null;
        if(filepath != null){
            path = "/upload"+Cons.IDEAS+filepath.getFileName();
            model.setCoverImg(path);
        }
        String[] types = getRequest( ).getParameterValues("product.types");
        if(types != null){
            String join = StringUtils.join(types, ",");
            model.setTypes(join);
        }
        model.update( );
        renderJson(Ret.ok("msg","修改成功!"));
    }

    /**
     * 删除
     */
    public void delete( ) {
        Integer id = getInt("id");
        if(id == null){
            renderJson(Ret.fail("msg", "删除失败"));
            return;
        }
        boolean delete = Product.dao.deleteById(id);
        if (delete) {
            renderJson(Ret.ok("msg", "删除成功!"));
        } else {
            renderJson(Ret.fail("msg", "删除失败"));
        }
    }



    public void files(){
        Integer pid = getInt("pid");
        Integer p = getInt("p", 1);
        if(p <= 0){
            p = 1;
        }
        keepPara("pid");
        Page<Files> page = Files.dao.paginate(p, 10, "select * ", " from files where pid = ? order by sort desc,create_time desc", pid);
        set("page",page);
        render("filelist.html");
    }

    public void files_add(){
        keepPara("pid");
        render("files_add.html");
    }

    public void files_edit(){
        Integer id = getInt("id");
        keepPara("pid");
        Files files = Files.dao.findById(id);
        set("files",files);
        render("files_edit.html");
    }

    public void files_save(){
        UploadFile file = getFile("filepath", Cons.FILES);
        Integer pid = getInt("pid", 0);
        Integer sort = getInt("sort", 0);

        if(file == null){
            renderJson(Ret.fail().set("msg","请上传文件"));
        }else{
            String filePath = CommonUtil.getFilePath(file, Cons.FILES);
            Files f = new Files();
            f.setFilename(file.getFileName());
            f.setCreateTime(new Date());
            f.setFilepath(filePath);
            f.setPid(pid);
            f.setSize(CommonUtil.formatFileUnit(file));
            f.setSort(sort);
            f.setTimes(0);
            f.save();
            renderJson(Ret.ok());
        }
    }

    public void files_update(){
        UploadFile file = getFile("filepath", Cons.FILES);
        Integer id = getInt("id", 0);
        Integer sort = getInt("sort", 0);

        Files f = Files.dao.findById(id);
        if(file != null){
            String filePath = CommonUtil.getFilePath(file, Cons.FILES);
            f.setFilename(file.getFileName());
            f.setFilepath(filePath);
            f.setSize(CommonUtil.formatFileUnit(file));
        }
        f.setSort(sort);
        f.update();

        renderJson(Ret.ok());
    }

    public void files_delete(){
        Integer id = getInt("id", 0);
        Files files = Files.dao.findById(id);
        if(StringUtils.isNotBlank(files.getFilepath())){
            CommonUtil.deleteFile(files.getFilepath());
        }
        Files.dao.deleteById(id);
        renderJson(Ret.ok());
    }

}
