package com.service.report;

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

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

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

    /**
     * 基本统计
     * @param orgid
     * @return
     */
    public Map basicStatistics(int orgid){
        Map map = new HashMap();
        Record list = Db.findFirst("SELECT dzs,lss as lss,xss,tsglys,tszs, tszcs,tszcs_bz,qkzs,(tszcs+(select count(*) from t_book_zhuxiao where orgid = t_dayreport.orgid))/xss as tssjcs," +
                "tszcs - tszcs_bz as qscs,tszcs / tszs as pjfb,tszcs / xss as tsbzl,sjdz " +
                "from t_dayreport WHERE DATEDIFF(createtime,NOW())=0 and orgid = ?",orgid);
        //读者数
        Record reader = Db.findFirst("SELECT count(id) as dzs from t_reader where orgid=? and status != 4 ", orgid);
        map.put("dzs", reader.get("dzs"));
        //图书管理员数,学生数，老师数
        List<Record> r_tsglys = Db.find("SELECT a.id as orgid,COUNT(b.id) as managers,(ifnull(a.students,0)+ ifnull(a.czstudents,0)+ ifnull(a.gzstudents,0)) as students," +
                "a.teachers as teachers from t_org a LEFT JOIN t_user b ON a.id = b.orgid " +
                "where orgid=? and isclose=0 and  a.orgtypeid=5 AND b.`status` = 1  GROUP BY a.id",orgid);
        Record rr = r_tsglys.get(0);
        //map.put("managers"+orgid,rr.get("managers"));
        map.put("xss",rr.get("students"));
        //map.put("teachers"+orgid,rr.get("teachers"));




        //图书总册数,图书种数
        Record r = Db.findFirst("SELECT a.orgid,COUNT(b.id) as tszcs,count(distinct a.shucihao,a.typecode) tszs, " +
                " count(distinct case when typecode in ('C6','C7','F11-6','G237.4','G259.1-6','G359.1-6','G811.3-6'," +
                "'J991-6','K811-6','K82-6','N6','O1-6','O6-6','Q939-6','Q949-6','R322-6','R851-6','S41-6'," +
                "'S722-6','T-6','TB91-6','TS664-6','TS941.7-6','U462-6','V26-6','V42-6','V46-6','X-6','X9-6','X93-6') then concat(a.shucihao,a.typecode) else NULL end)  as toolnum  " +
                "FROM t_book_detail b " +
                "LEFT JOIN t_book a on a.id = b.bookid LEFT join t_org o on o.id = a.orgid " +
                "WHERE o.id=? and isclose=0 and  b.status !=3 and o.orgtypeid = 5  GROUP BY a.orgid",orgid);


            map.put("tszcs",r.getInt("tszcs"));
            Record record = Db.findFirst("select count(*) ct from (\n" +
                    "select count(distinct a.id) from t_book a where a.orgid = ? and  a.booknum>0 group by a.id\n" +
                    ") t",orgid);
            map.put("tszs",r.getInt("tszs"));
            map.put("toolnum"+orgid,r.getInt("toolnum"));

        map.put("tssjcs", r.getInt("tszcs")*1.0D/rr.getInt("students"));
        map.put("tsbzl", r.getInt("tszcs")*1.0D/rr.getInt("students"));
        map.put("pjfb", r.getInt("tszcs")*1.0D/r.getInt("tszs"));
        return map;
    }
    /**
     * 今日简报
     * 查当天 借书，还书，新增，注销数量
     */
    public Map briefingToday(int orgid){
        Record r = Db.findFirst("SELECT COUNT(b.id) as jssl from t_reader a LEFT JOIN t_jieyue b ON a.id = b.readerid " +
                " WHERE b.flag = 0 AND DATEDIFF(b.createtime,NOW())=0 AND a.orgid = ? ",orgid);
        Record r1 = Db.findFirst("SELECT COUNT(b.id) as hssl from t_reader a LEFT JOIN t_jieyue b ON a.id = b.readerid " +
                "WHERE b.`status` = 1 AND b.flag = 0 AND DATEDIFF(b.returntime,NOW())=0 AND a.orgid = ?",orgid);
        Record r2 = Db.findFirst("SELECT COUNT(a.id) as xzsl from t_book_detail a LEFT JOIN t_book b ON a.bookid = b.id " +
                "WHERE DATEDIFF(a.shangjiatime,NOW())=0 AND b.orgid = ? and a.bookstatus=1",orgid);
        Record r3 = Db.findFirst("SELECT COUNT(id) as zxsl FROM t_book_zhuxiao WHERE flag = 0 AND DATEDIFF(createtime,NOW())=0 " +
                "AND status = 0 AND orgid  = ?",orgid);
        Map map = new HashMap();
        map.put("jssl",r);
        map.put("hssl",r1);
        map.put("xzsl",r2);
        map.put("zxsl",r3);
        return map;
    }
    /**
     * 流通统计
     */
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    public Map circulationStatistics(int orgid,String kssj,String jssj){
        Record r = Db.findFirst("SELECT ifnull(SUM(CASE WHEN b.flag = 0 THEN 1 ELSE 0 END),0) as tsjcsl," +
                "ifnull(SUM(CASE WHEN b.flag = 1 THEN 1 ELSE 0 END),0) as qkjcsl from t_reader a LEFT JOIN t_jieyue b ON a.id = b.readerid " +
                "WHERE b.`status` = 0 and a.orgid = ?",orgid);
        //图书借出数量，期刊借出数量，当前借出数量
        int tsjcsl = r.getInt("tsjcsl");
        int qkjcsl = r.getInt("qkjcsl");
        int dqjcsl = qkjcsl+tsjcsl;

        //kssj为前一个月，jssj为当天
        if(StringUtils.isBlank(kssj)){
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MONTH, -1);
            Date d = c.getTime();
            kssj = format.format(d);
        }
        if(StringUtils.isBlank(jssj)){
            Calendar c = Calendar.getInstance();
            jssj = format.format(c.getTime());
        }
        kssj = kssj+" 00:00:00";
        jssj = jssj+" 23:59:59";
        /*
        读者到馆率 = 读者到馆借阅书刊总人数/图书馆读者总人数*100%
        注：读者到馆人次 = 读者到馆借阅书刊总人数 = 读者借阅文献总册数
            r1读者到馆人次，r2读者总人数，r3读者借阅图书总册数，r4图书馆藏总册数，r5期刊馆藏总册数，r6学生数

            1. 读者到馆率（读者到馆借阅书刊总人数/图书馆读者总人数*100%）
            2. 藏书利用率（读者借阅图书总册数/图书馆图书总册数*100%）
            3. 文献利用率（读者借阅文献总册数/图书馆文献总册数*100%）
            4. 人均借阅册数（借阅总册次/学生人数）
            5. 读者阅读率（读者借阅书刊总册数/到馆借阅读者总人数*100%）
         */
        Record r1 = Db.findFirst("SELECT COUNT(a.id) as dzdgrc FROM t_jieyue a LEFT JOIN t_reader b ON a.readerid = b.id " +
                "WHERE b.orgid = ? AND a.createtime > ? AND a.createtime <= ?",orgid,kssj,jssj);
        Record r2 = Db.findFirst("select COUNT(id) as dzzrs from t_reader " +
                "WHERE orgid = ?",orgid);
        //createtime > '"+kssj+"' AND createtime <= '"+jssj+"' AND
        Record r3 = Db.findFirst("SELECT COUNT(a.id) as dzjytszcs FROM t_jieyue a LEFT JOIN t_reader b ON a.readerid = b.id " +
                "WHERE a.flag = 0 AND a.createtime > ? AND a.createtime <= ? AND b.orgid = ? ",kssj,jssj,orgid);
        Record r4 = Db.findFirst("SELECT COUNT(a.id) as tsgczcs from t_book_detail a LEFT JOIN t_book b ON a.bookid = b.id " +
                "WHERE a.createtime > ? AND a.createtime <= ? AND b.orgid = ?",kssj,jssj,orgid);
        Record r5 = Db.findFirst("SELECT COUNT(b.id) AS qkgczcs FROM t_periodical_zhengding a LEFT JOIN t_periodical_detail b ON a.id = b.libraryid " +
                "WHERE b.createtime > ? AND b.createtime <= ? AND a.orgid = ?",kssj,jssj,orgid);
        Record r6 = Db.findFirst("SELECT ifnull(students+czstudents+gzstudents,0) as students,id FROM t_org WHERE id =?",orgid);

        DecimalFormat df = new DecimalFormat("0.00%");
        int dzdgrc = r1.getInt("dzdgrc");
        int dzzrs = r2.getInt("dzzrs");
        int dzjytszcs = r3.getInt("dzjytszcs");
        int tsgczcs = r4.getInt("tsgczcs");
        int qkgczcs = r5.getInt("qkgczcs");
        int students = r6.getInt("students");
        int gczcs = tsgczcs + qkgczcs;
        String dzdgl = "0.00%";
        if(dzzrs != 0){
            dzdgl = df.format((float) dzdgrc / (float)dzzrs);
        }
        String cslyl = "0.00%";
        if(tsgczcs != 0){
            cslyl = df.format((float)dzjytszcs / (float)tsgczcs);
        }
        String wxlyl = "0.00%";
        if(gczcs != 0){
            wxlyl = df.format((float)dzdgrc / (float)gczcs);
        }
        float rjjycs = 0;
        if(students != 0){
            rjjycs = (float)dzdgrc / (float)students;
        }
        String dzydl = "0.00%";
        if(dzdgrc != 0){
            dzydl = df.format((float)dzjytszcs / (float) dzdgrc);
        }

        Map map = new HashMap();
        map.put("dzdgrc",dzdgrc);
        map.put("dqjcsl",dqjcsl);//当前借出数量
        map.put("tsjcsl",tsjcsl);//图书借出数量
        map.put("qkjcsl",qkjcsl);//期刊借出数量
        map.put("dzdgl",dzdgl);//读者到馆率
        map.put("cslyl",cslyl);//藏书利用率
        map.put("wxlyl",wxlyl);//文献利用率
        map.put("rjjycs",rjjycs);//人均借阅册数
        map.put("dzydl",dzydl);//读者阅读率
        return map;

    }
}
