package com.service.report;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

public class CirculationStatisticsService {
    public static final CirculationStatisticsService me = new CirculationStatisticsService();

    /**
     * 图书借阅排行
     * @param orgid
     * @param kssj
     * @param jssj
     * @param topnum
     * @return
     */
    public Page<Record> bookLendingRanking(int pageNumber, int pageSize,int orgid,String kssj,String jssj,Integer topnum){
        String select = "SELECT a.isbn,a.title,a.author,a.publisher,count(c.bookdetailid) as jieyuenums ";
        StringBuilder where = new StringBuilder(" FROM t_book a " +
                "LEFT JOIN t_book_detail b ON a.id = b.bookid LEFT JOIN t_jieyue c ON b.id = c.bookdetailid " +
                "WHERE a.orgid = ?");
        List values = new ArrayList();
        values.add(orgid);
        //如果没填时间，查近一个月
        if(!StringUtils.isNotBlank(kssj) && !StringUtils.isNotBlank(jssj)){
            where.append(" AND c.createtime>DATE_SUB(CURDATE(), INTERVAL 1 MONTH) ");
        }
        if(StringUtils.isNotBlank(kssj)){
            where.append(" AND c.createtime >= ?");
            values.add(kssj);
        }
        if(StringUtils.isNotBlank(jssj)){
            where.append(" AND c.createtime <= ?");
            values.add(jssj+" 23:59:59");
        }
        where.append(" GROUP BY a.id ORDER BY jieyuenums DESC ");
        //如果没填查询数量，查前50条
        if(topnum != null){
            if(topnum == 50){
                where.append(" LIMIT 0,50");
            }else if(topnum == 100){
                where.append(" LIMIT 0,100");
            }else if(topnum == 200){
                where.append(" LIMIT 0,200");
            }
        }else {
            where.append(" LIMIT 0,50");
            topnum = 50;
        }
        //因limit后不支持分页，则将数据存入list转化成page对象
        List<Record> list = Db.find(select+where, CommonUtils.listToArray(values));
        List<Record> list1 = new ArrayList<Record>();
        int index = 0;
        for(int i = (pageNumber - 1) * pageSize;i<list.size();i++){
            list1.add(index,list.get(i));
            index ++;
            if(index == pageSize){
                break;
            }
        }
        Page<Record> page = new Page<Record>(list1,pageNumber,pageSize,topnum / pageSize,list.size());
        return page;
    }
    /**
     * 图书分类借阅排行
     * select t.id,t.name,tt.jieyuenums from (
     * select id,GROUP_CONCAT(name) name from t_booktype where parentid in(1,2,3,4,5) GROUP BY name
     * ) t left join (select b.id,b.name,COUNT(e.bookdetailid) as jieyuenums
     * from t_booktype a INNER JOIN t_booktype b ON a.id = b.parentid
     * LEFT JOIN t_book c ON c.typeid = b.id LEFT JOIN t_book_detail d ON c.id = d.bookid
     * LEFT JOIN t_jieyue e ON e.bookdetailid = d.id
     * WHERE a.parentid = '0' AND e.createtime>DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY b.id ORDER BY jieyuenums DESC) tt on t.id=tt.id
     * order by id asc
     */
    public Page<Record> bookTypeLendingRanking(int pageNumber, int pageSize, int orgid, String kssj, String jssj){
        String select = "select a.id,CONCAT(a.id,a.`name`) as name,COUNT(e.bookdetailid) as jieyuenums ";
        StringBuilder where = new StringBuilder(" from t_booktype a " +
                "LEFT JOIN t_book c ON c.typeid = a.id LEFT JOIN t_book_detail d ON c.id = d.bookid " +
                "LEFT JOIN t_jieyue e ON e.bookdetailid = d.id " +
                "WHERE a.parentid in(1,2,3,4,5) AND c.orgid = ?");
        List values = new ArrayList();
        values.add(orgid);
        //如果没填时间，查近一个月
        if(StringUtils.isBlank(kssj) && StringUtils.isBlank(jssj)){
            where.append(" AND e.createtime>DATE_SUB(CURDATE(), INTERVAL 1 MONTH) ");
        }
        if(StringUtils.isNotBlank(kssj)){
            where.append(" AND e.createtime >= ?");
            values.add(kssj+" 00:00:00");
        }
        if(StringUtils.isNotBlank(jssj)){
            where.append(" AND e.createtime < ?");
            values.add(jssj+" 23:59:59");
        }
        where.append(" GROUP BY a.id ORDER BY jieyuenums DESC ");

        Page<Record> list = Db.paginate(pageNumber,pageSize,select,where.toString(), CommonUtils.listToArray(values));
        /*Record total = Db.findFirst("SELECT COUNT(a.id) as jieyuenumsT FROM t_jieyue a INNER JOIN t_reader b ON a.readerid = b.id " +
                "WHERE b.orgid = ?",orgid);*/
        //总借阅数
        int jieyuenumsT = 0;
        for (Record r : list.getList()){
            Integer jieyuenums = r.getInt("jieyuenums");
            jieyuenumsT +=jieyuenums;
        }
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        for (Record r : list.getList()){
            Integer jieyuenums = r.getInt("jieyuenums");
            String result = numberFormat.format((float) jieyuenums / (float) jieyuenumsT * 100);
            String proportion = result+"%";
            r.set("proportion",proportion);
        }
        return list;
    }
    /**
     * 读者借阅排行
     */
    public Page<Record> readerLendingRanking(int pageNumber, int pageSize, int orgid,String kssj,String jssj,Integer topnum,Integer dept,Integer readerType){
        String select = "SELECT b.realname,b.cardnumber,c.name as typename,d.deptname,COUNT(a.readerid) jieyuenums ";
        StringBuilder where = new StringBuilder(" FROM t_jieyue a " +
                "LEFT JOIN t_reader b ON a.readerid = b.id LEFT JOIN t_dict c ON b.readertypeid = c.id " +
                "LEFT JOIN t_org_dept d ON b.orgdeptid = d.id WHERE a.flag = 0 AND b.orgid = ?");
        List values = new ArrayList();
        values.add(orgid);
        if(!StringUtils.isNotBlank(kssj) && !StringUtils.isNotBlank(jssj)){
            where.append(" AND a.createtime>DATE_SUB(CURDATE(), INTERVAL 1 MONTH) ");
        }
        if(StringUtils.isNotBlank(kssj)){
            where.append(" AND a.createtime >= ?");
            values.add(kssj);
        }
        if(StringUtils.isNotBlank(jssj)){
            where.append(" AND a.createtime < ?");
            values.add(jssj+" 23:59:59");
        }
        if(dept != null){
            where.append(" AND b.orgdeptid = ?");
            values.add(dept);
        }
        if(readerType != null){
            where.append(" AND b.readertypeid = ?");
            values.add(readerType);
        }
        where.append(" GROUP BY a.readerid ORDER BY jieyuenums DESC ");
        //如果没填查询数量，查前50条
        if(topnum != null){
            where.append(" LIMIT 0,"+topnum);
        }else {
            where.append(" LIMIT 0,50");
            topnum = 50;
        }
        //因limit后不支持分页，则将数据存入list转化成page对象
        List<Record> list = Db.find(select+where, CommonUtils.listToArray(values));
        List<Record> list1 = new ArrayList<Record>();
        int index = 0;
        for(int i = (pageNumber - 1) * pageSize;i<list.size();i++){
            list1.add(index,list.get(i));
            index ++;
            if(index == pageSize){
                break;
            }
        }
        Page<Record> page = new Page<Record>(list1,pageNumber,pageSize,topnum / pageSize,list.size());
        return page;
    }

    /**
     * 部门借阅排行
     */
    public Page<Record> deptLendingRanking(int pageNumber, int pageSize, int orgid,String kssj,String jssj){
        String select = "SELECT c.deptname,COUNT(a.id) as jieyuenums ";
        StringBuilder where = new StringBuilder("FROM t_jieyue a " +
                "LEFT JOIN t_reader b ON a.readerid = b.id LEFT JOIN t_org_dept c ON b.orgdeptid = c.id " +
                "WHERE a.flag = 0 AND c.orgid = ?");
        List values = new ArrayList();
        values.add(orgid);
        StringBuffer totalRowSql = new StringBuffer("SELECT COUNT(*) FROM ( " +
                "SELECT b.id FROM t_jieyue a LEFT JOIN t_reader b ON a.readerid = b.id LEFT JOIN t_org_dept c ON b.orgdeptid = c.id \n" +
                "WHERE a.flag = 0 AND c.orgid = ? ");
        if(!StringUtils.isNotBlank(kssj) && !StringUtils.isNotBlank(jssj)){
            where.append(" AND a.createtime>DATE_SUB(CURDATE(), INTERVAL 1 MONTH) ");
            totalRowSql.append(" AND a.createtime>DATE_SUB(CURDATE(), INTERVAL 1 MONTH) ");
        }
        if(StringUtils.isNotBlank(kssj)){
            where.append(" AND a.createtime >= ?");
            totalRowSql.append(" AND a.createtime >= ?");
            values.add(kssj);
        }
        if(StringUtils.isNotBlank(jssj)){
            where.append(" AND a.createtime <= ?");
            totalRowSql.append(" AND a.createtime <= ?");
            values.add(jssj+" 23:59:59");
        }
        where.append(" GROUP BY b.orgdeptid ORDER BY jieyuenums DESC ");
        totalRowSql.append(" GROUP BY b.orgdeptid) a");
        Page<Record> list = Db.paginateByFullSql(pageNumber,pageSize,totalRowSql.toString(),select+where.toString(), CommonUtils.listToArray(values));
        return list;
    }
    /**
     * 部门人均借阅排行
     */
    public List<Record> deptPercapitaLendingRanking(int orgid,String kssj,String jssj){
        String select = " ";
        StringBuilder where = new StringBuilder(" ");
        List values = new ArrayList();
        values.add(orgid);
        if(!StringUtils.isNotBlank(kssj) && !StringUtils.isNotBlank(jssj)){
            where.append(" AND a.createtime>DATE_SUB(CURDATE(), INTERVAL 1 MONTH) ");
        }
        if(StringUtils.isNotBlank(kssj)){
            where.append(" AND a.createtime > ?");
            values.add(kssj);
        }
        if(StringUtils.isNotBlank(jssj)){
            where.append(" AND a.createtime < ?");
            values.add(jssj+" 23:59:59");
        }
        where.append(" GROUP BY b.orgdeptid ORDER BY jieyuenums DESC ");

        List<Record> list = Db.find(select+where, CommonUtils.listToArray(values));
        return list;
    }
}
