package com.jfinal.club.my.doc;

import com.jfinal.club.common.model.Doc;
import com.jfinal.club.common.model.Doctype;
import com.jfinal.club.common.model.Loveings;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import java.io.File;
import java.util.*;

import static com.jfinal.club.my.doc.DocKit.suFfix;

/**
 * @ClassName UsersDocService
 * @Description TODO
 * @Author caolong
 * @Date 2020/3/18 11:00
 */
public class UsersDocService {

    public static final String extName = ".jpg";

    private final String docCacheName = "doc";

    private Doc docDao = new Doc().dao();

    private Doctype doctype = new Doctype().dao();

    private Loveings loveings = new Loveings().dao();

    // 用户上传图像最多只允许 1M大小
    public int getAvatarMaxSize() {
        return 1024 * 1024 * 100;
    }

    /**
     * 上传文件
     */
    public String getAvatarTempDir() {
        return "/avatar/";
    }


    public Ret uploadAvatar(int usersId, UploadFile uf) {
        if (uf == null) {
            return Ret.fail("msg", "上传文件UploadFile对象不能为null");
        }
        try {
            if (DocKit.notImageExtName(uf.getFileName())) {
                return Ret.fail("msg", "文件类型不正确，只支持图片类型：pdf、doc、docx、xlsx、xls、pptx、ppt、txt");
            }
            String avatarUrl = "/upload" + getAvatarTempDir() + usersId + "_" + System.currentTimeMillis() + "." + suFfix(uf.getFileName());
            String saveFile = PathKit.getWebRootPath() + avatarUrl;
            int i = typeSuffix(suFfix(uf.getFileName()));
            File save = new File(saveFile);
            boolean saveResult = uf.getFile().renameTo(save);
            return Ret.ok("avatarUrl", avatarUrl).set("filetype", i);
        } catch (Exception e) {
            return Ret.fail("msg", e.getMessage());
        } finally {
            uf.getFile().delete();
        }
    }


    public Ret saveDoc(Doc doc, String avatarUrl, int usersId) {
        doc.setDocurl(avatarUrl);
        doc.setUsersid(usersId);
        doc.setStatus(0);
        doc.setAddtime(new Date());
        doc.setLooking(0);
        doc.setLoveing(0);
        doc.setUping(0);
        doc.setTops(0);
        doc.setSort(0);
        boolean save = doc.save();
        if (save) {
            return Ret.ok("msg", "上传成功,待审核");
        } else {
            return Ret.ok("msg", "上传失败");
        }
    }

    public Ret updateDoc(Doc doc, String fileUrl, int usersId) {
        if (fileUrl != null) {
            doc.setDocurl(fileUrl);
        }
        doc.setStatus(0);
        doc.setAddtime(new Date());
        doc.setLooking(0);
        doc.setLoveing(0);
        doc.setUping(0);
        doc.setTops(0);
        doc.setSort(0);
        boolean update = doc.update();
        if (update) {
            return Ret.ok("msg", "修改成功,待审核");
        } else {
            return Ret.ok("msg", "修改失败");
        }
    }

    /**
     * @return int
     * @Author Cc
     * @Description //TODO 判断文件类型并返回对应的值
     * @Date 2020/3/18
     * @Param []
     **/
    public int typeSuffix(String suffixName) {
        switch (suffixName) {
            case "pdf":
                return 1;
            case "doc":
                return 2;
            case "docx":
                return 2;
            case "xlsx":
                return 3;
            case "xls":
                return 3;
            case "pptx":
                return 4;
            case "ppt":
                return 4;
            case "txt":
                return 5;
            default:
                throw new IllegalStateException("Unexpected value: " + suffixName);
        }
    }


    public Page<Doc> getDocList(int usersId, int status, String text, int pageNum) {
        String parm = "";
        if (!StrKit.isBlank(text)) {
            parm = "%" + text + "%";
        } else {
            parm = "%%";
        }
        Page<Doc> docList = docDao.paginate(pageNum, 10, "select * ", "from doc where usersid = ? and status = ? and docname like ? order by tops desc, addtime desc", usersId, status, parm);
        return docList;
    }

    public Doc getDocById(int id) {
        return docDao.findById(id);
    }

    public Long countDocById(int usersId) {
        return Db.queryLong("select count(*) from doc where usersid = ? and status = 1", usersId);
    }

    public Long countDoc() {
        return Db.queryLong("select count(*) from doc where status = 1");
    }

    public Ret deleteById(int id) {
        boolean b = docDao.deleteById(id);
        if (b) {
            return Ret.ok("msg", "删除成功");
        } else {
            return Ret.fail("msg", "删除失败");
        }
    }

    /**
     * @return java.util.List<com.jfinal.plugin.activerecord.Record>
     * @Author Cc
     * @Description //TODO 查看所有分类及文档数量
     * @Date 2020/3/23
     * @Param []
     **/
    public List<Record> docTypeList() {

        return Db.find("SELECT d.*,COUNT(c.id) AS num FROM doctype AS d LEFT JOIN doc AS c ON d.id=c.doctype and c.status = 1 GROUP BY d.id ORDER BY d.id");
    }

    /**
     * @return java.util.List<com.jfinal.club.common.model.Doctype>
     * @Author Cc
     * @Description //TODO 查看所有分类
     * @Date 2020/3/23
     * @Param []
     **/
    public List<Doctype> doctypeList() {
        return doctype.find("select * from doctype");
    }

    public Doctype docTypeById(int id) {
        return doctype.findById(id);
    }

    public List<Doc> docListByLooking() {
        return docDao.find("select * from doc where status = 1 order by addtime desc limit 6");
    }

    public Page<Doc> getDocListAll(String text, int docType, int pageNum) {
        String parm = "";
        if (!StrKit.isBlank(text)) {
            parm = "%" + text + "%";
        } else {
            parm = "%%";
        }
        Page<Doc> docList = null;
        if (docType != 0) {
            docList = docDao.paginate(pageNum, 10, "select * ", "from doc where status = 1 and filetype = ? and docname like ? order by tops desc,addtime desc", docType, parm);
        } else {
            docList = docDao.paginate(pageNum, 10, "select * ", "from doc where status = 1 and docname like ? order by tops desc,addtime desc", parm);
        }
        return docList;
    }


    public Page<Doc> getDocListTop(int top, int docType, int pageNum) {
        Page<Doc> docList = null;
        if (docType != 0) {
            if (top != 3) {
                docList = docDao.paginate(pageNum, 10, "select d.*,u.nickname", "from doc d ,users u where u.id = d.usersid and d.status = 1 and d.doctype = ? and d.tops = ? order by d.tops desc,d.addtime desc", docType, top);
            } else {
                docList = docDao.paginate(pageNum, 10, "select d.*,u.nickname", "from doc d ,users u where u.id = d.usersid and d.status = 1 and d.doctype = ? order by d.tops desc,d.addtime desc", docType);
            }
        }
        return docList;
    }


    /**
     * @return com.jfinal.plugin.activerecord.Page<com.jfinal.club.common.model.Doc>
     * @Author Cc
     * @Description //TODO 文档 猜你喜欢
     * @Date 2020/3/19
     * @Param []
     **/
    public Page<Doc> getDocByUsersLike(int usersid, int pageNum) {
        return docDao.paginate(pageNum, 4, "select d.*", "from doc d  where d.status = 1 and d.tops = 1 order by d.tops desc,d.addtime desc");
    }


    public Page<Doc> getDocByUping(int pageNum, int top, int size) {
        return docDao.paginate(pageNum, size, "select *", "from doc where status = 1 and tops = ? order by uping desc,addtime desc", top);
    }

    /**
     * @return com.jfinal.plugin.activerecord.Page<com.jfinal.club.common.model.Doc>
     * @Author Cc
     * @Description //TODO 首页推荐文档
     * @Date 2020/3/24
     * @Param [pageNum, size]
     **/
    public Page<Doc> getDocBySort(int pageNum, int size) {
        return docDao.paginate(pageNum, size, "select *", "from doc where status = 1 order by sort desc , addtime desc");
    }

}
