package com.iformall.controller.mem;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.iformall.annotation.SystemControllerLog;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.dto.MarkingCouponDataReportDto;
import com.iformall.domain.po.WxCouponOrder;
import com.iformall.mapper.WxCUserBasicInfoMapper;
import com.iformall.service.WxCUserBasicInfoService;
import com.iformall.utils.DataUtil;
import com.iformall.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.iformall.common.ResultData;
import com.iformall.domain.dto.WxCUserBasicInfoDto;
import com.iformall.domain.vo.CUserDateAmountVo;
import com.iformall.domain.vo.TouchUsersReportVo;
import com.iformall.domain.vo.UserStructureVo;
import com.iformall.service.WxCUserService;
import com.iformall.service.WxCouponOrderService;
import com.iformall.service.WxUserVisitService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("wxCUserData")
@Api(description = "会员首页报表数据")
public class WxCUserDataController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCUserService wxCUserService;
    @Autowired
    private WxUserVisitService wxUserVisitService;
    @Autowired
    private WxCouponOrderService wxCouponOrderService;
    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @GetMapping("findUserCountData")
    @ApiOperation("查询用户数量接口")
    @SystemControllerLog(description = "会员首页-报表数据-查询用户数量接口")
    public ResultData findUserCountData() {
        logger.debug("[" + getIpAddr() + "] WxCUserDataController::findUserCountData");
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(getTenantId());
        long allCount = wxCUserService.findCount(dto);//总数
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();

        long todayCount = 0;
        long yesterdayCount = 0;
        long dayOfWeekCount = 0;
        List<UserStructureVo> weekVos = new ArrayList<>();//周会员数
        List<UserStructureVo> monthVos = new ArrayList<>();//周会员数

        for (int i = 29, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            dto.setStartTime(c.getTime());
            c.add(Calendar.DAY_OF_YEAR, 1);
            dto.setEndTime(c.getTime());
            long count = wxCUserService.findCount(dto);
            UserStructureVo vo = new UserStructureVo();

            vo.setName(new SimpleDateFormat("MM/dd").format(dto.getStartTime()));
            vo.setSortNum(sortNum++);
            vo.setCount(count);
            if (i <= 7) {
                UserStructureVo vow = new UserStructureVo();
                vow.setSortNum(vo.getSortNum());
                vow.setName(vo.getName());
                vow.setCount(vo.getCount());

                if (i == 1) {
                    yesterdayCount = vow.getCount();
                }
                if (i == 0) {
                    todayCount = vow.getCount();
                }
                if (i == 7) {
                    dayOfWeekCount = vow.getCount();
                } else {
                    weekVos.add(vow);
                }
            }
            monthVos.add(vo);
        }

        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);
        String dayPercentage = "--";
        if (yesterdayCount > 0) {
            Long count = todayCount - yesterdayCount;
            dayPercentage = nf.format(count.doubleValue() / new Double(yesterdayCount).doubleValue());
        }
        String weekPercentage = "--";
        if (dayOfWeekCount > 0) {
            Long count = todayCount - dayOfWeekCount;
            weekPercentage = nf.format(count.doubleValue() / new Double(dayOfWeekCount).doubleValue());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("allCount", allCount);//会员总数
        map.put("todayCount", todayCount);//今日新增会员数
        map.put("weekVos", weekVos);//月用户增加数列表
        map.put("monthVos", monthVos);//月用户增加数列表
        map.put("dayPercentage", dayPercentage);//日环比
        map.put("weekPercentage", weekPercentage);    //周同比

        long weekVosCount = 0l;
        for (UserStructureVo us:weekVos) {
            weekVosCount += us.getCount();
        }
        map.put("weekVosCount", weekVosCount);    //周新增会员

        //自然增长
        //String startdate = DateUtils.getTimeBefore(30, new Date());
        //String systemTime = DateUtils.getSystemTime("yyyy-MM-dd");
        //Date startDate = DateUtils.getDateFromString(startdate + " 00:00:00","yyyy-MM-dd HH:mm:ss").getTime();
        //Date endDate = DateUtils.getDateFromString(systemTime + " 23:59:59","yyyy-MM-dd HH:mm:ss").getTime();
        WxCUserBasicInfoDto wxCUserBasicInfoDto = new WxCUserBasicInfoDto();
        wxCUserBasicInfoDto.setTenantId(getTenantId());
        wxCUserBasicInfoDto.setStartTime(null);
        wxCUserBasicInfoDto.setEndTime(null);
        map.put("growCount", wxCUserBasicInfoService.findGrowUserCount(wxCUserBasicInfoDto));
        //全部导入的
        map.put("importCount", wxCUserBasicInfoService.findImportUserCount(wxCUserBasicInfoDto));
        //全部
        map.put("allHistoryUserCount", wxCUserBasicInfoService.findCount(wxCUserBasicInfoDto));
        return new ResultData(map);
    }

    @ApiOperation("查询用户活跃量")
    @GetMapping("findUserVisitData")
    @SystemControllerLog(description = "会员首页-报表数据-查询用户活跃量")
    public ResultData findUserVisitData() {
        logger.debug("[" + getIpAddr() + "] WxCUserDataController::findUserVisitData");
        HashMap<String, Object> params = new HashMap<>();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, -1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date endTime = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, -30);
        Date startTime = c.getTime();
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("tenantId", getTenantId());
        MarkingCouponDataReportDto markingCouponDataReportDto = new MarkingCouponDataReportDto();
        markingCouponDataReportDto.setTenantId(getTenantId());
        markingCouponDataReportDto.setStartTime(startTime);
        markingCouponDataReportDto.setEndTime(endTime);
        List<TouchUsersReportVo> list = wxUserVisitService.touchUsersReportList(markingCouponDataReportDto);
        Map<String, TouchUsersReportVo> dateMap = new HashMap<>();
        for (TouchUsersReportVo vo : list) {
            dateMap.put(vo.getXTime(), vo);
        }
        List<UserStructureVo> weekVos = new ArrayList<>();//每周uv
        List<UserStructureVo> monthVos = new ArrayList<>();//每月uv

        //今日活跃数
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        params.put("startTime",today+" 00:00:00");
        params.put("endTime",today+" 23:59:59");
        long todayVisitCount = wxUserVisitService.queryVisitUv(params);

        long yesterdayCount = 0;//昨天活跃数
        long beforeYesterdayCount = 0;//前天活跃数
        long thisMonthCount = 0;//月总数
        long dayOfWeekCount = 0;//上周周x数
        for (int i = 29, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(endTime);
            c.add(Calendar.DAY_OF_YEAR, -i);
            String dayStr = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(c.getTime()));
            vo.setSortNum(sortNum++);
            if (dateMap.get(dayStr) != null) {
                TouchUsersReportVo rv = dateMap.get(dayStr);
                Long l = new Long((long) rv.getUv());
                vo.setCount(l);
            } else {
                vo.setCount(0);
            }

            if (i <= 7) {
                UserStructureVo vow = new UserStructureVo();
                vow.setName(vo.getName());
                vow.setSortNum(vo.getSortNum());
                vow.setCount(vo.getCount());

                if (i == 0) {
                    yesterdayCount = vow.getCount();
                }
                if (i == 1) {
                    beforeYesterdayCount = vow.getCount();
                }
                if (i == 7) {
                    dayOfWeekCount = vow.getCount();
                } else {
                    weekVos.add(vow);
                }

            }
            monthVos.add(vo);
            thisMonthCount += vo.getCount();
        }

        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);
        String dayPercentage = "--";
        if (beforeYesterdayCount > 0) {
            Long count = yesterdayCount - beforeYesterdayCount;
            dayPercentage = nf.format(count.doubleValue() / new Double(beforeYesterdayCount).doubleValue());
        }
        String weekPercentage = "--";
        if (dayOfWeekCount > 0) {
            Long count = yesterdayCount - dayOfWeekCount;
            weekPercentage = nf.format(count.doubleValue() / new Double(dayOfWeekCount).doubleValue());
        }
        Map<String, Object> mapVo = new HashMap<>();
        mapVo.put("yesterdayCount", yesterdayCount);//昨日活跃数
        mapVo.put("thisMonthCount", thisMonthCount);//近一个月活跃数
        mapVo.put("weekVos", weekVos);//周活跃数列表
        mapVo.put("monthVos", monthVos);//月活跃数列表
        mapVo.put("dayPercentage", dayPercentage);//日环比
        mapVo.put("weekPercentage", weekPercentage);    //周同比

        mapVo.put("todayVisitCount", todayVisitCount);    //今日活跃数
        long weekVosCount = 0l;
        for (UserStructureVo us:weekVos) {
            weekVosCount += us.getCount();
        }
        mapVo.put("weekVosCount", weekVosCount);//周活跃数总数
        return new ResultData(mapVo);
    }

    @ApiOperation("查询用户消费金额")
    @GetMapping("findUserAmountData")
    @SystemControllerLog(description = "会员首页-报表数据-查询用户消费金额")
    public ResultData findUserAmountData() {
        logger.debug("[" + getIpAddr() + "] WxCUserDataController::findUserAmountData");
        String tenantId = getTenantId();
        Calendar c = Calendar.getInstance();
        Date today = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date endTime = c.getTime();//明天0点
        c.add(Calendar.DAY_OF_YEAR, -30);//三十天前
        Date startTime = c.getTime();
        WxCouponOrder wxCouponOrder = new WxCouponOrder();
        wxCouponOrder.setTenantId(tenantId);
        wxCouponOrder.setStartTime(startTime);
        wxCouponOrder.setEndTime(endTime);
        int thisMonthCount = wxCouponOrderService.queryPriceTotal(wxCouponOrder);//月消费金额
        c.clear();
        c.setTime(endTime);
        Date eTime = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, -30);
        Date sTime = c.getTime();
        List<CUserDateAmountVo> datas = wxCouponOrderService.queryPriceTotalGroup(tenantId, sTime, eTime);
        Map<String, Integer> dataMap = new HashMap<>();
        for (CUserDateAmountVo v : datas) {
            dataMap.put(v.getXTime(), v.getPrice());
        }
        Integer todayCount = 0;//今日金额数
        Integer yesterdayCount = 0;//昨日金额数
        Integer dayOfWeekCount = 0;//上周x
        List<UserStructureVo> weekVos = new ArrayList<>();//周消费金额
        List<UserStructureVo> monthVos = new ArrayList<>();//周消费金额
        for (int i = 29, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(c.getTime()));
            vo.setSortNum(sortNum++);
            if (dataMap.get(dateStr) != null) {
                int price = dataMap.get(dateStr);
                vo.setPrice(price);
            } else {
                vo.setPrice(0);
            }
            if (i <= 7) {
                UserStructureVo vow = new UserStructureVo();
                vow.setName(vo.getName());
                vow.setSortNum(vo.getSortNum());
                vow.setPrice(vo.getPrice());

                if (i == 0) {
                    todayCount = vow.getPrice();
                }
                if (i == 1) {
                    yesterdayCount = vow.getPrice();
                }
                if (i == 7) {
                    dayOfWeekCount = vow.getPrice();
                } else {
                    weekVos.add(vow);
                }
            }
            monthVos.add(vo);
        }

        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);
        String dayPercentage = "--";
        if (yesterdayCount > 0) {
            Integer count = todayCount - yesterdayCount;
            dayPercentage = nf.format(count.doubleValue() / new Double(yesterdayCount).doubleValue());
        }
        String weekPercentage = "--";
        if (dayOfWeekCount > 0) {
            Integer count = todayCount - dayOfWeekCount;
            weekPercentage = nf.format(count.doubleValue() / new Double(dayOfWeekCount).doubleValue());
        }
        Map<String, Object> map = new HashMap<>();
        DecimalFormat df = new DecimalFormat("0.00");
        map.put("todayCount", df.format((float) todayCount / 100));//今日消费金额
        String thisMonthCountStr = df.format((float) thisMonthCount / 100);
        map.put("thisMonthCount", thisMonthCountStr);//近一个月消费金额数
        map.put("dayPercentage", dayPercentage);//日环比
        map.put("weekPercentage", weekPercentage);    //周同比
        map.put("weekVos", weekVos);//一周金额列表
        map.put("monthVos", monthVos);//一月金额列表
        return new ResultData(map);
    }


}



