package com.jfinal.club._admin.demo;

import com.jfinal.club.common.controller.BaseController;
import com.jfinal.club.common.model.Demo;
import com.jfinal.club.util.Cons;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import lombok.extern.log4j.Log4j;

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

    /**
     * 列表
     */
    public void index( ) {
        keepPara("text");
        Integer p = getInt("p", 1);
        if(p <= 0){
            p = 1;
        }
        String text = get("text");
        if(text != null){
            text = "%"+text+"%";
        }else{
            text = "%%";
        }
        Page< Demo > demo = Demo.dao.paginate(p, getInt("s",10), "select * ", "from demo where title like ? order by sort desc,create_date desc",text);
        setAttr("page", demo);
    }

    public void add( ) {
        keepPara("p");
        render("add_edit.html");
    }

    public void save( ) {
        UploadFile filepath = getFile("filepath", Cons.DEMOIMG, 500000);
        String path = null;
        if(filepath != null){
            path = "/upload"+Cons.DEMOIMG+filepath.getFileName();
        }
        getModel(Demo.class).set("img",path).removeNullValueAttrs().save();
        renderJson(Ret.ok("msg","添加成功!"));
    }

    public void edit( ) {
        keepPara("p");
        Integer id = getInt("id");
        Demo demo = Demo.dao.findById(id);
        setAttr("demo",demo);
        render("add_edit.html");
    }

    public void update( ) {
        UploadFile filepath = getFile("filepath", Cons.DEMOIMG, 500000);
        String path = null;
        if(filepath != null){
            path = "/upload"+Cons.DEMOIMG+filepath.getFileName();
        }
        getModel(Demo.class).set("img",path).removeNullValueAttrs().update( );
        renderJson(Ret.ok("msg","修改成功!"));
    }

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

    public void status_t(){
        Integer id = getInt("id");
        Demo demo = Demo.dao.findById(id);
        demo.setStatus(1);
        demo.removeNullValueAttrs().update();
        index();
    }
    public void status_f(){
        Integer id = getInt("id");
        Demo demo = Demo.dao.findById(id);
        demo.setStatus(0);
        demo.removeNullValueAttrs().update();
        index();
    }

}
