package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.api.feign.MallAdminFeignService;
import com.yonge.cooleshow.biz.dal.dto.search.OrderSearch;
import com.yonge.cooleshow.biz.dal.entity.UserOrder;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.GoodTypeEnum;
import com.yonge.cooleshow.biz.dal.service.UserOrderDetailService;
import com.yonge.cooleshow.biz.dal.service.UserOrderService;
import com.yonge.cooleshow.biz.dal.vo.UserOrderDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yonge.cooleshow.biz.dal.entity.StudentTime;
import com.yonge.cooleshow.biz.dal.dao.StudentTimeDao;
import com.yonge.cooleshow.biz.dal.service.StudentTimeService;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class StudentTimeServiceImpl extends ServiceImpl<StudentTimeDao, StudentTime> implements StudentTimeService {
    private final static Logger log = LoggerFactory.getLogger(StudentTimeServiceImpl.class);
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private UserOrderDetailService orderDetailService;
    @Autowired
    private MallAdminFeignService mallAdminFeignService;

    @Override
    public void totalStudentTime() {
        LocalDate toDay = LocalDate.now();
        //查询未记录第一次购买时间的订单
        OrderSearch query = new OrderSearch();
        query.setOrderClient(ClientEnum.STUDENT.getCode());
        query.setStartTime(LocalDateTime.of(toDay, LocalTime.MIN));
        query.setEndTime(LocalDateTime.of(toDay, LocalTime.MAX));

        Map<Long, StudentTime> studentTimeMap = new HashMap<>();

        List<UserOrder> orderList = userOrderService.selectUnRecordTimeOrder(query);
        if (!CollectionUtils.isEmpty(orderList)) {
            List<Long> userIds = orderList.stream().map(UserOrder::getUserId).collect(Collectors.toList());
            List<StudentTime> studentTimes = baseMapper.selectBatchIds(userIds);
            for (StudentTime studentTime : studentTimes) {
                studentTimeMap.put(studentTime.getUserId(), studentTime);
            }
        }

        Date now = new Date();
        for (UserOrder userOrder : orderList) {
            StudentTime studentTime = studentTimeMap.get(userOrder.getUserId());
            if (null == studentTime) {
                studentTime = new StudentTime();
                studentTime.setUserId(userOrder.getUserId());
            }

            List<UserOrderDetailVo> orderDetilListByOrderNo = orderDetailService.getOrderDetilListByOrderNo(userOrder.getOrderNo());

            for (UserOrderDetailVo detailVo : orderDetilListByOrderNo) {
                if (detailVo.getActualPrice() != null && detailVo.getActualPrice().compareTo(BigDecimal.ZERO) > 0 && studentTime.getFirstPayTime() == null) {
                    studentTime.setFirstPayTime(now);
                }
                if (null == studentTime.getFirstVipTime() && GoodTypeEnum.VIP.equals(detailVo.getGoodType())) {
                    studentTime.setFirstVipTime(now);
                }
                if (null == studentTime.getFirstPracticeTime() && GoodTypeEnum.PRACTICE.equals(detailVo.getGoodType())) {
                    studentTime.setFirstPracticeTime(now);
                }
                if (null == studentTime.getFirstLiveTime() && GoodTypeEnum.LIVE.equals(detailVo.getGoodType())) {
                    studentTime.setFirstLiveTime(now);
                }
                if (null == studentTime.getFirstVideoTime() && GoodTypeEnum.VIDEO.equals(detailVo.getGoodType())) {
                    studentTime.setFirstVideoTime(now);
                }
                if (null == studentTime.getFirstMusicTime() && GoodTypeEnum.MUSIC.equals(detailVo.getGoodType())) {
                    studentTime.setFirstMusicTime(now);
                }
                if (null == studentTime.getFirstActivityTime() && GoodTypeEnum.ACTI_REGIST.equals(detailVo.getGoodType())) {
                    studentTime.setFirstActivityTime(now);
                }
            }

            StudentTime old = baseMapper.selectById(userOrder.getUserId());
            if (null == old) {
                baseMapper.insert(studentTime);
            } else {
                baseMapper.updateById(studentTime);
            }
        }
        //商城用户统计
        Map<String, Object> param = new HashMap<>();
        param.put("startTime", query.getStartTime());
        param.put("endTime", query.getEndTime());
        List<Map<String, Object>> mallDataList = mallAdminFeignService.userOrderInfoList(param).getData();
        Map<Long, Date> timeMap = new HashMap<>();
        if (CollectionUtils.isEmpty(mallDataList)) {
            return;
        }

        for (Map<String, Object> data : mallDataList) {
            try {
                Long userId = Long.valueOf(data.get("userId").toString());
                Date receiveTime = new Date(Long.valueOf(data.get("receiveTime").toString()));
                timeMap.put(userId, receiveTime);
            } catch (Exception e) {
                log.error("统计学生首次使用时间异常，param is {}", JSONObject.toJSONString(data));
                continue;
            }
        }

        List<StudentTime> studentTimes = baseMapper.selectBatchIds(timeMap.keySet());
        Map<Long, StudentTime> mallStudentTimeMap = new HashMap<>();
        for (StudentTime studentTime : studentTimes) {
            mallStudentTimeMap.put(studentTime.getUserId(), studentTime);
        }

        for (Long userId : timeMap.keySet()) {
            StudentTime studentTime = mallStudentTimeMap.get(userId);
            if (null == studentTime) {
                studentTime = new StudentTime();
                studentTime.setUserId(userId);
            }

            if (null == studentTime.getFirstMallTime()) {
                studentTime.setFirstMallTime(timeMap.get(userId));
            }

            StudentTime old = baseMapper.selectById(userId);
            if (null == old) {
                baseMapper.insert(studentTime);
            } else {
                baseMapper.updateById(studentTime);
            }
        }

    }

    @Override
    public StudentTime setTimeByGoodType(StudentTime studentTime, GoodTypeEnum goodType) {
        if (null == studentTime) {
            studentTime = new StudentTime();
        }
        if (GoodTypeEnum.VIP.equals(goodType) && null == studentTime.getFirstVipTime()) {
            studentTime.setFirstVipTime(new Date());
        }
        if (GoodTypeEnum.PRACTICE.equals(goodType) && null == studentTime.getFirstPracticeTime()) {
            studentTime.setFirstPracticeTime(new Date());
        }
        if (GoodTypeEnum.LIVE.equals(goodType) && null == studentTime.getFirstLiveTime()) {
            studentTime.setFirstLiveTime(new Date());
        }
        if (GoodTypeEnum.VIDEO.equals(goodType) && null == studentTime.getFirstVideoTime()) {
            studentTime.setFirstVideoTime(new Date());
        }
        if (GoodTypeEnum.MUSIC.equals(goodType) && null == studentTime.getFirstMusicTime()) {
            studentTime.setFirstMusicTime(new Date());
        }
        return studentTime;
    }
}