package com.iformall.schedule;

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

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.analysis.WxMaVisitTrend;
import com.iformall.service.wechat.FmOpenService;
import com.iformall.utils.MaUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.github.pagehelper.PageInfo;
import com.iformall.domain.po.WxAppinfo;
import com.iformall.domain.po.WxUserVisit;
import com.iformall.enums.EnumAppType;
import com.iformall.service.WxAppinfoService;
import com.iformall.service.WxUserVisitService;

@Component
public class WxAppVisitSchedule {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
    private boolean isFmOpen;
	 
	@Autowired
	private WxUserVisitService wxUserVisitService;
	 
	@Autowired
	private WxAppinfoService WxAppinfoService;

	@Autowired
    private FmOpenService openService;


	@Scheduled(cron = "0 0 9/1 * * ? ") //早晨9点开始每小时取一次,获取前一日,微信时间为GMT
	public void daliyVisitRetrive() {
		try {

			WxAppinfo appInfoQ = new WxAppinfo();
            appInfoQ.setType(EnumAppType.C.getCode());
			List<WxAppinfo> apps = WxAppinfoService.getList(appInfoQ);
			for(WxAppinfo app:apps) {
				if(StringUtils.isBlank(app.getAppId())||StringUtils.isBlank(app.getSecret())) {
					continue;
				}
				Calendar c = Calendar.getInstance();
                c.add(Calendar.DAY_OF_YEAR, -1);
                Date lastDate = c.getTime();
				String date = new SimpleDateFormat("yyyyMMdd").format(lastDate);
				if (!checkData(date,app)) {
                    getData(lastDate, app);
                }
			}
		}catch(Exception e) {
			logger.error("获取微信访问数据失败",e);
		}
	}


	@Scheduled(cron = "0 0 2 * * ? ") //2点做一次补录
	public void completeVisitRetrive() {
		try {

			WxAppinfo appInfo = new WxAppinfo();
			appInfo.setType(EnumAppType.C.getCode());
            List<WxAppinfo> apps = WxAppinfoService.getList(appInfo);
			for(WxAppinfo appinfo :apps) {
				if(StringUtils.isBlank(appinfo.getAppId())||StringUtils.isBlank(appinfo.getSecret())) {
					continue;
				}
				Calendar c = Calendar.getInstance();
				String date;
				for(int i = 2;i <=7;i++) { //查找最近7天有没有漏掉的数据
					c.add(Calendar.DAY_OF_YEAR, -1*i);
                    Date lastDate = c.getTime();
					date = new SimpleDateFormat("yyyyMMdd").format(c.getTime());
					if (!checkData(date,appinfo)) {
                        getData(lastDate, appinfo);
                    }
				}
			}
		}catch(Exception e) {
			logger.error("获取微信访问数据失败",e);
		}
	}

	private boolean checkData(String date,WxAppinfo appInfo) {
		WxUserVisit wxUserVisit = new WxUserVisit();
		wxUserVisit.setAppId(appInfo.getAppId());
		wxUserVisit.setTenantId(appInfo.getTenantId());
		wxUserVisit.setRefDate(date);
		PageInfo<WxUserVisit> page  = wxUserVisitService.listAsPage(wxUserVisit, 1, 10000);
		if (page.getList().size() > 0)
			return true;
		return false;
	}
	
	private void getData(Date lastDate,WxAppinfo appInfo) throws Exception {
        WxMaService wxMaService = null;
        if(isFmOpen) {
            wxMaService = openService.getWxOpenComponentService().getWxMaServiceByAppid(appInfo.getAppId());
        } else {
            wxMaService = MaUtil.getWeappService(appInfo);
        }
        try {
            List<WxMaVisitTrend> vtList = wxMaService.getAnalysisService().getDailyVisitTrend(lastDate, lastDate);
            logger.info(vtList.toString());
            for(WxMaVisitTrend maVisitTrend: vtList) {
                WxUserVisit v = new WxUserVisit();
                v.setAppId(appInfo.getAppId());
                v.setTenantId(appInfo.getTenantId());
                String time = maVisitTrend.getRefDate();
                Date dayDate = new SimpleDateFormat("yyyyMMdd").parse(time);
                v.setDayDate(dayDate);
                v.setRefDate(time);
                v.setSessionCnt(Integer.valueOf(maVisitTrend.getSessionCnt() + ""));
                v.setVisitPv(Integer.valueOf(maVisitTrend.getVisitPv()+""));
                v.setVisitUv(Integer.valueOf(maVisitTrend.getVisitUv()+""));
                v.setVisitUvNew(Integer.valueOf(maVisitTrend.getVisitUvNew()+""));
                v.setStayTimeSession(maVisitTrend.getStayTimeSession()+"");
                v.setVisitDepth(maVisitTrend.getVisitDepth()+"");
                v.setStayTimeUv(maVisitTrend.getStayTimeUv()+"");
                wxUserVisitService.saveOrUpdate(v);
            }
        } catch (WxErrorException e) {
            logger.error(e.getMessage());
        }
	}
}
