package com.jfinal.club.my.ct;

import com.jfinal.club.common.kit.ImageKit;
import com.jfinal.club.common.model.Account;
import com.jfinal.club.common.model.Userct;
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.upload.UploadFile;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

/**
 * @ClassName UserCtService
 * @Description TODO
 * @Author caolong
 * @Date 2020/3/19 15:08
 */
@Log4j
public class UserCtService {


    public static final String extName = ".jpg";

    private Userct userctdao = new Userct( ).dao( );

    /**
     * 上传图像到临时目录，发回路径供 jcrop 裁切
     */
    public Ret uploadAvatar(int accountId, UploadFile uf) {
        if (uf == null) {
            return Ret.fail("msg", "上传文件UploadFile对象不能为null");
        }
        try {
            if (ImageKit.notImageExtName(uf.getFileName( ))) {
                return Ret.fail("msg", "文件类型不正确，只支持图片类型：gif、jpg、jpeg、png、bmp");
            }
            String avatarUrl = "/upload" + getAvatarTempDir( ) + accountId + "_" + System.currentTimeMillis( ) + extName;
            String saveFile = PathKit.getWebRootPath( ) + avatarUrl;
            ImageKit.zoom(500, uf.getFile( ), saveFile);
            return Ret.ok("avatarUrl", avatarUrl);
        } catch (Exception e) {
            return Ret.fail("msg", e.getMessage( ));
        } finally {
            uf.getFile( ).delete( );
        }
    }

    public Ret saveAvatar(Account loginAccount, String avatarUrl, int x, int y, int width, int height) {
        int accountId = loginAccount.getId( );
        // 暂时用的 webRootPath，以后要改成 baseUploadPath，并从一个合理的地方得到
        String webRootPath = PathKit.getWebRootPath( );
        String avatarFileName = webRootPath + avatarUrl;

        try {
            // 相对路径 + 文件名：用于保存到 account.avatar 字段
            String[] relativePathFileName = new String[1];
            // 绝对路径 + 文件名：用于保存到文件系统
            String[] absolutePathFileName = new String[1];
            buildPathAndFileName(accountId, webRootPath, relativePathFileName, absolutePathFileName);

            BufferedImage bi = ImageKit.crop(avatarFileName, x, y, width, height);
            bi = ImageKit.resize(bi, 200, 200);     // 将 size 变为 200 X 200，resize 不会变改分辨率
            deleteOldAvatarIfExists(absolutePathFileName[0]);
            ImageKit.save(bi, absolutePathFileName[0]);
            return Ret.ok("msg", "头像更新成功，部分浏览器需要按 CTRL + F5 强制刷新看效果");
        } catch (Exception e) {
            return Ret.fail("msg", "头像更新失败：" + e.getMessage( ));
        } finally {
            new File(avatarFileName).delete( );     // 删除用于裁切的源文件
        }
    }

    private void buildPathAndFileName(int accountId, String webRootPath, String[] relativePathFileName, String[] absolutePathFileName) {
        String relativePath = (accountId / 5000) + "/";
        String fileName = accountId + extName;
        relativePathFileName[0] = relativePath + fileName;

        String absolutePath = webRootPath + "/upload/avatar/" + relativePath;   // webRootPath 将来要根据 baseUploadPath 调整，改代码，暂时选先这样用着，着急上线
        File temp = new File(absolutePath);
        if (!temp.exists( )) {
            temp.mkdirs( );  // 如果目录不存在则创建
        }
        absolutePathFileName[0] = absolutePath + fileName;
    }


    /**
     * 目前该方法为空实现
     * 如果在 linux 上跑稳了，此方法可以删除，不必去实现，如果出现 bug，
     * 则尝试实现该方法，即当用户图像存在时再次上传保存，则先删除老的，
     * 以免覆盖老文件时在 linux 之上出 bug
     */
    private void deleteOldAvatarIfExists(String oldAvatar) {

    }

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

    /**
     * 上传文件，以及上传后立即缩放后的文件暂存目录
     */
    public String getAvatarTempDir( ) {
        return "/avatar/temp/";
    }


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

    public Ret saveCt(Userct userct, String avatarUrl, int usersid, Boolean keepLogin) {
        userct.setImgs(avatarUrl);
        userct.setAddtime(new Date( ));
        if (keepLogin) {
            userct.setAnonymous(1);
        } else {
            userct.setAnonymous(0);
        }
        userct.setUsersid(usersid);
        userct.setStatus(0);
        userct.setTops(0);
        userct.setLooking(0);
        userct.setLoveing(0);
        userct.setShareing(0);
        userct.setSort(0);
        if (userct.save( )) {
            return Ret.ok("msg", "添加成功");
        } else {
            return Ret.fail("msg", "添加失败");
        }
    }

    public Ret upCt(Userct userct, String avatarUrl, int usersid, Boolean keepLogin) {
        if (!StrKit.isBlank(avatarUrl)) {
            userct.setImgs(avatarUrl);
        }
        userct.setAddtime(new Date( ));
        if (keepLogin) {
            userct.setAnonymous(1);
        } else {
            userct.setAnonymous(0);
        }
/*        userct.setUsersid(usersid);
        if (usersid != 1) {
            userct.setStatus(0);
            userct.setTops(0);
            userct.setLooking(0);
            userct.setLoveing(0);
            userct.setShareing(0);
            userct.setSort(0);
        }*/
        if (userct.removeNullValueAttrs( ).update( )) {
            return Ret.ok("msg", "添加成功");
        } else {
            return Ret.fail("msg", "添加失败");
        }
    }

    public Page< Userct > getCtList(int usersId, int status, String text, int pageNum) {
        Page< Userct > ctList;
        String parm = "";
        if (!StrKit.isBlank(text)) {
            parm = "%" + text + "%";
        } else {
            parm = "%%";
        }
        if (StringUtils.isNotBlank(text)) {
            ctList = userctdao.paginate(pageNum, 10, "select * ", "from userct where usersid = ? and status = ? and ctname like ? order by tops desc, addtime desc", usersId, status, parm);
        } else {
            ctList = userctdao.paginate(pageNum, 10, "select * ", "from userct where usersid = ? and status = ? order by tops desc, addtime desc", usersId, status);
        }
        return ctList;
    }

    public Userct getCtById(int id) {
        return userctdao.findById(id);
    }

    /**
     * @return
     * @Author Cc
     * @Description //TODO 记录查看详情浏览次数 大于30分钟浏览量+1
     * @Date 2020/3/23
     * @Param
     **/
    public Boolean upLooking(Userct userct, Map< Integer, Object > map, HttpSession session) {
        try {
            if (map != null) {
                Date date = (Date) map.get(userct.getUsersid( ));
                Calendar dateOne = Calendar.getInstance( );
                Calendar dateTwo = Calendar.getInstance( );
                dateOne.setTime(new Date( ));
                dateTwo.setTime(date);
                long timeOne = dateOne.getTimeInMillis( );
                long timeTwo = dateTwo.getTimeInMillis( );
                long minute = (timeOne - timeTwo) / (1000 * 60);
                log.info("date:" + date);
                if (minute > 30) {
                    userct.setLooking(userct.getLooking( ) + 1);
                    map.clear( );
                    return userct.update( );
                }
            } else {
                map = new HashMap<>( );
                map.put(userct.getUsersid( ), new Date( ));
                session.setAttribute("userCtMap", map);
                userct.setLooking(userct.getLooking( ) + 1);
                return userct.update( );
            }
        } catch (NullPointerException e) {
            log.info("map:" + map);
            log.debug("空指针异常");
        }
        return false;
    }


    public Page< Userct > getUserCtListAll(String text, int size, int pageNum) {
        String parm = "";
        if (!StrKit.isBlank(text)) {
            parm = "%" + text + "%";
        } else {
            parm = "%%";
        }
        return userctdao.paginate(pageNum, size, "select u.* ,d.id as doctypeid ,d.img,d.typename,d.type", "from userct as u , doctype as d where u.doctype = d.id and  u.status = 1 and u.ctname like ? order by u.tops desc,u.looking desc,u.shareing desc, u.addtime desc", parm);
    }

    /**
     * 热搜
     *
     * @return
     */
    public Page< Userct > getUserCtListByLooking( ) {
        return userctdao.paginate(1, 10, "select * ", "from userct where status = 1  order by looking desc");
    }

    /**
     * @return
     * @Author Cc
     * @Description //TODO type = 1 根据浏览量 2 最新 type = 0 分类
     * @Date 2020/3/23
     * @Param
     **/
    public Page< Userct > getUserCtByHotOrNews(String text, String type, int pageNum, int size, int doctype) {
        String parm = "";
        if (!StrKit.isBlank(text)) {
            parm = "%" + text + "%";
        } else {
            parm = "%%";
        }
        if (!StrKit.isBlank(type)) {
            if ("1".equals(type)) {
                return userctdao.paginate(pageNum, size, "select *", "from userct where status = 1 and ctname like ? order by looking desc", parm);
            } else if ("2".equals(type)) {
                return userctdao.paginate(pageNum, size, "select *", "from userct where status = 1 and ctname like ? order by addtime desc", parm);
            } else {
                return userctdao.paginate(pageNum, size, "select *", "from userct where status = 1 and doctype = ? and ctname like ? order by addtime desc", doctype, parm);
            }
        }
        return null;
    }

    /**
     * @return com.jfinal.kit.Ret
     * @Author Cc
     * @Description //TODO 删除词条
     * @Date 2020/3/23
     * @Param [id]
     **/
    public Ret deleteById(int id) {
        boolean b = userctdao.deleteById(id);
        if (b) {
            return Ret.ok("msg", "删除成功");
        } else {
            return Ret.fail("msg", "删除失败");
        }
    }

    /**
     * @return
     * @Author Cc
     * @Description //TODO 首页显示词条
     * @Date 2020/3/24
     * @Param
     **/
    public Page< Userct > getUserctBySort(int pageNum, int size) {
        return userctdao.paginate(pageNum, size, "select * ", "from userct where status = 1 order by sort desc,addtime desc");
    }

    /**
     * 最新推荐
     *
     * @return
     */
    public List< Userct > getZuiXinTops( ) {
        try {
            return userctdao.find("select u.* ,d.id as doctypeid ,d.img,d.typename,d.type from userct as u , doctype as d where u.doctype = d.id and  u.status = 1 and u.tops = 1  order by  u.addtime desc");
        } catch (Exception e) {
            e.printStackTrace( );
        }
        return null;
    }

    /**
     * 顶部数据
     * @return
     */
    public List< Userct > getBanner( ) {
        try {
            return userctdao.find("select u.* ,d.id as doctypeid ,d.img,d.typename,d.type from userct as u , doctype as d where u.doctype = d.id and  u.status = 1  order by u.tops desc,u.looking desc,u.shareing desc, u.addtime desc");
        } catch (Exception e) {
            e.printStackTrace( );
        }
        return null;
    }
}
