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

import com.google.common.collect.Lists;
import com.ssj.bean.weixin.libmy.domain.TbLibBorrowHis;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.push.domain.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.dao.weixin.library.dao.ILibBorrowHisDao;
import com.ssj.dao.weixin.library.dao.IReadParentQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.weixin.util.Collections3;
import com.ssj.framework.weixin.util.WxUtil;
import com.ssj.service.weixin.library.dto.out.ReadMonthOutDto;
import com.ssj.service.weixin.library.dto.out.ReadYearOutDto;
import com.ssj.service.weixin.library.dto.out.ThemeOutDto;
import com.ssj.service.weixin.library.dto.out.YearRankTotalOutDto;
import com.ssj.service.weixin.library.service.IBookDetailService;
import com.ssj.service.weixin.library.service.ILibBorrowHisService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class LibBorrowHisServiceImpl extends BaseServiceImpl<TbLibBorrowHis,String> implements ILibBorrowHisService {

    @Autowired
    private ILibBorrowHisDao dao;

    @Autowired
    private IReadParentQueryDao queryDao;

    @Autowired
    private ILibJoinService joinService;

    @Autowired
    private PushTemplateService pushTemplateService;

    @Autowired
    private IBookDetailService bookDetailService;

    @Autowired
    private LibVipServiceService libVipServiceService;

    @Override
    public PagingAndSortingRepository<TbLibBorrowHis, String> getDao() {
        return dao;
    }

    @Override
    public List<YearRankTotalOutDto> findrankTotalDto(Map<String, String> params) {
        return queryDao.findrankTotalDto(params);
    }

    @Override
    public List<ThemeOutDto> findThemeInfoList(Map<String, String> params) {
        return queryDao.findThemeInfoList(params);
    }

    @Override
    public List<ReadMonthOutDto> findReadMonthList(Map<String, String> params) {
        //List<Map<String,Object>> list = queryDao.findReadMonthList(params);
        return queryDao.findReadMonthList(params);
    }

    @Override
    public List<ReadYearOutDto> findReadYearList(Map<String, String> params) {
        return queryDao.findReadYearList(params);
    }

    @Override
    public void pushReadNoticeToUser() {
        //查询出所有馆进行循环
        List<TbLibJoin> allList = joinService.findAll();
        Map<String,Object> params = new HashMap<>();
        params.put("searchDate", DateHelper.format(new Date(),"yyyy-MM"));
        int lastRankNum =0;
        Map<String, String> data = new HashMap<String,String>();
        for (TbLibJoin join :allList){
//            if(join.getLeagueName().contains("测试")||join.getLeagueName().contains("总部")){
//                continue;
//            }
            params.put("libId",join.getId());
            List<Map<String,Object>> list = queryDao.findLibRankToPush(params);
            lastRankNum =0;
            if(!list.isEmpty()){
                for (Map<String,Object> map:list){

                    data.put("first", "亲爱的"+map.get("child_name")+"家长，距离月度排名评选截止时间只剩5天了，加油哦~");
                    data.put("keyword1", DateHelper.format(new Date(),"yyyy年MM月")+"馆内借阅量排名");
                    data.put("keyword2", "距离上一名只差"+(lastRankNum==0?0:(lastRankNum-Integer.parseInt(map.get("borrow_num").toString())))+"本");
                    data.put("keyword3","当前排名为第"+map.get("ranking").toString().split("\\.")[0]+"名");
                    sendWxNotice(data,map.get("wx_account")==null?"":map.get("wx_account").toString(),"");
                    lastRankNum = Integer.parseInt(map.get("borrow_num").toString());
                }
            }
        }
    }

    @Override
    public void pushReadMonthToUser() {
        Map<String,Object> params = new HashMap<>();
        params.put("searchDate", DateHelper.format(DateHelper.getLastMonthFirstDay(new Date()),"yyyy-MM"));
        //查询出所有馆进行循环
        List<TbLibJoin> allList = joinService.findAll();
        Map<String, String> data = new HashMap<String,String>();
        for (TbLibJoin join :allList){
            params.put("libId",join.getId());
            List<Map<String,Object>> list = queryDao.findLibRankToPush(params);
            //总借阅量
            int totalNum = 0;
            //总借阅次数
            int totalTimes = 0;
            if(!list.isEmpty()){
                List<TbLibBorrowHis> hisList = Lists.newArrayList();
                for (Map<String,Object> map:list){
                    data.put("first", "亲爱的"+map.get("child_name")+"家长，您孩子的月度排名结果已经出来了！");
                    data.put("keyword1", DateHelper.format(DateHelper.getLastMonthFirstDay(new Date()),"yyyy年MM月")+"馆内借阅量排名结果");
                    data.put("keyword2", "借书总量"+map.get("borrow_num")+"本");
                    data.put("keyword3","第"+map.get("ranking").toString().split("\\.")[0]+"名");
                    sendWxNotice(data,map.get("wx_account").toString(),"parents/pages/ranking/ranking?type=1&vipId="+map.get("vip_id")+"&libId="+join.getId());
                    totalNum+=Integer.parseInt(map.get("borrow_num").toString().split("\\.")[0]);
                    totalTimes+=Integer.parseInt(map.get("borrow_times").toString().split("\\.")[0]);
                    addHis(map,hisList,join,2,params.get("searchDate").toString());
                }
                this.save(hisList);
            }
            //推送到馆长
            if(totalNum>0){
                List<Map<String,Object>> managerList = bookDetailService.libManageList(join.getId());
                if(Collections3.isNotEmpty(managerList)){
                    data.put("keyword1", DateHelper.format(DateHelper.getLastMonthFirstDay(new Date()),"yyyy年MM月")+"馆内借阅量排名结果");
                    data.put("keyword2", "馆内借书总数量"+totalNum+"本");
                    data.put("keyword3","馆内借阅总次数"+totalTimes+"次");
                    for(Map<String,Object> map:managerList){
                        data.put("first", "亲爱的"+map.get("name")+"馆长，"+join.getLeagueName()+"月度排名结果已经出来了！");
                        sendWxNotice(data,map.get("wx_account").toString(),"");
                    }

                }
            }
        }
    }

    @Override
    public void pushReadYearToUser() {
        Map<String,Object> params = new HashMap<>();
        params.put("searchDate", DateHelper.format(DateHelper.getLastMonthFirstDay(new Date()),"yyyy"));
        //查询出所有馆进行循环
        List<TbLibJoin> allList = joinService.findAll();
        Map<String, String> data = new HashMap<String,String>();
        for (TbLibJoin join :allList){
            params.put("libId",join.getId());
            //总借阅量
            int totolNum = 0;
            //总借阅次数
            int totalTimes = 0;
            List<Map<String,Object>> list = queryDao.findLibRankToPush(params);
            if(!list.isEmpty()){
                List<TbLibBorrowHis> hisList = Lists.newArrayList();
                for (Map<String,Object> map:list){
                    data.put("first", "亲爱的"+map.get("child_name")+"家长，您孩子的年度排名结果已经出来了！");
                    data.put("keyword1", DateHelper.format(DateHelper.getLastMonthFirstDay(new Date()),"yyyy年")+"馆内借阅量排名结果");
                    data.put("keyword2", "借书总量"+map.get("borrow_num")+"本");
                    data.put("keyword3","第"+map.get("ranking").toString().split("\\.")[0]+"名");
                    sendWxNotice(data,map.get("wx_account").toString(),"parents/pages/ranking/ranking?type=1&vipId="+map.get("vip_id")+"&libId="+join.getId());
                    addHis(map,hisList,join,1,params.get("searchDate").toString());

                    totolNum+=Integer.parseInt(map.get("borrow_num").toString().split("\\.")[0]);
                    totalTimes+=Integer.parseInt(map.get("borrow_times").toString().split("\\.")[0]);
                }
                this.save(hisList);
            }

            //推送到馆长
            if(totolNum>0){
                List<Map<String,Object>> managerList = bookDetailService.libManageList(join.getId());
                if(Collections3.isNotEmpty(managerList)){
                    data.put("keyword1", DateHelper.format(DateHelper.getLastMonthFirstDay(new Date()),"yyyy年")+"馆内借阅量排名结果");
                    data.put("keyword2", "馆内借书总数量"+totolNum+"本");
                    data.put("keyword3","馆内借阅总次数"+totalTimes+"次");
                    for(Map<String,Object> map:managerList){
                        data.put("first", "亲爱的"+map.get("name")+"馆长，"+join.getLeagueName()+"年度排名结果已经出来了！");
                        sendWxNotice(data,map.get("wx_account").toString(),"");
                    }

                }
            }
        }
    }

    public void addHis(Map<String,Object> map,List<TbLibBorrowHis> hisList,TbLibJoin join,int type,String searchDate){
        //插入月记录
        TbLibBorrowHis his = new TbLibBorrowHis();
        his.setBorrowNum(Integer.parseInt(map.get("borrow_num")+""));
        his.setBorrowTimes(Integer.parseInt(map.get("borrow_times")+""));
        his.setChildImg(map.get("child_img")+"");
        his.setChildName(map.get("child_name")+"");
        his.setHisYear(searchDate.substring(0,4));
        his.setLibId(join.getId());
        his.setVipId(map.get("vip_id")+"");
        his.setRanking(Integer.parseInt(map.get("ranking").toString().split("\\.")[0]));
        if(type==2){
            his.setHisMonth(searchDate.substring(5));
            if(his.getRanking()<4){
                his.setHeadRanking(1);
            }else{
                his.setHeadRanking(2);
            }
            //改变借阅书籍量
            if(join.getType()<9){
                LibVipService vipService = libVipServiceService.getById(map.get("id").toString());
                vipService.setBorrowNum(his.getRanking()==1?5:his.getRanking()==2?4:his.getRanking()==3?3:2);
                libVipServiceService.save(vipService);
            }
        }
        hisList.add(his);
    }

    public void sendWxNotice(Map<String, String> data,String openid,String pagePath){
        String template_id_short="OPENTM412338989";
        Miniprogram min = new Miniprogram();
        min.setPagepath(pagePath);
        min.setAppid(WxUtil.map.get("readingAppId"));
        SendTemplateShort templateShort = new SendTemplateShort(openid, template_id_short, null,data,min);
        pushTemplateService.saveAndSendPushWxTemplate(templateShort);
    }
}
