package com.jfinal.club.my.doc;

import com.alibaba.fastjson.JSONObject;
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.Doc;
import com.jfinal.club.common.model.Doctype;
import com.jfinal.club.common.model.Questions;
import com.jfinal.club.common.model.Userct;
import com.jfinal.club.download.DownloadService;
import com.jfinal.club.my.ct.UserCtService;
import com.jfinal.club.my.newsfeed.UsersInfoIntreceptor;
import com.jfinal.club.my.ques.QuestionsService;
import com.jfinal.club.reg.RegService;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import java.util.List;

/**
 * @ClassName UsersDocController
 * @Description TODO
 * @Author caolong
 * @Date 2020/3/17 17:21
 */
@Before(TypeIntreceptor.class)
public class UsersDocController extends BaseController {


    @Inject
    RegService regSrv;

    @Inject
    UsersDocService usersDocService;

    @Inject
    UserCtService userCtService;

    @Inject
    QuestionsService questionsService;

    @Inject
    DownloadService downloadService;

    public void fileDetail() {
        render("file_detail.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO  文档前端首页
     * @Date 2020/3/18
     * @Param []
     **/
    public void docIndex() {
        Long countDoc = usersDocService.countDoc();
        setAttr("allDoc", countDoc);
        Page<Doc> docLike = null;
        if (isLogin()) {
            docLike = usersDocService.getDocByUsersLike(getloginUsersId(), getParaToInt("p", 1));
            //文档下载个数和下载个数
            setAttr("docCount", usersDocService.countDocById(getloginUsersId()));
            setAttr("countDownload", downloadService.countDownloadById(getloginUsersId()));
        } else {
//            猜你喜欢
            docLike = usersDocService.getDocByUsersLike(0, getParaToInt("p", 1));
        }
        setAttr("docLike", docLike);
        // 热门
        Page<Doc> docByUping = usersDocService.getDocByUping(getParaToInt("p", 1), 0, 50);
        // 精品
        Page<Doc> docByUpingTop = usersDocService.getDocByUping(getParaToInt("p", 1), 1, 50);
        setAttr("docUping", docByUping);
        setAttr("docUpingTop", docByUpingTop);
        List<Record> records = usersDocService.docTypeList();
        setAttr("doctypes", records);
        render("fl_index.html");
    }


    /**
     * @return void
     * @Author Cc
     * @Description //TODO 猜你喜欢ajax
     * @Date 2020/3/21
     * @Param []
     **/
    public void likeDoc() {
        Page<Doc> docByUsersLike = null;
        if (isLogin()) {
            docByUsersLike = usersDocService.getDocByUsersLike(getloginUsersId(), getParaToInt("p", 1));
        } else {
//            猜你喜欢
            docByUsersLike = usersDocService.getDocByUsersLike(0, getParaToInt("p", 1));
        }
        JSONObject object = new JSONObject();
        object.put("data", docByUsersLike.getList());
        object.put("pageNum", getParaToInt("p") + 1);
        renderJson(object);
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO  文档页面
     * @Date 2020/3/18
     * @Param []
     **/
    public void file() {
        int doctype = 0;
        int top = 3;
        if (!StrKit.isBlank(getPara("doctype"))) {
            doctype = Integer.parseInt(getPara("doctype"));
        }
        if (!StrKit.isBlank(getPara("top"))) {
            top = Integer.parseInt(getPara("top"));
        }
        Page<Doc> docTop = usersDocService.getDocListTop(top, doctype, getParaToInt("p", 1));
        if (doctype != 0) {
            Doctype docType = usersDocService.docTypeById(doctype);
            setAttr("docType", docType);
        }
        setAttr("doctype", doctype);
        setAttr("top", top);
        setAttr("docTop", docTop);
        render("file.html");
    }


    /**
     * @return void
     * @Author Cc
     * @Description //TODO  搜索页面
     * @Date 2020/3/18
     * @Param [] type == 1 文件搜索页面
     **/
    public void searchList() {
        String text = getPara("text");
        int docType = 0;
        if (!StrKit.isBlank(getPara("rad"))) {
            docType = Integer.parseInt(getPara("rad"));
        }
        int type = Integer.parseInt(getPara("type"));
        if (type == 1) {
            Page<Doc> docList = usersDocService.getDocListAll(text, docType, getParaToInt("p", 1));
            setAttr("List", docList);
        } else if (type == 2) {
            Page<Userct> userCtListAll = userCtService.getUserCtListAll(text, 10, getParaToInt("p", 1));
            setAttr("List", userCtListAll);
        } else if (type == 3) {
            Page<Questions> questionsPage = questionsService.getUserCtListAll(text, 10, getParaToInt("p", 1));
            setAttr("List", questionsPage);
        }
        setAttr("rad", docType);
        setAttr("type", type);
        setAttr("text", text);
        render("search_list.html");
    }


    /**
     * @return void
     * @Author Cc
     * @Description //TODO  文档审核成功
     * @Date 2020/3/18
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void fileSuccess() {
        Page<Doc> docList = usersDocService.getDocList(getloginUsersId(), 1, getPara("text"), getParaToInt("p", 1));
        setAttr("docList", docList);
        setAttr("text", getPara("text"));
        render("file_success.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO  文档审核失败
     * @Date 2020/3/18
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void fileFail() {
        Page<Doc> docList = usersDocService.getDocList(getloginUsersId(), 2, getPara("text"), getParaToInt("p", 1));
        setAttr("docList", docList);
        setAttr("text", getPara("text"));
        render("file_fail.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO  文档待审核
     * @Date 2020/3/18
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void index() {
        Page<Doc> docList = usersDocService.getDocList(getloginUsersId(), 0, getPara("text"), getParaToInt("p", 1));
        setAttr("docList", docList);
        setAttr("text", getPara("text"));
        render("index.html");
    }

    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void delfile() {
        if (!StrKit.isBlank(getPara("id"))) {
            int id = Integer.parseInt(getPara("id"));
            Ret ret = usersDocService.deleteById(id);
            renderJson(ret);
        }
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 编辑文档页面跳转
     * @Date 2020/3/18
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void fileUp() {
        keepPara("p");
        String docid = getPara("docid");
        if (!StrKit.isBlank(docid)) {
            Doc docById = usersDocService.getDocById(Integer.parseInt(docid));
            setAttr("doc", docById);
        }
        render("file_up.html");
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO  文件发布/编辑
     * @Date 2020/3/18
     * @Param []
     **/
    @Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
    public void fileUps() {
        UploadFile uf = null;
        String types = "";
        try {
            uf = getFile("filenames", usersDocService.getAvatarTempDir(), usersDocService.getAvatarMaxSize());
            types = getPara("types");
            if (uf == null) {
                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;
        }
        Doc doc = getModel(Doc.class);
        if ("1".equals(types)) {
            if (uf != null) {
                Ret ret = usersDocService.uploadAvatar(getloginUsersId(), uf);
                if (ret.isOk()) {
                    String avatarUrl = ret.get("avatarUrl").toString();
                    doc.setFiletype(Integer.parseInt(ret.get("filetype").toString()));
                    Ret ret1 = usersDocService.updateDoc(doc, avatarUrl, getloginUsersId());
                    renderJson(ret1);
                } else {
                    renderJson(ret);
                }
            } else {
                Ret ret1 = usersDocService.updateDoc(doc, null, getloginUsersId());
                renderJson(ret1);
            }
        } else {
            Ret ret = usersDocService.uploadAvatar(getloginUsersId(), uf);
            if (ret.isOk()) {
                String avatarUrl = ret.get("avatarUrl").toString();
                doc.setFiletype(Integer.parseInt(ret.get("filetype").toString()));
                Ret ret1 = usersDocService.saveDoc(doc, avatarUrl, getloginUsersId());
                renderJson(ret1);
                return;
            } else {
                renderJson(ret);
            }
        }
    }
}
