package com.jfinal.club.my.ct;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.club.common.controller.BaseController;
import com.jfinal.club.common.interceptor.FrontAuthInterceptor;
import com.jfinal.club.common.model.Userct;
import com.jfinal.club.common.model.Users;
import com.jfinal.club.my.doc.TypeIntreceptor;
import com.jfinal.club.my.doc.UsersDocService;
import com.jfinal.club.my.newsfeed.UsersInfoIntreceptor;
import com.jfinal.club.my.newsfeed.UsersService;
import com.jfinal.club.my.ques.QuestionsService;
import com.jfinal.club.ws.DocWsService;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import lombok.extern.log4j.Log4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserCtController
 * @Description TODO
 * @Author caolong
 * @Date 2020/3/19 14:55
 */
@Log4j
@Before(TypeIntreceptor.class)
public class UserCtController extends BaseController {

    @Inject
    UserCtService userCtService;

    @Inject
    UsersService usersService;

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 我的词条 待审核
     * @Date 2020/3/19
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void index( ) {
        Page< Userct > userCtList = userCtService.getCtList(getloginUsersId( ), 0, getPara("text"), getParaToInt("p", 1));
        setAttr("userCtList", userCtList);
        setAttr("text", getPara("text"));
        setAttr("my_ct", true);
        render("my_ct.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 我的词条 成功审核
     * @Date 2020/3/19
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void ctSuccess( ) {
        Page< Userct > userCtList = userCtService.getCtList(getloginUsersId( ), 1, getPara("text"), getParaToInt("p", 1));
        setAttr("userCtList", userCtList);
        setAttr("text", getPara("text"));
        render("file_success.html");
        render("ct_success.html");
        setAttr("my_ct", true);
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 我的词条 成功失败
     * @Date 2020/3/19
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void ctFail( ) {
        Page< Userct > userCtList = userCtService.getCtList(getloginUsersId( ), 2, getPara("text"), getParaToInt("p", 1));
        setAttr("userCtList", userCtList);
        setAttr("text", getPara("text"));
        setAttr("my_ct",true);
        render("file_success.html");
        render("ct_fail.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 添加 / 修改词条 页面跳转
     * @Date 2020/3/20
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void centerCt( ) {
        keepPara("p");
        String ctid = getPara("ctid");
        if (!StrKit.isBlank(ctid)) {
            Userct userct = userCtService.getCtById(Integer.parseInt(ctid));
            setAttr("userct", userct);
        }
        render("center_ct.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 添加 / 修改词条
     * @Date 2020/3/20
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class, UserCtValidator.class})
    public void saveCt( ) {
        UploadFile uf = null;
        String types = "";
        try {
            uf = getFile("filepath", userCtService.getAvatarTempDir( ), userCtService.getAvatarMaxSize( ));
            if (uf == null) {
                types = getPara("types");
                if (!"1".equals(types)) {
                    renderJson(Ret.fail("msg", "请先选择上传文件"));
                    return;
                }
            }
        } catch (Exception e) {
            if (e instanceof com.jfinal.upload.ExceededSizeException) {
                renderJson(Ret.fail("msg", "文件大小超出范围"));
            } else {
                if (uf != null) {
                    // 只有出现异常时才能删除，不能在 finally 中删，因为后面需要用到上传文件
                    uf.getFile( ).delete( );
                }
                renderJson(Ret.fail("msg", e.getMessage( )));
            }
            return;
        }
        Ret ret = null;
        boolean keepLogin = getParaToBoolean("rad", false);
        Userct model = getModel(Userct.class);
        types = getPara("types");
        if (uf != null) {
            ret = userCtService.uploadAvatar(getloginUsersId( ), uf);
            if (ret.isOk( )) {
                String avatarUrl = ret.get("avatarUrl").toString( );
                if ("1".equals(types)) {
                    Ret ret1 = userCtService.upCt(model, avatarUrl, getloginUsersId( ), keepLogin);
                    renderJson(ret1);
                } else {
                    Ret ret1 = userCtService.saveCt(model, avatarUrl, getloginUsersId( ), keepLogin);
                    renderJson(ret1);
                }
            }
        } else {
            Ret ret1 = userCtService.upCt(model, null, getloginUsersId( ), keepLogin);
            renderJson(ret1);
        }
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 法律百科首页
     * @Date 2020/3/19
     * @Param []
     **/
    public void baikeIndex( ) {
        //顶部图
        List<Userct> bannerList = userCtService.getBanner();
        //推荐
        List< Userct > topsList = userCtService.getZuiXinTops();
        //热搜
        Page< Userct > lookList = userCtService.getUserCtListByLooking( );

        setAttr("bannerList", bannerList);

        List< BaikeIndexVo > dlist = new ArrayList<>( );

        if(topsList != null && topsList.size() > 0){
            BaikeIndexVo v = null;
            List< Userct > list = null;
            for (int i = 0; i < topsList.size(); i++) {
                if(i == 0 || i % 5 == 0){
                    list = new ArrayList<>( );
                    v = new BaikeIndexVo( );
                    v.setUserct(topsList.get(i));
                }else{
                    list.add(topsList.get(i));
                }
                if(i % 5 == 0 || i == topsList.size()){
                    v.setUserctList(list);
                    dlist.add(v);
                }
            }
        }

        setAttr("topsList", dlist);
        setAttr("lookList", lookList);

        render("baike_index.html");
    }


//    com.jfinal.template.stat.ast.ForEntry.entrySet()

    /**
     * @return void
     * @Author Cc
     * @Description //TODO type = 1 热门 type = 2 最新
     * @Date 2020/3/20
     * @Param []
     **/
    public void baikeList( ) {
        String type = getPara("type", "1");
        String text = getPara("text");
        int doctype = getParaToInt("doctype", 0);
        Page< Userct > userCtListAll = userCtService.getUserCtListAll("", 50, 1);
        Page< Userct > userCtByHotOrNews = userCtService.getUserCtByHotOrNews(text, type, getParaToInt("p", 1), 10, doctype);
        setAttr("userCtByHotOrNews", userCtByHotOrNews);
        setAttr("userCtListAll", userCtListAll);
        setAttr("type", type);
        setAttr("text", text);
        setAttr("doctype", doctype);
        render("baike_list.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 法律百科首页 创建词条
     * @Date 2020/3/19
     * @Param []
     **/
    public void ctSet( ) {
        render("ct_set.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 法律百科详情
     * @Date 2020/3/20
     * @Param []
     **/
    public void ctDetail( ) {
        int id = Integer.parseInt(getPara("id"));
        Userct ctById = userCtService.getCtById(id);
        Users usersById = usersService.findUsersById(ctById.getUsersid( ));

        Page< Userct > userCtListAll = userCtService.getUserCtListAll("", 10, 1);
        ctById.setLooking(ctById.getLooking( ) == null ? 1 : ctById.getLooking( ) + 1);
        ctById.removeNullValueAttrs( ).update( );
        setAttr("usersById", usersById);
        setAttr("ctById", ctById);
        setAttr("userCtListAll", userCtListAll);
        render("ct_detail.html");
    }

    public void delCt( ) {
        if (!StrKit.isBlank(getPara("id"))) {
            int id = Integer.parseInt(getPara("id"));
            Ret ret = userCtService.deleteById(id);
            renderJson(ret);
        }
    }

}
