package com.controller;

import com.alibaba.fastjson.JSON;
import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Before;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;
import com.model.BookHot;
import com.model.Org;
import com.model.User;
import com.service.HotBookService;
import com.service.OrgService;
import com.tools.JwtUtils;
import com.validator.BookValidator;
import com.validator.HotBookValidator;

import java.util.List;

/**
 * 图书操作
 * 2018-10-23
 * zj
 */
@ControllerInterface(path="/hotBook")
public class HotBookController extends BaseController {
    HotBookService service = HotBookService.me;
    OrgService orgService = OrgService.me;
    public void index() {
        render("/view/hotbook/hotbook.html");
    }

    @Before(CacheInterceptor.class)
    @CacheName("hotBookList")
    public void list(){
        try{
            User user= getSessionAttr("userInfo");
            int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
            if(operatorid == 0){
                fail(3,"token错误");
                return;
            }

            int schooltype=getParaToInt("schooltype");
            String booktypeid=getPara("booktypeid");

            List<Org> orgList =orgService.findAllParentOrg(user.getOrgid());
            success(service.paginate(orgList,schooltype,booktypeid,this.getParaToInt("pageNumber"),this.getParaToInt("pageSize")));
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }
    public void getById(){
        int id =this.getParaToInt("bean.id", 0);
        if(id == 0){
            fail();
            return;
        }
        success(service.findById(id));
    }
    //增加
    @Before({HotBookValidator.class,EvictInterceptor.class})
    @CacheName("hotBookList")
    public void addOrUpdate(){ 
        //必填信息
        BookHot bean = getBean(BookHot.class,"bean");


        try {
            User user= getSessionAttr("userInfo");
            int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
            if(operatorid == 0){
                 fail(3,"token错误");
                 return;
            }
            bean.setOrgid(user.getOrgid());
            service.addOrUpdate(bean,operatorid);
            success();
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }

    @Before({HotBookValidator.class,EvictInterceptor.class})
    @CacheName("hotBookList")
    public void delete(){
        try{
            String rolejson = getPara("hotbok");
            List<BookHot> bookHotList=  JSON.parseArray(rolejson, BookHot.class);
            service.deleteHotBook(bookHotList);

        }catch (Exception e) {
            e.printStackTrace();
            fail();
        }
        success();
    }
}
