package com.ym.mec.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.ActivityApplyStudentType;
import com.ym.mec.biz.dal.entity.Teacher;
import com.ym.mec.biz.dal.entity.VipGroupActivity;
import com.ym.mec.biz.dal.entity.VipGroupCategory;
import com.ym.mec.biz.dal.page.ActivityStudentQueryInfo;
import com.ym.mec.biz.dal.page.DoubleEleven2021QueryInfo;
import com.ym.mec.biz.dal.page.VipGroupActivityQueryInfo;
import com.ym.mec.biz.service.VipGroupActivityService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.util.collection.MapUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class VipGroupActivityServiceImpl extends BaseServiceImpl<Integer, VipGroupActivity>  implements VipGroupActivityService {
	
	@Autowired
	private VipGroupActivityDao vipGroupActivityDao;
	@Autowired
	private ActivityApplyStudentTypeDao activityApplyStudentTypeDao;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private VipGroupCategoryDao vipGroupCategoryDao;
	@Autowired
	private SysConfigDao sysConfigDao;

	@Override
	public BaseDAO<Integer, VipGroupActivity> getDAO() {
		return vipGroupActivityDao;
	}

	private void checkSettlement(VipGroupSalarySettlementTypeDto settlementTypeDto){
		if(Objects.nonNull(settlementTypeDto) && settlementTypeDto.getSalarySettlementType() != null){
			switch (settlementTypeDto.getSalarySettlementType()){
				case TEACHER_DEFAULT:
					break;
				case FIXED_SALARY:
					if(Objects.isNull(settlementTypeDto.getSettlementValue())){
						throw new BizException("请指定固定课酬");
					}
					break;
				default:
					throw new BizException("错误的课酬结算标准!");
			}
		}
	}

	@Override
	public VipGroupActivityAddDto addVipGroupActivity(VipGroupActivityAddDto vipGroupActivityAddDto) {

		if(Objects.isNull(vipGroupActivityAddDto.getOrganId())){
			throw new BizException("请指定部门!");
		}
		VipGroupSalarySettlementDto vipGroupSalarySettlement = vipGroupActivityAddDto.getVipGroupSalarySettlement();
		if(vipGroupSalarySettlement != null){
			checkSettlement(vipGroupSalarySettlement.getOfflineSalarySettlement());
			checkSettlement(vipGroupSalarySettlement.getGiveVipOfflineSalarySettlement());
			checkSettlement(vipGroupSalarySettlement.getPracticeSalarySettlement());
			checkSettlement(vipGroupSalarySettlement.getGivePracticeSalarySettlement());
		}
		vipGroupActivityAddDto.setSalarySettlementJson(JSON.toJSONString(vipGroupActivityAddDto.getVipGroupSalarySettlement()));
		ActivityApplyStudentType applyToStudentType = getApplyToStudentType(vipGroupActivityAddDto.getApplyToStudentType());
//		vipGroupActivityAddDto.setApplyToStudentType(JSONObject.toJSONString(applyToStudentType));
		super.insert(vipGroupActivityAddDto);
		applyToStudentType.setActivityId(vipGroupActivityAddDto.getId());
		activityApplyStudentTypeDao.insert(applyToStudentType);
		return vipGroupActivityAddDto;
	}

	private ActivityApplyStudentType getApplyToStudentType(String applyToStudentType){
		ActivityApplyStudentType activityApplyStudentType = new ActivityApplyStudentType();
		if(StringUtils.isNotEmpty(applyToStudentType)){
			List<Integer> collect = Arrays.stream(applyToStudentType.split(",")).mapToInt(Integer::valueOf).boxed().collect(Collectors.toList());
			//0：老用户；1：新用户，2会员，3非会员
			if(collect.contains(0) && collect.contains(1)){
				activityApplyStudentType.setNewStudent(-1);
			}else {
				if(collect.contains(0)){
					activityApplyStudentType.setNewStudent(0);
				}
				if(collect.contains(1)){
					activityApplyStudentType.setNewStudent(1);
				}
			}
			if(collect.contains(2) && collect.contains(3)){
				activityApplyStudentType.setMemberFlag(-1);
			}else {
				if(collect.contains(2)){
					activityApplyStudentType.setMemberFlag(1);
				}
				if(collect.contains(3)){
					activityApplyStudentType.setMemberFlag(0);
				}
			}
		}
		return activityApplyStudentType;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public VipGroupActivityAddDto updateVipGroupActivity(VipGroupActivityAddDto vipGroupActivityAddDto, Integer operatorId) {
		VipGroupActivity oldVipGroupActivity = vipGroupActivityDao.get(vipGroupActivityAddDto.getId());
		if(Objects.isNull(oldVipGroupActivity)){
			throw new BizException("活动不存在!");
		}
		if("PROGRESS".equals(oldVipGroupActivity.getStatus())){
			oldVipGroupActivity.setCoursesStartTime(vipGroupActivityAddDto.getCoursesStartTime());
			oldVipGroupActivity.setCoursesEndTime(vipGroupActivityAddDto.getCoursesEndTime());
			oldVipGroupActivity.setStartTime(vipGroupActivityAddDto.getStartTime());
			oldVipGroupActivity.setEndTime(vipGroupActivityAddDto.getEndTime());
			oldVipGroupActivity.setApplyToStudentType(vipGroupActivityAddDto.getApplyToStudentType());
			oldVipGroupActivity.setStudentMaxUsedTimes(vipGroupActivityAddDto.getStudentMaxUsedTimes());
			super.update(oldVipGroupActivity);
		}else {
			VipGroupSalarySettlementDto vipGroupSalarySettlement = vipGroupActivityAddDto.getVipGroupSalarySettlement();
			if(vipGroupSalarySettlement != null){
				checkSettlement(vipGroupSalarySettlement.getOfflineSalarySettlement());
				checkSettlement(vipGroupSalarySettlement.getGiveVipOfflineSalarySettlement());
				checkSettlement(vipGroupSalarySettlement.getPracticeSalarySettlement());
				checkSettlement(vipGroupSalarySettlement.getGivePracticeSalarySettlement());
			}
			vipGroupActivityAddDto.setSalarySettlementJson(JSON.toJSONString(vipGroupActivityAddDto.getVipGroupSalarySettlement()));
			super.update(vipGroupActivityAddDto);
		}
		ActivityApplyStudentType applyToStudentType = getApplyToStudentType(vipGroupActivityAddDto.getApplyToStudentType());
		applyToStudentType.setActivityId(vipGroupActivityAddDto.getId());
		activityApplyStudentTypeDao.updateByActivity(applyToStudentType);
		return vipGroupActivityAddDto;
	}

	@Override
	public List<VipGroupActivity> findByVipGroupCategory(ActivityQueryDto activityQueryDto) {
		Teacher teacher = teacherDao.get(activityQueryDto.getTeacherId());
		if(Objects.isNull(teacher)){
			throw new BizException("未找到指定教师");
		}
		String organId = activityQueryDto.getOrganId();
		if(StringUtils.isBlank(organId)){
			organId = teacher.getTeacherOrganId().toString();
			if (StringUtils.isNotEmpty(teacher.getFlowOrganRange())) {
				organId += "," + teacher.getFlowOrganRange();
			}
			activityQueryDto.setOrganId(organId);
		}
		return vipGroupActivityDao.findByCategory(activityQueryDto);
	}

	@Override
	public List<ExportVipGroupActivityDto> exportVipGroupActivity(VipGroupActivityQueryInfo queryInfo) {
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);
		return vipGroupActivityDao.exportVipGroupActivity(params);
	}

    @Override
    public List<WaitCourseActivityDto> queryWaitCourseActivity(Integer teacherId,String organId) {
		return vipGroupActivityDao.queryWaitCourseActivity(teacherId,organId, TenantContextHolder.getTenantId());
    }

    @Override
    public ActivityWaitCourseStudentNumDto getActivityWaitCourseStudentNum(Integer userId, Integer activityId) {
		ActivityWaitCourseStudentNumDto activityWaitCourseStudentNum = vipGroupActivityDao.getActivityWaitCourseStudentNum(userId, activityId);
		VipGroupActivity activity = vipGroupActivityDao.get(activityId);
		if(StringUtils.isNotEmpty(activity.getVipGroupCategoryIdList())){
			VipGroupCategory category = vipGroupCategoryDao.get(Integer.parseInt(activity.getVipGroupCategoryIdList().split(",")[0]));
			activity.setVipGroupCategoryNames(category.getName());
			activity.setVipGroupCategoryNum(category.getStudentNum());
		}
		if(StringUtils.isNotEmpty(activity.getGiveCategoryId())){
			VipGroupCategory category = vipGroupCategoryDao.get(Integer.parseInt(activity.getGiveCategoryId()));
			activity.setGiveCategoryName(category.getName());
			activity.setGiveCategoryNum(category.getStudentNum());
		}
		activityWaitCourseStudentNum.setVipGroupActivity(activity);
		return activityWaitCourseStudentNum;
    }

	@Override
	public PageInfo<ActivityWaitCourseStudentNumDto> getActivityStudentCanCourseNum(ActivityStudentQueryInfo queryInfo) {
		PageInfo<ActivityWaitCourseStudentNumDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List<ActivityWaitCourseStudentNumDto> dataList = null;
		int count = vipGroupActivityDao.countActivityStudentCanCourseNum(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = vipGroupActivityDao.getActivityStudentCanCourseNum(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

    @Override
    public List<DoubleEleven2021Dto> organDoubleEleven2021Statis(OrganDoubleEleven2021StatisDto statisDto) {
		String order = statisDto.getOrder();
		String sort = statisDto.getSort();
		List<DoubleEleven2021Dto> doubleEleven2021Dtos = vipGroupActivityDao.countOrganDoubleEleven2021Statis(statisDto.getOrganId());
		if(doubleEleven2021Dtos != null && doubleEleven2021Dtos.size() > 0){
			List<Integer> organIdList = doubleEleven2021Dtos.stream().map(e -> e.getOrganId()).collect(Collectors.toList());
			List<DoubleEleven2021ActivityDto> activityDtoList = vipGroupActivityDao.countOrganActivityStatis(organIdList);
			Map<Integer, List<DoubleEleven2021ActivityDto>> collect = new HashMap<>();
			if(activityDtoList != null && activityDtoList.size() > 0){
				collect = activityDtoList.stream().collect(Collectors.groupingBy(DoubleEleven2021ActivityDto::getOrganId));
			}
			Map<Long, Long> maps = MapUtil.convertIntegerMap(vipGroupActivityDao.countOrganGiveMemberNum(organIdList));
			for (DoubleEleven2021Dto doubleEleven2021Dto : doubleEleven2021Dtos) {
				if(doubleEleven2021Dto.getTotalBuyAmount().compareTo(BigDecimal.ZERO) > 0){
					doubleEleven2021Dto.setAvgBuyAmount(
							doubleEleven2021Dto.getTotalBuyAmount().divide(new BigDecimal(doubleEleven2021Dto.getTotalBuyNum()),2,BigDecimal.ROUND_CEILING));
				}
				List<DoubleEleven2021ActivityDto> activityDtos = collect.get(doubleEleven2021Dto.getOrganId());
				if(activityDtos != null && activityDtos.size() > 0){
					for (DoubleEleven2021ActivityDto activityDto : activityDtos) {
						if(activityDto.getType() == 1){
							doubleEleven2021Dto.setVip1V120Amount(activityDto.getBuyAmount());
							doubleEleven2021Dto.setVip1V120Num(activityDto.getBuyNum());
						}else if (activityDto.getType() == 2){
							doubleEleven2021Dto.setVip1V140Amount(activityDto.getBuyAmount());
							doubleEleven2021Dto.setVip1V140Num(activityDto.getBuyNum());
						}else if (activityDto.getType() == 3){
							doubleEleven2021Dto.setVip1V220Amount(activityDto.getBuyAmount());
							doubleEleven2021Dto.setVip1V220Num(activityDto.getBuyNum());
						}else if (activityDto.getType() == 4){
							doubleEleven2021Dto.setVip1V240Amount(activityDto.getBuyAmount());
							doubleEleven2021Dto.setVip1V240Num(activityDto.getBuyNum());
						}else if (activityDto.getType() == 5){
							doubleEleven2021Dto.setMusicTheoryAmount(activityDto.getBuyAmount());
							doubleEleven2021Dto.setMusicTheoryNum(activityDto.getBuyNum());
						}
					}
				}
				Long giveNum = maps.get(doubleEleven2021Dto.getOrganId().longValue());
				doubleEleven2021Dto.setGiveMemberNum(giveNum == null?0l:giveNum);
			}
			if(sort.equals("totalBuyAmount")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getTotalBuyAmount)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getTotalBuyAmount).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("totalBuyNum")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getTotalBuyNum)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getTotalBuyNum).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("avgBuyAmount")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getAvgBuyAmount)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getAvgBuyAmount).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("giveMemberNum")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getGiveMemberNum)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getGiveMemberNum).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("vip1v120Amount")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V120Amount)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V120Amount).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("vip1v140Amount")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V140Amount)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V140Amount).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("vip1v220Amount")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V220Amount)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V220Amount).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("vip1v240Amount")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V240Amount)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V240Amount).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("musicTheoryAmount")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getMusicTheoryAmount)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getMusicTheoryAmount).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("vip1v120Num")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V120Num)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V120Num).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("vip1v140Num")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V140Num)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V140Num).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("vip1v220Num")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V220Num)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V220Num).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("vip1v240Num")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V240Num)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getVip1V240Num).reversed()).collect(Collectors.toList());
				}
			}else if(sort.equals("musicTheoryNum")){
				if(order.equals("ASC")){
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getMusicTheoryNum)).collect(Collectors.toList());
				}else {
					doubleEleven2021Dtos = doubleEleven2021Dtos.stream().sorted(Comparator.comparing(DoubleEleven2021Dto::getMusicTheoryNum).reversed()).collect(Collectors.toList());
				}
			}
		}
		return doubleEleven2021Dtos;
    }

	@Override
	public Object doubleEleven2021Statis() {
		//获取总成交数据
		DoubleEleven2021Dto doubleEleven2021Dto = vipGroupActivityDao.countDoubleEleven2021Statis();
		if(doubleEleven2021Dto.getTotalBuyAmount().compareTo(BigDecimal.ZERO) > 0){
			doubleEleven2021Dto.setAvgBuyAmount(
					doubleEleven2021Dto.getTotalBuyAmount().divide(new BigDecimal(doubleEleven2021Dto.getTotalBuyNum()),2,BigDecimal.ROUND_CEILING));
		}
		//获取活动成交数据
		List<DoubleEleven2021ActivityDto> activityDtos = vipGroupActivityDao.countActivityStatis();
		if(activityDtos != null && activityDtos.size() > 0){
			for (DoubleEleven2021ActivityDto activityDto : activityDtos) {
				if(activityDto.getType() == 1){
					doubleEleven2021Dto.setVip1V120Amount(activityDto.getBuyAmount());
					doubleEleven2021Dto.setVip1V120Num(activityDto.getBuyNum());
				}else if (activityDto.getType() == 2){
					doubleEleven2021Dto.setVip1V140Amount(activityDto.getBuyAmount());
					doubleEleven2021Dto.setVip1V140Num(activityDto.getBuyNum());
				}else if (activityDto.getType() == 3){
					doubleEleven2021Dto.setVip1V220Amount(activityDto.getBuyAmount());
					doubleEleven2021Dto.setVip1V220Num(activityDto.getBuyNum());
				}else if (activityDto.getType() == 4){
					doubleEleven2021Dto.setVip1V240Amount(activityDto.getBuyAmount());
					doubleEleven2021Dto.setVip1V240Num(activityDto.getBuyNum());
				}else if (activityDto.getType() == 5){
					doubleEleven2021Dto.setMusicTheoryAmount(activityDto.getBuyAmount());
					doubleEleven2021Dto.setMusicTheoryNum(activityDto.getBuyNum());
				}
			}
		}
		//获取赠送会员数
		Integer giveMemberNum = vipGroupActivityDao.countGiveMemberNum();
		doubleEleven2021Dto.setGiveMemberNum(giveMemberNum==null?0l:giveMemberNum.longValue());
		return doubleEleven2021Dto;
	}

	@Override
	public PageInfo<DoubleEleven2021OrderDetailDto> doubleEleven2021OrderDetail(DoubleEleven2021QueryInfo queryInfo) {
		PageInfo<DoubleEleven2021OrderDetailDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List<DoubleEleven2021OrderDetailDto> dataList = null;
		int count = vipGroupActivityDao.countDoubleEleven2021OrderDetail(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = vipGroupActivityDao.queryDoubleEleven2021OrderDetail(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}
}
