/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.guosen.loginUser.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.guosen.ActivityUv.service.IActivityUvService;
import org.springblade.modules.guosen.agenter.entity.Agenter;
import org.springblade.modules.guosen.agenter.service.IAgenterService;
import org.springblade.modules.guosen.loginUser.dto.LoginDTO;
import org.springblade.modules.guosen.loginUser.dto.LoginUserDTO;
import org.springblade.modules.guosen.loginUser.entity.LoginUser;
import org.springblade.modules.guosen.loginUser.mapper.LoginUserMapper;
import org.springblade.modules.guosen.loginUser.service.ILoginUserService;
import org.springblade.modules.guosen.loginUser.vo.LoginUserVO;
import org.springblade.modules.guosen.loginUser.vo.LoginWebVO;
import org.springblade.modules.guosen.production.entity.Production;
import org.springblade.modules.guosen.production.service.IProductionService;
import org.springblade.modules.guosen.rank.service.RankService;
import org.springblade.modules.guosen.rank.service.RedisService;
import org.springblade.modules.guosen.userActivityStatistical.entity.UserActivityStatistical;
import org.springblade.modules.guosen.userActivityStatistical.service.IUserActivityStatisticalService;
import org.springblade.modules.guosen.useragenter.entity.UserAgenter;
import org.springblade.modules.guosen.useragenter.service.IUserAgenterService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-06-16
 */
@Service
public class LoginUserServiceImpl extends BaseServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

	@Resource @Lazy
	private IUserActivityStatisticalService userActivityStatisticalService;
	@Resource
	private IAgenterService agenterService;
	@Resource
	private IUserAgenterService userAgenterService;
	@Resource @Lazy
	private IProductionService productionService;
	@Resource
	private IActivityUvService activityUvService;
	@Resource @Lazy
	private RankService rankService;

	@Override
	public IPage<LoginUserVO> selectLoginUserPage(IPage<LoginUserVO> page, LoginUserVO loginUser) {
		return page.setRecords(baseMapper.selectLoginUserPage(page, loginUser));
	}

	@Override
	@Transactional
	public LoginWebVO login(LoginDTO loginDTO) {
		//通过openid获取用户信息
		LoginUser user = this.getOne(Condition.getQueryWrapper(new LoginUser()).lambda()
			.eq(LoginUser::getOpenid, loginDTO.getOpenid()));
		if (user != null) {
			LoginWebVO loginWebVO = new LoginWebVO();
			BeanUtil.copyProperties(user, loginWebVO);
			return loginWebVO;
		}
		//用户信息为空，直接插进数据库中
		this.save(loginDTO);
		if (loginDTO.getAgenterId() != null) {
			//查看分享人是不是代理者
			Agenter agenter = agenterService.getOne(Condition.getQueryWrapper(new Agenter()).lambda()
				.eq(Agenter::getUserId, loginDTO.getAgenterId()));
			if (agenter != null) {
				//分享人是代理者,插入代理记录表
				UserAgenter userAgenter = new UserAgenter();
				userAgenter.setUserId(loginDTO.getId());//新用户id
				userAgenter.setAgenterId(agenter.getId());//代理表id
				userAgenterService.save(userAgenter);
			}
		}
		LoginWebVO loginWebVO = new LoginWebVO();
		BeanUtil.copyProperties(loginDTO, loginWebVO);
		return loginWebVO;
	}

	@Override
	public LoginWebVO getLoginWebVO(Long userId) {
		LoginWebVO loginWebVO = new LoginWebVO();
		LoginUser loginUser = this.getById(userId);
		if (loginUser == null) {
			return null;
		}
		loginWebVO.setTotalHot(loginUser.getTotalHot());
		loginWebVO.setAvatar(loginUser.getAvatar());
		loginWebVO.setNickName(loginUser.getNickName());
		loginWebVO.setCover(loginUser.getCover());
		loginWebVO.setVideo(loginUser.getVideo());

		List<UserActivityStatistical> list = userActivityStatisticalService.list(Condition.getQueryWrapper(new UserActivityStatistical()).lambda()
			.eq(UserActivityStatistical::getUserId, userId));

		BigDecimal totalCash = BigDecimal.ZERO;
		for (UserActivityStatistical item : list) {
			BigDecimal itemTotalCash = item.getTotalCash();
			if (itemTotalCash == null) {
				itemTotalCash = BigDecimal.ZERO;
			}
			totalCash = totalCash.add(itemTotalCash);
		}
		loginWebVO.setTotalCost(totalCash);
		return loginWebVO;
	}

	@Override
	@Transactional
	public Boolean delete(List<Long> idList) {
		for (Long userId : idList) {
			//删除缓存里的数据
			List<UserActivityStatistical> list = userActivityStatisticalService.list(Condition.getQueryWrapper(new UserActivityStatistical()).lambda()
				.eq(UserActivityStatistical::getUserId, userId));
			for (UserActivityStatistical item : list) {
				Long activityId = item.getActivityId();
				rankService.zSetRemove(activityId.toString(),userId.toString(),0);
			}
			List<Production> productions = productionService.list(Condition.getQueryWrapper(new Production()).lambda()
				.eq(Production::getUserId, userId));

			for (Production production : productions) {
				Long activityId = production.getActivityId();
				Long productionId = production.getId();
				rankService.zSetRemove(activityId.toString(), productionId.toString(), 1);
			}

			Map map = new HashMap();
			map.put("user_id", userId);

			//删除统计表的记录
			userActivityStatisticalService.removeByMap(map);
			//删除作品表的记录
			productionService.removeByMap(map);
			//删除活动uv里的数据
//			activityUvService.removeByMap(map);
		}
		return this.deleteLogic(idList);
	}
}
