package com.ssj.task;

import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.weixin.libmy.domain.TbLibWeeklyRecord;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.service.weixin.library.service.ILibSubscribeService;
import com.ssj.service.weixin.library.service.IOneBookService;
import com.ssj.service.weixin.library.service.LibWeeklyRecordService;
import com.ssj.service.weixin.order.service.OrderDetailsService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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


@DisallowConcurrentExecution
    @Component
    public class PushWeeklyTask implements Job {

        private static Logger logger = LoggerFactory.getLogger(PushWeeklyTask.class);

        @Override
        public void execute(JobExecutionContext jobExecutionContext) {
            try {

                ILibSubscribeService libSubscribeService =  SystemResourceLocator.getBean(ILibSubscribeService.class);
                OrderDetailsService orderDetailsService =  SystemResourceLocator.getBean(OrderDetailsService.class);
                IOneBookService oneService =  SystemResourceLocator.getBean(IOneBookService.class);
                LibWeeklyRecordService libWeeklyRecordService =  SystemResourceLocator.getBean(LibWeeklyRecordService.class);
                PushTemplateService pushTemplateService= SystemResourceLocator.getBean(PushTemplateService.class);


                String weekly=getTimeInterval(new Date());
                String startTime=weekly.split(",")[0];
                String endTime= weekly.split(",")[1];
                String url= SystemResourceLocator.getValue("sys_url")+"/weixin/weekly/weekly_#VIPID#?start_time="+startTime+"&end_time="+endTime;
                List<Map<String,Object>> borrows= libSubscribeService.queryBorrowByVip(startTime, endTime);

                Map<String,String> data =new HashMap<String, String>();
                for (Map<String, Object> map : borrows) {
                    try{
                        data.clear();
                        String vip_id=map.get("vip_id").toString();
                        String user_id=map.get("user_id").toString();
                        String wx_account=map.get("wx_account").toString();
                        String child_name=map.get("child_name").toString();

                        Map<String,Object> libVip=libSubscribeService.queryEffectiveByVip(vip_id);
                        Long subscribenum= libSubscribeService.countSubscribeByVip(vip_id, startTime, endTime);
                        if(libVip!=null && subscribenum>0){//有效的
                            Map<String,Object> readMap= libSubscribeService.countWeeklyRead(vip_id, startTime, endTime);
                            int timeCount=0;
                            if(readMap.get("time_count")!=null){
                                timeCount=(int)Double.parseDouble(readMap.get("time_count").toString());//阅读分数
                            }
                            Map<String,Object> rankingMap= libSubscribeService.queryRankingByVip(vip_id, startTime, endTime);
                            double ranking=0;
                            if(rankingMap.get("rownum")!=null){
                                ranking=Double.parseDouble(rankingMap.get("rownum").toString());
                            }

                            Integer count=orderDetailsService.signSubscribCount(libVip.get("lib_id").toString());
                            double rankingrate=((double)count-ranking)/(double)count*100;
                            logger.info("rankingrate:"+rankingrate+"  count："+count+"  ranking:"+ranking);
                            long borrownum= libSubscribeService.countBorrowByVip(vip_id, startTime, endTime);

                            Map<String, Object> firstMap = oneService.getTjInfo(user_id);

                            data.put("first", child_name+"妈妈／爸爸，您好。您孩子本周阅读报告出炉咯\n");
                            data.put("keyword1","这周你孩子到馆阅读"+timeCount+"分时长，完成"+firstMap.get("readnum")+"次阅读心得分享，累计借阅"+borrownum+"本图书 。");
                            data.put("keyword2","你孩子目前的阅读量，在私塾家小会员里面排名处于"+getRankingRateTitle(rankingrate)+"，跑赢 "+rankingrate+"% 的小会员，继续加油哦！");
                            data.put("remark", "\n点击“详情”，即可查看您孩子的阅读周报告。");
                            String template_id_short=(String) SystemResourceLocator.getValue("sendTemplate104");
                            //SendTemplate  sendTemplate  =new  SendTemplate(wx_account,templateId,url.replaceAll("#VIPID#", vip_id),data);
                            //NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);

                            SendTemplateShort sendTemplateShort=new SendTemplateShort(wx_account, template_id_short, url.replaceAll("#VIPID#", vip_id), data);
                            pushTemplateService.savePushWxTemplate(sendTemplateShort);


                            TbLibWeeklyRecord record=new TbLibWeeklyRecord();
                            record.setVipId(vip_id);
                            record.setStartTime(DateHelper.parseDate(startTime, "yyyy-MM-dd"));
                            record.setPushTime(new Date());
                            record.setContent(JSONObject.toJSONString(data));
                            libWeeklyRecordService.save(record);
                        }
                    } catch (Exception e) {
                        logger.error("任务失败:" + e.getMessage(), e);
                    }
                }
            } catch (Exception e) {
                logger.error("任务失败:" + e.getMessage(), e);
            }
        }

        /**
         * 根据当前日期获得所在周的日期区间（周一和周日日期）
         *
         * @return
         * @author wuwen
         * 2017年9月26日11:54:02
         * @throws
         */
        private static String getTimeInterval(Date date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
            if (1 == dayWeek) {
                cal.add(Calendar.DAY_OF_MONTH, -1);
            }
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            int day = cal.get(Calendar.DAY_OF_WEEK);
            cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
            String imptimeBegin = sdf.format(cal.getTime());
            cal.add(Calendar.DATE, 6);
            String imptimeEnd = sdf.format(cal.getTime());
            return imptimeBegin + "," + imptimeEnd;
        }


        private static String getRankingRateTitle(double rankingrate) {
            if(rankingrate>=0 && rankingrate<=59){
                return "中下游";
            }else if(rankingrate>=60 && rankingrate<=79){
                return "中游";
            }else{
                return "上游";
            }
        }

}
