package com.jfinal.club._admin.ideastype;

import com.jfinal.club.common.controller.BaseController;
import com.jfinal.club.common.model.Ideas;
import com.jfinal.club.common.model.IdeasType;
import com.jfinal.club.common.model.IdeasType;
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;

import java.util.Date;

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

    /**
     * 列表
     */
    public void index( ) {
        keepPara("text");
        Integer p = getInt("p", 1);
        if(p <= 0){
            p = 1;
        }
        Page< IdeasType > ideasType = IdeasType.dao.paginate(p, getInt("s",10), "select * ", "from ideas_type order by sort desc,create_time desc");
        setAttr("page", ideasType);
    }

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

    public void save( ) {
        UploadFile filepath = getFile("filepath", Cons.IDEASTYPE);
        IdeasType model = getModel(IdeasType.class);
        String path = null;
        if(filepath != null){
            path = "/upload"+Cons.IDEASTYPE+filepath.getFileName();
            model.setCoverImg(path);
        }
        model.set("create_time",new Date()).save();
        renderJson(Ret.ok("msg","添加成功!"));
    }

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

    public void update( ) {
        UploadFile filepath = getFile("filepath", Cons.IDEASTYPE);
        IdeasType model = getModel(IdeasType.class);
        String path = null;
        if(filepath != null){
            path = "/upload"+Cons.IDEASTYPE+filepath.getFileName();
            model.setCoverImg(path);
        }
        model.update( );
        renderJson(Ret.ok("msg","修改成功!"));
    }

    /**
     * 删除
     */
    public void delete( ) {
        Integer id = getInt("id");
        if(id == null){
            renderJson(Ret.fail("msg", "删除失败"));
            return;
        }

        Ideas ideas = Ideas.dao.findFirst("select * from ideas where type = ? ", id);
        if(ideas != null){
            renderJson(Ret.fail("msg", "有数据引用不能删除!"));
            return;
        }

        boolean delete = IdeasType.dao.deleteById(id);
        if (delete) {
            renderJson(Ret.ok("msg", "删除成功!"));
        } else {
            renderJson(Ret.fail("msg", "删除失败"));
        }
    }

}
