package com.mcwl.communityCenter.service.impl;

import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.AjaxResult;
import com.mcwl.common.core.domain.R;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.ShareCodeUtils;
import com.mcwl.communityCenter.constant.InviteConstant;
import com.mcwl.communityCenter.constant.StatusConstant;
import com.mcwl.communityCenter.domain.Community;
import com.mcwl.communityCenter.domain.CommunityUser;
import com.mcwl.communityCenter.domain.Invite;
import com.mcwl.communityCenter.domain.InviteCodeMapping;
import com.mcwl.communityCenter.mapper.CommunityUserMapper;
import com.mcwl.communityCenter.mapper.InviteMapper;
import com.mcwl.communityCenter.service.CommunityService;
import com.mcwl.communityCenter.service.CommunityUserService;
import com.mcwl.communityCenter.service.InviteCodeMappingService;
import com.mcwl.communityCenter.service.InviteService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class InviteServiceImpl extends ServiceImpl<InviteMapper, Invite> implements InviteService {

    private final InviteCodeMappingService inviteCodeMappingService;

    private final CommunityService communityService;

    private final InviteMapper inviteMapper;

    private final CommunityUserMapper communityUserMapper;


    @Override
    public String getInviteCode(Long communityId) {


        // 查询用户的社区
        Community userCommunity = communityService.lambdaQuery()
                .eq(Community::getId, communityId)
                .one();

        if (Objects.isNull(userCommunity)) {
            return null;
        }

        String idCode = ShareCodeUtils.idToCode(SecurityUtils.getUserId());

        String inviteCode = "https://www.yaoqing.com?communityId=" + communityId + "&inviteCode=" + idCode;

        // 插入数据库
        InviteCodeMapping inviteCodeMapping = new InviteCodeMapping();
        inviteCodeMapping.setUserId(SecurityUtils.getUserId());
        inviteCodeMapping.setInviteCode(idCode);
        inviteCodeMapping.setCommunityId(communityId);
        inviteCodeMapping.setStatus(StatusConstant.STATUS_AVAILABLE);
        inviteCodeMappingService.save(inviteCodeMapping);

        return inviteCode;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Object> acceptInvite(Long communityId, String inviteCode) {

        // 解析邀请码
        Long userId;
        try {
            userId = ShareCodeUtils.codeToId(inviteCode);
        } catch (Exception e) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "邀请码有误");
        }

        if (Objects.isNull(userId)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "邀请码有误");
        }

        // 判断是否是同一个人
        if (Objects.equals(userId, SecurityUtils.getUserId())) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "不能邀请自己");
        }

        Community community = communityService.getByTenantIdAndCommunityId(userId, communityId);

        // 查询邀请码
        InviteCodeMapping inviteCodeMapping = inviteCodeMappingService.lambdaQuery()
                .eq(InviteCodeMapping::getUserId, userId)
                .eq(InviteCodeMapping::getCommunityId, communityId)
                .eq(InviteCodeMapping::getInviteCode, inviteCode)
                .eq(InviteCodeMapping::getStatus, StatusConstant.STATUS_AVAILABLE)
                .one();

        if (Objects.isNull(inviteCodeMapping)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "没查询到该邀请码");
        }

        // 判断是否已经邀请过
        Invite inv = inviteMapper.isInvite(userId, communityId, SecurityUtils.getUserId());
        if (Objects.nonNull(inv)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "不能重复邀请");
        }


        inviteCodeMapping.setStatus(StatusConstant.STATUS_UNAVAILABLE);
        inviteCodeMappingService.updateById(inviteCodeMapping);

        Invite invite = new Invite();
        invite.setType(InviteConstant.INVITE_ADMIN);
        invite.setFeeType(InviteConstant.INVITE_FEE);
        baseMapper.insert(invite);

        Calendar now = Calendar.getInstance();
        Date startTime = now.getTime();
        now.add(Calendar.YEAR, community.getValidityDay());
        Date endTime = now.getTime();

        communityUserMapper.insert(CommunityUser
                .builder()
                .tenantId(userId)
                .communityId(communityId)
                .userId(SecurityUtils.getUserId())
                .userType(1)
                .inviteId(invite.getId())
                .startTime(startTime)
                .endTime(endTime)
                .build());

        return R.ok(null, "邀请成功");
    }
}
