package com.ssj.dao.weixin.library.dao.impl;

import com.ssj.bean.weixin.libmy.domain.TbLibUserApply;
import com.ssj.dao.weixin.library.dao.IReadParentQueryDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.service.reading.out.VipBorrowOutDto;
import com.ssj.service.weixin.library.dto.out.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class ReadParentQueryDaoImpl implements IReadParentQueryDao {

    @Autowired
    private PagingHibernateJdbcDao dao;

    @Override
    public Page<IndexOutDto> findGoodIndexData(Map<String,String> params, Pageable pageable) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();
        sql.append("SELECT a.title,count(1) as book_size,a.local_image,b.name as theme_name,ifnull(c.heat,0) as heat,ifnull(section,'') as grade,a.summary,a.id as book_info_id from tb_lib_book_info a\n" );
        sql.append("left join tb_lib_book_detail t on a.id = t.info_id \n" );
        sql.append("left join sys_sort b on a.child_theme=b.code and b.pid='a316f70c-1184-44b9-a636-dbe10262f176'\n" );
        sql.append("left join tb_lib_book_isbn_heat c on a.isbn13 = c.isbn13\n" );
        sql.append("where a.book_stock>0 \n" );
        if(StringUtil.isNotEmpty(params.get("libId"))){
            sql.append(" and  a.lib_id =?  \n" );
            queryParams.add(params.get("libId"));
        }
        if(StringUtil.isNotEmpty(params.get("themeCode"))){
            if(params.get("themeCode").equals("other")){
                sql.append(" and (a.child_theme is null or a.child_theme='') \n" );
            }else{
                sql.append(" and a.child_theme=?  \n" );
                queryParams.add(params.get("themeCode"));
            }

        }
        if(StringUtil.isNotEmpty(params.get("searchTitle"))){
            sql.append(" and a.title like concat('%',?,'%')  \n" );
            queryParams.add(params.get("searchTitle"));
        }

        if(StringUtil.isNotEmpty(params.get("notInId"))){
            sql.append(" and a.id <> ? \n" );
            queryParams.add(params.get("notInId"));
        }

        if(StringUtil.isNotEmpty(params.get("grade"))){
            if(params.get("grade").equals("other") || params.get("grade").equals("其他")){
                sql.append(" and (a.section is null or a.section='') \n" );
            }else{
                sql.append(" and a.section = ? \n" );
                queryParams.add(params.get("grade"));
            }

        }

        sql.append(" group by a.id order by c.heat desc,a.id ");
        return dao.findPage(sql.toString(),queryParams.toArray(),pageable,IndexOutDto.class);
    }

    @Override
    public List<SuccessOutDto> findBorrowedList(List<String> bookDetails) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();
        sql.append("SELECT a.title,a.local_image,a.summary,DATE_FORMAT( b.borrowed_time,'%Y.%m.%d') as borrowed_time, DATE_FORMAT( b.back_book_time,'%Y.%m.%d') as back_book_time from tb_lib_book_info a\n" );
        sql.append("left join tb_lib_book_detail b on a.id = b.info_id \n" );
        sql.append("where b.id in ('" ).append(bookDetails.toString().replace("[","").replace("]","").replace(", ","','")).append("')");
        return dao.findList(sql.toString(),queryParams.toArray(),SuccessOutDto.class);
    }

    @Override
    public Page<Map<String, Object>> growthRecordList(Map<String, Object> searchParams, Pageable pageable) {
        StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        String type = searchParams.get("type").toString();
        if("2".equals(type)){ //归还记录
            selSQL.append("SELECT a.title,a.local_image,ifnull(a.summary,'') as summary,DATE_FORMAT(y.start_time,'%Y.%m.%d') as borrowed_time,DATE_FORMAT(y.end_time,'%Y.%m.%d') as back_book_time,DATE_FORMAT(h.update_time,'%Y.%m.%d %H:%i') as create_time \n" );
            selSQL.append(" from  tb_order_details  h ");
            selSQL.append(" join  tb_lib_user_history y on h.id = y.detail_id ");
            selSQL.append(" join  tb_lib_book_detail l on h.book_detail_id =l.id ");
            selSQL.append(" JOIN   tb_lib_book_info a on a.id  = l.info_id  ");
            selSQL.append(" where h.vip_id =?  and  h.is_close='1' and y.order_type=1  ");
            selSQL.append(" order by  h.update_time  desc ");
            queryParams.add(searchParams.get("vipId"));
        }else{ //借书记录
            selSQL.append("SELECT a.title,a.local_image,ifnull(a.summary,'') as summary,DATE_FORMAT(b.borrowed_time,'%Y.%m.%d') as borrowed_time,DATE_FORMAT(b.back_book_time,'%Y.%m.%d') as back_book_time,DATE_FORMAT(b.borrowed_time,'%Y.%m.%d %H:%i') as create_time from tb_lib_book_info a\n" );
            selSQL.append("left join tb_lib_book_detail b on a.id = b.info_id \n" );
            selSQL.append(" where b.vip_id=? and b.lib_id=? ");
            selSQL.append(" order by b.borrowed_time desc ");
            queryParams.add(searchParams.get("vipId"));
            queryParams.add(searchParams.get("libId"));
        }
        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
    }

    @Override
    public Page<BookHisViewOutDto> themeBorrowedList(Map<String, String> params, Pageable pageable) {

        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();

        sql.append("SELECT c.title,c.local_image,c.summary from tb_order_details a\n" );
        sql.append("join tb_lib_book_detail b on a.book_detail_id = b.id\n" );
        sql.append("join tb_lib_book_info c on b.info_id=c.id\n" );
        sql.append("where 1=1 ");

        if(StringUtil.isNotEmpty(params.get("vipId"))){
            sql.append(" and  a.vip_id =?  \n" );
            queryParams.add(params.get("vipId"));
        }
        if(StringUtil.isNotEmpty(params.get("themeCode"))){
            sql.append(" and c.child_theme=?  \n" );
            queryParams.add(params.get("themeCode"));
        }

        sql.append(" order by a.create_time desc ");
        return dao.findPage(sql.toString(),queryParams.toArray(),pageable,BookHisViewOutDto.class);
    }

    @Override
    public Page<LibRankingOutDto> findUserRankingLib(Map<String, Object> params, Pageable pageable) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();

        sql.append("SELECT t11.child_name,t11.img_url as child_img,t11.borrow_times,t11.borrow_num,t11.vip_id, t11.ranking from (\n");
        sql.append("	SELECT t.child_name,t.img_url,t.borrow_times,t.borrow_num,t.vip_id,@rownum\\:=@rownum+1 ranking from (\n");
        sql.append("		SELECT c.child_name,c.img_url,count(DISTINCT a.create_time) as borrow_times,count(1) as borrow_num,b.vip_id,@rownum\\:=0 from tb_lib_vip_service b\n");
        sql.append("		join tb_order_details a on a.vip_id= b.vip_id \n");
        sql.append("		join tb_lib_read_vip c on b.vip_id=c.id\n");
        sql.append("		where b.lib_id= ?  \n");
        queryParams.add(params.get("libId"));
        if(!StringUtil.isEmpty(params.get("searchDate"))){
            sql.append(" and a.create_time REGEXP ? ");
            queryParams.add(params.get("searchDate"));
        }
        sql.append("		and c.user_id is not null  and b.species='S001'  \n");
        sql.append("		GROUP BY a.vip_id\n");
        sql.append("		order by borrow_num desc,max(a.create_time) asc  \n");
        sql.append("	) t \n");
        sql.append(") t11 ");
        if(!StringUtil.isEmpty(params.get("vipId"))){
            sql.append(" where t11.vip_id=? ");
            queryParams.add(params.get("vipId"));
        }
        return dao.findPage(sql.toString(),queryParams.toArray(),pageable,LibRankingOutDto.class);
    }

    @Override
    public List<YearRankTotalOutDto> findrankTotalDto(Map<String, String> params) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();
        sql.append("select child_name,child_img,ranking,vip_id,GROUP_CONCAT(his_month) as rank_month,count(1) as rank_times  from tb_lib_borrow_his where head_ranking=1 and his_year=? and lib_id=? and vip_id=? group by vip_id");
        queryParams.add(params.get("year"));
        queryParams.add(params.get("libId"));
        queryParams.add(params.get("vipId"));
        return dao.findList(sql.toString(),queryParams.toArray(),YearRankTotalOutDto.class);
    }

    @Override
    public List<ThemeOutDto> findThemeInfoList(Map<String, String> params) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();
        sql.append("SELECT a.theme_name,a.code as theme_code,case when a.count1=0 || b.total_count=0 then 0 else   round(a.count1/b.total_count *100) end as percentage\n");
        sql.append("from (\n");
        sql.append("SELECT t11.name as theme_name,t11.code,count(if(t.id is not null,true,null)) as count1 from sys_sort t11\n");
        sql.append("left  join tb_lib_user_history t on t.book_theme = t11.code and t.vip_id= ? and   t.order_type=1\n");
        sql.append("where t11.pid='a316f70c-1184-44b9-a636-dbe10262f176'\n");
        sql.append("GROUP BY t11.code\n");
        sql.append(") a left join (\n");
        sql.append("SELECT count(t11.id) as total_count from sys_sort t11\n");
        sql.append("join   tb_lib_user_history t on t.book_theme = t11.code and t.vip_id= ? and   t.order_type=1 \n");
        sql.append("where t11.pid='a316f70c-1184-44b9-a636-dbe10262f176'\n");
        sql.append(") b on 1=1 where a.count1>0  order by percentage desc ");
        queryParams.add(params.get("vipId"));
        queryParams.add(params.get("vipId"));
        return dao.findList(sql.toString(),queryParams.toArray(),ThemeOutDto.class);
    }

    @Override
    public Page<TbLibUserApply> applyBookHisList(Map<String, Object> params, Pageable pageable) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();

        sql.append("select * from tb_lib_user_apply  where 1=1 \n" );
        if(!StringUtil.isEmpty(params.get("vipId"))){
            sql.append(" and  vip_id =?  \n" );
            queryParams.add(params.get("vipId"));
        }
        if(!StringUtil.isEmpty(params.get("libId"))){
            sql.append(" and lib_id = ?  \n" );
            queryParams.add(params.get("libId"));
        }
        if(!StringUtil.isEmpty(params.get("type"))){
            sql.append(" and type = ?  \n" );
            queryParams.add(params.get("type"));
        }
        if(!StringUtil.isEmpty(params.get("pid"))){
            sql.append(" and pid = ?  \n" );
            queryParams.add(params.get("pid"));
        }

        sql.append(" order by create_time desc ");
        return dao.findPage(sql.toString(),queryParams.toArray(),pageable,TbLibUserApply.class);
    }

    @Override
    public List<ReadMonthOutDto> findReadMonthList(Map<String, String> params) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();
        sql.append("SELECT a.start_time,a.end_time,count(if(TO_DAYS(a.start_time)<=TO_DAYS(t.start_time) and TO_DAYS(t.start_time)<=TO_DAYS(a.end_time),true,null)) as borrow_num from (\n" );
        sql.append("SELECT DATE_FORMAT(date_sub(now(),interval 28 day),'%Y.%m.%d') start_time,DATE_FORMAT(date_sub(now(),interval 22 day),'%Y.%m.%d') as end_time\n" );
        sql.append("union all\n" );
        sql.append("SELECT DATE_FORMAT(date_sub(now(),interval 21 day),'%Y.%m.%d') start_time,DATE_FORMAT(date_sub(now(),interval 15 day),'%Y.%m.%d') as end_time\n" );
        sql.append("union all\n" );
        sql.append("SELECT DATE_FORMAT(date_sub(now(),interval 14 day),'%Y.%m.%d') start_time,DATE_FORMAT(date_sub(now(),interval 8 day),'%Y.%m.%d') as end_time\n" );
        sql.append("union all\n" );
        sql.append("SELECT DATE_FORMAT(date_sub(now(),interval 7 day),'%Y.%m.%d') start_time,DATE_FORMAT(NOW(),'%Y-%m-%d') as end_time\n" );
        sql.append(") a left join tb_lib_user_history t on t.vip_id=? and t.order_type=1 and   t.start_time BETWEEN  date_sub(now(),interval 28 day)   and NOW()\n" );
        sql.append("GROUP BY a.start_time;");
        queryParams.add(params.get("vipId"));
        return dao.findList(sql.toString(),queryParams.toArray(),ReadMonthOutDto.class);
    }

    @Override
    public List<ReadYearOutDto> findReadYearList(Map<String, String> params) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();
        sql.append("SELECT t.months,count(if(t.months=left(DATE_FORMAT(t11.start_time,'%Y.%m.%d'),7) ,true,null)) as borrow_num from (\n" );
        sql.append("select case when length(mon)=1 then concat(left(CURRENT_DATE,4),'.','0',mon) else concat(left(CURRENT_DATE,4),'.',mon) end months \n" );
        sql.append("from (select @m\\:=@m+1 mon from sys_role ,(select @m\\:=0) a ) aa limit 12\n" );
        sql.append(") t left join tb_lib_user_history t11 on t11.vip_id=? and t11.order_type=1 and t11.start_time regexp left(CURRENT_DATE,4)\n" );
        sql.append("GROUP BY t.months");
        queryParams.add(params.get("vipId"));
        return dao.findList(sql.toString(),queryParams.toArray(),ReadYearOutDto.class);
    }

    @Override
    public List<Map<String, Object>> findLibRankToPush(Map<String, Object> params) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();

        sql.append("SELECT t11.id,t11.wx_account,t11.child_name,t11.img_url as child_img,t11.borrow_times,t11.borrow_num,t11.vip_id, t11.ranking from (\n");
        sql.append("	SELECT t.id,t.wx_account,t.child_name,t.img_url,t.borrow_times,t.borrow_num,t.vip_id,@rownum\\:=@rownum+1 ranking from (\n");
        sql.append("		SELECT b.id,d.wx_account,c.child_name,c.img_url,count(DISTINCT a.create_time) as borrow_times,count(1) as borrow_num,b.vip_id,@rownum\\:=0 from tb_lib_vip_service b\n");
        sql.append("		join tb_order_details a on a.vip_id= b.vip_id \n");
        sql.append("		join tb_lib_read_vip c on b.vip_id=c.id\n");
        sql.append("		join tb_user d on c.user_id = d.id \n");
        sql.append("		where b.lib_id= ?  \n");
        queryParams.add(params.get("libId"));
        sql.append("		and c.user_id is not null and d.wx_account is not null  and b.species='S001' \n");

        if(!StringUtil.isEmpty(params.get("searchDate"))){
            sql.append(" and a.create_time REGEXP ? ");
            queryParams.add(params.get("searchDate"));
        }

        sql.append(" GROUP BY a.vip_id\n");
        sql.append(" order by borrow_num desc,max(a.create_time) asc \n");
        sql.append("	) t \n");
        sql.append(") t11 ");
        return dao.findMap(sql.toString(),queryParams.toArray());
    }

    @Override
    public Page<LibRankingOutDto> libRankingHis(Map<String, Object> params, Pageable pageable) {
        StringBuffer sql = new StringBuffer();
        List<Object> queryParams = new ArrayList<Object>();

        sql.append("SELECT child_name,child_img,borrow_times,borrow_num,vip_id, ranking from tb_lib_borrow_his \n");
        sql.append(" where lib_id=? and his_year=? ");
        queryParams.add(params.get("libId"));
        queryParams.add(params.get("year"));
        if("".equals(params.get("hisMonth").toString())){
            sql.append(" and his_month is null ");
        }else{
            sql.append(" and his_month =? ");
            queryParams.add(params.get("hisMonth"));
        }
        sql.append(" order by ranking asc ");
        return dao.findPage(sql.toString(),queryParams.toArray(),pageable,LibRankingOutDto.class);
    }

    @Override
    public List<VipBorrowOutDto> findInfoListById(String bookInfoId,String libId) {
        StringBuilder selSql = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();

        selSql.append("select a.child_name,count(1) as borrow_num,sum(case when borrow_day=0 then 1 else borrow_day end) borrow_day from ( \n");
        selSql.append("SELECT t11.child_name, t13.info_id,t11.id ,case when t.is_close='1' then to_days(t.update_time)-to_days(t.create_time) else to_days(now())-to_days(t.create_time) end as borrow_day  \n");
        selSql.append("from tb_order_details t  \n");
        selSql.append("left join tb_lib_read_vip t11 on t.vip_id = t11.id \n");
        selSql.append("left join tb_lib_book_detail t13 on t.book_detail_id = t13.id \n");
        selSql.append("where t.lib_id = ?  and t.is_close= '2' and t13.info_id=?   \n");
        queryParams.add(libId);
        queryParams.add(bookInfoId);
        selSql.append("  ) a  group by a.info_id,a.id  \n");


        return dao.findList(selSql.toString(), queryParams.toArray(),VipBorrowOutDto.class);
    }
}
