package com.service;

import com.config.BaseController;
import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.model.*;
import com.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 机构
 * 2018-10-16
 * zj
 */
public class OrgService {

    public static final OrgService me = new OrgService();
    private Org dao = new Org().dao();
    private  User userDao = new User().dao();

    public Page<Record> paginates(int pageNumber,int pagesize,Integer orgid,Integer areatypeid,Integer schoolcategoryid,Integer status,String orgname,Integer orgtypeid) {
        Page<Record> page = null;
        if(orgtypeid == 5){
            String select1 = "SELECT a.id,a.id as orgid,a.orgtypeid,a.orgname,a.address,a.status,a.orgcode, " +
                    "(SELECT loginname FROM t_user WHERE orgid = a.id AND isadmin = 1 limit 1) as number,a.linkman,a.linkphone,b.areatype,c.category ";
            StringBuilder where1 = new StringBuilder(" FROM t_org a LEFT JOIN t_areatype b ON a.areatypeid = b.id " +
                    "LEFT JOIN t_schoolcategory c ON a.schoolcategoryid = c.id WHERE isclose=0 ");
            List list1 = new ArrayList();
            where1.append("AND a.id = ? ");
            list1.add(orgid);
            if (areatypeid != null) {
                where1.append(" and a.areatypeid = ?");
                list1.add(areatypeid);
            }
            if (schoolcategoryid != null) {
                where1.append(" and a.schoolcategoryid = ?");
                list1.add(schoolcategoryid);
            }
            if (status != null) {
                where1.append(" and a.status = ?");
                list1.add(status);
            }
            if (StringUtils.isNotBlank(orgname)) {
                where1.append(" and a.orgname like ?");
                list1.add("%" + orgname + "%");
            }
            page = Db.paginate(pageNumber, pagesize, select1, where1.toString(), CommonUtils.listToArray(list1));
        }else {
            String select = "SELECT a.id,a.id as orgid,a.orgtypeid,a.orgname,a.address,a.status,a.orgcode," +
                    "(SELECT loginname FROM t_user WHERE orgid = a.id AND isadmin = 1 limit 1) as number,a.linkman,a.linkphone,b.areatype,c.category ";
            StringBuilder where = new StringBuilder(" FROM t_org a LEFT JOIN t_areatype b ON a.areatypeid = b.id " +
                    "LEFT JOIN t_schoolcategory c ON a.schoolcategoryid = c.id WHERE isclose=0 ");
            List list = new ArrayList();
            where.append("AND a.parentid = ? ");
            list.add(orgid);
            if(areatypeid!=null){
                where.append(" and a.areatypeid = ?");
                list.add(areatypeid);
            }
            if(schoolcategoryid!=null){
                where.append(" and a.schoolcategoryid = ?");
                list.add(schoolcategoryid);
            }
            if(status != null ){
                where.append(" and a.status = ?");
                list.add(status);
            }
            if(StringUtils.isNotBlank(orgname)){
                where.append(" and a.orgname like ?");
                list.add("%"+orgname+"%");
            }
            page = Db.paginate(pageNumber, pagesize,select,where.toString(), CommonUtils.listToArray(list));
        }

        for(Record r : page.getList()){
            int id = r.getInt("orgid");
            String parentcodes = CommonUtils.codeAddOne(id,6);
            Record school = Db.findFirst("select id as orgid,(select sum(ifnull(students,0)+ ifnull(czstudents,0)+ ifnull(gzstudents,0)) from t_org where parentcodes like ? or id = ?) as students," +
                    "(select COUNT(id) from t_org where orgtypeid = 5 AND isclose=0 and (parentcodes like ? or id = ?)) as schoolnum," +
                    "(select SUM(teachers) from t_org where parentcodes like ? or id = ?) as teachers " +
                    "from t_org o WHERE o.id = ? ","%"+parentcodes+"%",id,"%"+parentcodes+"%",id,"%"+parentcodes+"%",id,id);
            Integer schoolnum = 0;
            Integer students = 0;
            Integer teachers = 0;
            if(school!=null){
                schoolnum = school.getInt("schoolnum");
                students = school.getInt("students");
                teachers = school.getInt("teachers");
            }
            r.set("schoolnum",schoolnum);
            r.set("students",students);
            r.set("teachers",teachers);
        }
        return page;
    }

    public Page<Record> paginatestojswadmin(int pageNumber,int pagesize,Integer orgid,Integer areatypeid,Integer schoolcategoryid,Integer status,String orgname,Integer orgtypeid) {
        Page<Record> page = null;
        String select = "SELECT a.id,a.id as orgid,a.orgtypeid,a.orgname,a.address,a.status," +
                "(SELECT loginname FROM t_user WHERE orgid = a.id AND isadmin = 1 limit 1) as number,a.linkman,a.linkphone,b.areatype,c.category ";
        StringBuilder where = new StringBuilder(" FROM t_org a LEFT JOIN t_areatype b ON a.areatypeid = b.id " +
                "LEFT JOIN t_schoolcategory c ON a.schoolcategoryid = c.id WHERE isclose=0 ");
        List list = new ArrayList();
        where.append("AND a.parentcodes like ? ");
        list.add("%" + orgid + "%");
        if(areatypeid!=null){
            where.append(" and a.areatypeid = ?");
            list.add(areatypeid);
        }
        if(schoolcategoryid!=null){
            where.append(" and a.schoolcategoryid = ?");
            list.add(schoolcategoryid);
        }
        if(status != null ){
            where.append(" and a.status = ?");
            list.add(status);
        }
        if(StringUtils.isNotBlank(orgname)){
            where.append(" and a.orgname like ?");
            list.add("%"+orgname+"%");
        }
        page = Db.paginate(pageNumber, pagesize,select,where.toString(), CommonUtils.listToArray(list));

        for(Record r : page.getList()){
            int id = r.getInt("orgid");
            String parentcodes = CommonUtils.codeAddOne(id,6);
            Record school = Db.findFirst("select id as orgid,(select sum(ifnull(students,0)+ ifnull(czstudents,0)+ ifnull(gzstudents,0)) from t_org where parentcodes like ? or id = ?) as students," +
                    "(select COUNT(id) from t_org where orgtypeid = 5 AND isclose=0 and (parentcodes like ? or id = ?)) as schoolnum," +
                    "(select SUM(teachers) from t_org where parentcodes like ? or id = ?) as teachers " +
                    "from t_org o WHERE o.id = ? ","%"+parentcodes+"%",id,"%"+parentcodes+"%",id,"%"+parentcodes+"%",id,id);
            Integer schoolnum = 0;
            Integer students = 0;
            Integer teachers = 0;
            if(school!=null){
                schoolnum = school.getInt("schoolnum");
                students = school.getInt("students");
                teachers = school.getInt("teachers");
            }
            r.set("schoolnum",schoolnum);
            r.set("students",students);
            r.set("teachers",teachers);
        }
        return page;
    }

    public List<Record> thisUnit(Integer orgid){
        List<Record> list = Db.find("SELECT a.id,a.orgname,b.loginname,a.address,a.linkman,a.linkphone " +
                "FROM t_org a LEFT JOIN t_user b ON a.id = b.orgid WHERE a.id = ?",orgid);
        return list;
    }

    public void unitEdit(Integer id,String linkman,String linkphone){
        Db.update("UPDATE t_org SET linkman = ?,linkphone = ? WHERE id = ?",linkman,linkphone,id);
    }

    public void deleteById(int id) {
        Db.update("UPDATE t_org SET isclose = 1 WHERE id = ?",id);
        //dao.deleteById(id);
    }
    @Before(CacheInterceptor.class)
    @CacheName("findById")
    public Org findById(int id){
        return dao.findById(id);
    }
    public void addOrUpdate(Org bean, int operatorid){
        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                if(bean.getId()== null){
                    //获取当前管理员机构，根据当前机构添加下级机构
                    //同时创建上下级关系parentcodes 假如parentcodes最上级为1，每增加下一级，则下一级parentcodes为父级id补0：100000
                    User curruser = userDao.findById(operatorid);
                    if(CommonUtils.isNotNullOrNotEmpty(curruser)){
                        int uOrgid = curruser.getOrgid();
                        //查询当前机构的parentid和parentcodes，如果parentid为0，则为最上级，如果不是最上级，则最上级parentcodes+当前生成parentcodes为当前parentcodes
                        Org o = dao.findFirst("SELECT parentid,parentcodes,orgtypeid from t_org WHERE id =?",uOrgid);
                        String parentcodes = o.getParentcodes();
                        String p = parentcodes+uOrgid+",";
                        bean.setParentid(uOrgid).setParentcodes(p);
                    }else {
                        bean.setParentid(0).setParentcodes("0");
                    }
                    //如果为学校则默认审核未通过 如果为教育局则默认审核通过
                    if(bean.getOrgtypeid() == 5) {
                        bean.setStatus(0);
                    } else {
                        bean.setStatus(1);
                    }
                    bean.setCreatetime(new Date()).setOperatorid(operatorid).save();

                    //创建一个新机构的同时，生成一个所创建机构的超级管理员账号 t_user
                    User user = new User();
                    //初始密码123456
                    user.setIsadmin(1).setStatus(1).setRealname(bean.getOrgname()).setPhone(bean.getLinkphone()).setPassword(CommonUtils.getMD5String(CommonUtils.getMD5String(PropKit.get("initPassword")))).setOrgid(bean.getId()).setOperatorid(operatorid).setCreatetime(new Date()).save();

                    RoleUser roleUser = new RoleUser();
                    roleUser.setRoleid(bean.getOrgtypeid().equals(1)?2:bean.getOrgtypeid().equals(2)?3:bean.getOrgtypeid().equals(3)?4:bean.getOrgtypeid().equals(5)?5:-1);
                    roleUser.setUserid(user.getId());
                    roleUser.setCreatetime(new Date());
                    roleUser.setOperatorid(operatorid);
                    roleUser.save();

                    String orgids = ReaderService.codeAddOne(bean.getId(),6);
                    String cardnumber = (orgids+user.getId()).trim();
                    Db.update("update t_user set code = ?,loginname = ? where id = ? ",cardnumber,cardnumber,user.getId());

                    if (bean.getOrgtypeid()==5){
                        new Library().setOrgid(bean.getId()).setOperatorid(bean.getOperatorid()).setLibrary("基本书库").setCreatetime(new Date()).save();
                        new Library().setOrgid(bean.getId()).setOperatorid(bean.getOperatorid()).setLibrary("教师书库").setCreatetime(new Date()).save();
                        new Library().setOrgid(bean.getId()).setOperatorid(bean.getOperatorid()).setLibrary("工具书库").setCreatetime(new Date()).save();

                        new OrgSetting().setOrgid(bean.getId()).setTstiaoxinmaweishu(8).setQktiaoxingmaweishu(7).setJieshuzhengweishu(6).save();

                        OrgBookField orgBookField = new OrgBookField();
                        orgBookField.setOrgid(bean.getId()).setKeyword(0).setEdition(0).setOtherauthor(0).setNewsource(0)
                                .setBltitle(0).setSubtitle(0).setWorkmode(0).setGuobie(0).setSize(0).setLanguage(0).setBinding(0)
                                .setCongshuming(0).setCongshuauthor(0).save();
                    }
                }else{
                    Org old = dao.findById(bean.getId());
                    bean.setCreatetime(old.getCreatetime()).setOperatorid(old.getOperatorid()).setUpdatetime(new Date()).setUpdateuserid(operatorid).update();
                }
                return true;
            }
        });
        if(PropKit.getBoolean("logswitch")){
            Thread t = new Thread() {
                public void run() {
                    Org org = dao.findById(bean.getId());
                    SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Map map = new HashMap();
                    map.put("orgid",org.getId().toString());
                    map.put("orgname",org.getOrgname());
                    map.put("status",org.getStatus().toString());
                    map.put("plattype","1");
                    map.put("orgtypeid",org.getOrgtypeid().toString());
                    map.put("parentid", org.getParentid().toString());
                    map.put("parentcodes",org.getParentcodes());
                    if(CommonUtils.isNotNullOrNotEmpty(org.getRffectivetime())){
                        map.put("rffectivetime",format3.format(org.getRffectivetime()));
                    }
                    if(CommonUtils.isNotNullOrNotEmpty(org.getCreatetime())){
                        map.put("orgcreatetime",format3.format(org.getCreatetime()));
                    }
                    HttpKit.get(PropKit.get("createOrgLogServiceUrl"), map);
                }
            };
            t.start();
        }
    }

    public void passWordReset(String pwd,int orgid){
        Record record = Db.findFirst("select id from t_user where isadmin=1 and orgid = ?",orgid);
        Db.update("UPDATE t_user SET password = ? WHERE id =?",pwd,record.getInt("id"));
    }

    public String orgLogo(int orgid){
        Record record = Db.findFirst("select orglogo from t_org where id = ?",orgid);
        if(record != null){
            return record.get("orglogo");
        }
        return "";
    }

    public String getSchoolForSql(int operatorid){
        Record r_orgid = Db.findFirst("select orgid from t_user where id=?",operatorid);
        int orgid = r_orgid.getInt("orgid");
        //根据orgid生成parentcodes
        String parentcodes = CommonUtils.codeAddOne(orgid,6);
        List<Record> r_orgidList = Db.find("select id from t_org where parentcodes like ?","%"+parentcodes+"%");
        StringBuffer values = new StringBuffer();
        for(Record r : r_orgidList){
            int id = r.getInt("id");
            String value = String.valueOf(id);
            values.append(value+",");
        }
        values.append(orgid+",");
        String val = "";
        if (values.length() > 0){
            values.deleteCharAt(values.length() - 1);
            //获取该机构下有哪些下级机构
            val = "("+values+")";
        }
        return val;
    }

    public List<Org> fuzzyFindOrg(Integer orgid,String content,Integer schoolcategoryid){
        String select = "SELECT id as orgid,orgname ";
        StringBuilder where = new StringBuilder(" FROM t_org WHERE parentid = ?");
        List list = new ArrayList();
        list.add(orgid);
        if(StringUtils.isNotBlank(content)){
            where.append(" AND orgname LIKE ? ");
            list.add("%"+content+"%");
        }
        if(schoolcategoryid != null){
            where.append(" AND schoolcategoryid = ?");
            list.add(schoolcategoryid);
        }
        List<Org> orgs = dao.find(select+where,CommonUtils.listToArray(list));
        return  orgs;
    }

    public  List<Org> findSchool(int orgid){
        List<Org> orgList;
        Record databaseRecord = Db.findFirst("select * from t_database where status = 1 and orgid = ?",orgid);
        if(CommonUtils.isNotNullOrNotEmpty(databaseRecord)){
            orgList=dao.use(databaseRecord.getStr("databasename")).find("select id,orgname,orgtypeid from t_org where parentid =?",orgid);
        } else {
            orgList=dao.find("select id,orgname,orgtypeid from t_org where parentid =?",orgid);
        }

        List<Org> returnOrgList = new ArrayList<Org>();
        for (Org org : orgList){
            if (org.getOrgtypeid().equals(5)){
                returnOrgList.add(org);
            }else {
                returnOrgList.addAll(findSchool(org.getId()));
            }
        }
        return returnOrgList;
    }

    public  Page<Org> findChildOrg(int orgid,int pageNumber, int pageSize){
        return dao.paginate(pageNumber,pageSize,"select id,orgname,orgtypeid ","from t_org where parentid =?",orgid);
    }
    public  List<Org> findChildOrgs(int orgid){
        return dao.find("select id,orgname,orgtypeid from t_org where parentid =?",orgid);
    }

    public  List<Org> findAllParentOrg(int orgid){
        Org org =dao.findFirst("select id,parentid from t_org where id =?",orgid);
        if (org ==null){
            return new  ArrayList<Org>();
        }
        List<Org> returnOrgList = new ArrayList<Org>();
        returnOrgList.add(org);
        if (!org.getParentid().equals(0)){
            returnOrgList.addAll(findAllParentOrg(org.getParentid()));
        }
        return returnOrgList;
    }

    public Page findOrgList(Integer pageNumber, Integer pageSize, String orgname) {
        String select ="select o.id, o.orgname,o.createtime,o.linkman,o.linkphone,p.orgname uporgname,o.status ";
        StringBuffer where =new StringBuffer(" FROM t_org o " +
                " LEFT JOIN t_org p ON o.parentid = p.id where o.orgtypeid = 5");
        List list = new ArrayList();
        if (CommonUtils.isNotNullOrNotEmpty(orgname)) {
            where.append(" and o.orgname ? ");
            list.add("%"+orgname+"%");
        }
        return Db.paginate(pageNumber,pageSize, select,where.toString(), BaseController.listToArray(list));
    }

    public void updateStatus(Integer id, Integer status) {
        Db.update("update t_org set status = ? where id = ?",status ,id);
    }



    public Org orgreport(Integer orgid){
        String sql ="select a.id,parentid,orgname,schoolcategoryid,students,czstudents,gzstudents," +
                " (select count(*)  from t_reader where orgid =a.id) as readernum " +
                " from t_org a where a.id =? ";

        Org org= dao.findFirst(sql,orgid);
        sql = "select count(distinct c.id) as tszcs,count(distinct b.shucihao,b.typecode) as tszs,sum(b.price) as bookprice  from  t_book b inner join t_book_detail c on b.id =c.bookid where orgid =?   and c.status !=3  AND c.bookstatus = 1";
        Record record=Db.findFirst(sql,orgid);
        org.put("tszcs",record.get("tszcs"));
        org.put("tszs",record.get("tszs"));
        org.put("bookprice",record.get("bookprice"));

        sql = " select count(distinct d.kanming,d.bookno) as qkzs,sum(e.price) as qkzje,count(e.id) as qkzcs from t_periodical_zhengding  d  inner join t_periodical_detail e on e.periodicalid = d.id and e.status not in (3) and d.orgid=? ";
        record=Db.findFirst(sql,orgid);
        org.put("qkzs",record.get("qkzs"));
        org.put("qkzje",record.get("qkzje"));
        org.put("qkzcs",record.get("qkzcs"));
        return org;
    }
}
