package org.springblade.modules.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.SysCache;
import org.springblade.core.launch.utils.INetUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tenant.BladeTenantProperties;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.member.dto.MemberDTO;
import org.springblade.modules.member.entity.MemberEntity;
import org.springblade.modules.member.enums.DateTypeEnum;
import org.springblade.modules.member.enums.MemberAuditStatusEnum;
import org.springblade.modules.member.mapper.MemberMapper;
import org.springblade.modules.member.service.IMemberInfoService;
import org.springblade.modules.system.entity.Tenant;
import org.springframework.stereotype.Service;
import org.springblade.modules.member.util.DateUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service

@AllArgsConstructor
public class MemberInfoServiceImpl extends BaseServiceImpl<MemberMapper, MemberEntity> implements IMemberInfoService {

	private final BladeTenantProperties tenantProperties;

	@Override
	public String getRandomName() {
		return "随机名字";
	}

	@Override
	public String getRandomAvatar() {
		return "http://cdn.zhenwopai.com/avatar/1564114490560";
	}

	@Override
	public MemberEntity addMember(String fromProductCode, String tenantId) {
		MemberEntity memberEntity = new MemberEntity();
		memberEntity.setNickName(this.getRandomName());
		memberEntity.setAvator(this.getRandomAvatar());
		memberEntity.setRegIp(INetUtil.getHostIp());
		memberEntity.setRegisterTime(DateUtil.now());
		memberEntity.setAuditStatus(MemberAuditStatusEnum.PASS.getCode());//默认审核通过
		memberEntity.setTenantId(this.addTenantId(tenantId));
		this.save(memberEntity);

		return memberEntity;
	}

	private String addTenantId(String tenantId) {
		if (StringUtil.isBlank(tenantId)) {
			tenantId = BladeConstant.ADMIN_TENANT_ID;
		}
		Tenant tenant = SysCache.getTenant(tenantId);
		if (Func.isNotEmpty(tenant)) {
			Integer accountNumber = tenant.getAccountNumber();
			if (tenantProperties.getLicense()) {
				String licenseKey = tenant.getLicenseKey();
				String decrypt = DesUtil.decryptFormHex(licenseKey, "0000000000000000");
				accountNumber = JsonUtil.parse(decrypt, Tenant.class).getAccountNumber();
			}
			Long tenantCount = baseMapper.selectCount(Wrappers.<MemberEntity>query().lambda().eq(MemberEntity::getTenantId, tenantId));
			if (accountNumber != null && accountNumber > 0 && accountNumber <= tenantCount) {
				throw new ServiceException("当前租户已到最大账号额度!");
			}
		}
		return tenantId;
	}


// TODO chenjs 以下方法是遗留方法，先放着，以后再重构


	@Override
	public Boolean getMemPhone(String phone) {
		MemberEntity entity = new MemberEntity();
		entity.setPhone(phone);
		QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>(entity);
		wrapper.last("limit 1");
		if (Func.isNotEmpty(this.getOne(wrapper))) {
			return true;
		} else {
			return false;
		}

	}

	@Override
	public MemberEntity setMemberInfoEntity(MemberDTO memberInfoDTO) {
		MemberEntity memberInfoEntity = BeanUtil.copy(memberInfoDTO, MemberEntity.class);
		return memberInfoEntity;
	}

	@Override
	public List<MemberEntity> getBirMemByDate(String dateType) {
		if (dateType.equals(DateTypeEnum.TODAY.getCode())) {//今日
			List<MemberEntity> birMemByDate = baseMapper.getBirMemByDate(DateUtil.getDayBegin(), DateUtil.getDayEnd());
			return birMemByDate;
		} else if (dateType.equals(DateTypeEnum.REC7DAY.getCode())) {//近7天
			List<MemberEntity> birMemByDate = baseMapper.getBirMemByDate(DateUtil.getFrontDay(new Date(), 7), DateUtil.getDayEnd());
			return birMemByDate;
		} else if (dateType.equals(DateTypeEnum.MONTH.getCode())) {//本月
			List<MemberEntity> birMemByDate = baseMapper.getBirMemByDate(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth());
			return birMemByDate;
		} else if (dateType.equals(DateTypeEnum.MONTHSURPLUS.getCode())) {//本月还有的会员生日人数（剩余的）
			List<MemberEntity> birMemByDate = baseMapper.getBirMemByDate(DateUtil.getDayEnd(), DateUtil.getEndDayOfMonth());
			return birMemByDate;
		} else {
			return null;
		}
	}

	//统计第一位会员注册日期到今天之间的天数
	public static Integer getDayNum(Date startTime) {
		long targetTime = startTime.getTime();
		long todayTime = new Date().getTime();
		long time = Math.abs(todayTime - targetTime);
		float day = (float) time / (float) (1000 * 60 * 60 * 24);
		Integer ceil = Integer.valueOf((int) Math.ceil(day));
		return ceil;
	}

	@Override
	public MemberEntity getMemberInfoByPhone(String phone) {
		if (Func.isEmpty(phone)) {
			return null;
		}
		MemberEntity entity = new MemberEntity();
		entity.setPhone(phone);
		QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>(entity);
		wrapper.last("limit 1");
		return this.getOne(wrapper);
	}

	@Override
	public BigDecimal averageDailyIncrease(Boolean includeDel) {
		QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
		wrapper.orderByAsc("create_time");

		//是否过滤掉过期的、退卡的、删除了的会员
		if (Func.isNotEmpty(includeDel)) {
			if (includeDel) {//是
				wrapper.eq("deleted", 0).or().eq("deleted", 1);
			}
		}

		List<MemberEntity> list = this.list(wrapper);
		Date createTime = list.get(0).getCreateTime();
		Integer dayNum = getDayNum(createTime);

		BigDecimal averageDaily = new BigDecimal(list.size()).divide(new BigDecimal(dayNum), 2, RoundingMode.HALF_UP);

		return averageDaily;
	}
}
