package com.YuyeTech.HeartRate.game.userinfo.service;

import cn.hutool.core.date.DateUtil;
import com.YuyeTech.HeartRate.common.service.CommonServiceImpl;
import com.YuyeTech.HeartRate.enums.UserDeleteStatus;
import com.YuyeTech.HeartRate.game.TP_AppleInfo.projo.AppleInfo;
import com.YuyeTech.HeartRate.enums.UserEnum;
import com.YuyeTech.HeartRate.enums.UserStatus;
import com.YuyeTech.HeartRate.exception.UserException;
import com.YuyeTech.HeartRate.game.TP_AppleInfo.vo.AppleInfoVo;
import com.YuyeTech.HeartRate.game.TP_WxInfo.projo.WxInfo;
import com.YuyeTech.HeartRate.game.TP_WxInfo.vo.WxInfoVo;
import com.YuyeTech.HeartRate.game.imageInfo.service.PicturesService;
import com.YuyeTech.HeartRate.game.userDeleteLog.service.UserDeleteLogService;
import com.YuyeTech.HeartRate.game.userDeleteLog.vo.UserDeleteLogVo;
import com.YuyeTech.HeartRate.game.userinfo.projo.MainInfo;
import com.YuyeTech.HeartRate.game.userinfo.projo.UserInfo;
import com.YuyeTech.HeartRate.game.userinfo.repository.MainInfoRepository;
import com.YuyeTech.HeartRate.game.userinfo.vo.MainInfoVo;
import com.YuyeTech.HeartRate.game.TP_AppleInfo.service.AppleInfoService;
import com.YuyeTech.HeartRate.game.TP_WxInfo.service.WxInfoService;
import com.YuyeTech.HeartRate.service.FriendInfoService;
import com.YuyeTech.HeartRate.utils.AliyunOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author:slambb
 * @date:2019/12/31
 */
@Service
@Transactional
@Slf4j
public class MainInfoServiceImpl extends CommonServiceImpl<MainInfoVo, MainInfo, String> implements MainInfoService {

    @Autowired
    private MainInfoRepository mainInfoRepository;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private PicturesService picturesService;

    @Autowired
    private AppleInfoService appleInfoService;

    @Autowired
    private WxInfoService wxInfoService;

    @Autowired
    private UserDeleteLogService userDeleteLogService;

    @Autowired
    private FriendInfoService friendInfoService;



    @Override
    public MainInfo findMainInfoById(String userId) {
        MainInfo mainInfo = mainInfoRepository.findById(userId).orElse(null);
        if (mainInfo == null) {
            throw new UserException(UserEnum.USER_NOT_EXIST.getCode(), UserEnum.USER_NOT_EXIST.getMessage());
        }
        return mainInfo;
    }


    @Override
    public MainInfo addMainInfo(MainInfo mainInfo) {
        return mainInfoRepository.save(mainInfo);
    }

    @Override
    public MainInfo findMainInfoByPhoneNumberAndPassword(String telephoneNumber, String password) {
        MainInfo mainInfo = mainInfoRepository.findByTelephoneNumberAndPassword(telephoneNumber, password).orElse(null);
        return mainInfo;
    }

    @Override
    public MainInfo findMainInfoByEmailAndPassword(String email, String password) {
        MainInfo mainInfo = mainInfoRepository.findByEmailAndPassword(email, password).orElse(null);
        return mainInfo;
    }

    @Override
    public MainInfo findMainInfoByEmail(String mail) {
        MainInfo mainInfo = mainInfoRepository.findByEmail(mail).orElse(null);
        return mainInfo;
    }

    @Override
    public MainInfo findMainInfoByPhoneNumber(String telephoneNumber) {
        MainInfo mainInfo = mainInfoRepository.findByTelephoneNumber(telephoneNumber).orElse(null);
        return mainInfo;
    }

    /**
     * 1.挂起用户状态，修改 main_info 信息。
     * 2.记录到日志里面
     * 删除关联的表数据，外键关联
     *
     * @param userId
     * @return
     */
    @Override
    public String deleteMainInfoById(String userId,String type) {
        try {
            //记录挂起日志，
            UserDeleteLogVo userDeleteLog = userDeleteLogService.getVo(userId);
            if(userDeleteLog == null)
            {
                userDeleteLog = new UserDeleteLogVo();
                userDeleteLog.setCreateTime(DateUtil.date());
            }
            MainInfoVo mainInfoVo = super.getVo(userId);

            //判断是否处于挂起状态，如果是，暂时不再调用
            if (mainInfoVo.getStatus().equals(UserStatus.PENDING.ordinal())) {
                throw new RuntimeException("不可删除");
                //删除用户自定义头像
                //清除好友列表关系
                //super.delete(userId);
                //todo 后续考虑是否完成删除

            } else  {
                //正常状态下进行删除操作，先清空用户信息（包活wx登录和apple登录），然后记录一个日志
                //此删除只是把用户关联的数据清空，暂时保留一份记录
                userDeleteLog.setUserId(mainInfoVo.getUserId());

                UserInfo userInfo = userInfoService.findUserInfoById(userId,false);

                userDeleteLog.setUsername(userInfo.getUsername());
                userInfo.setUsername("");
                userInfo.setStatus(2);
                userInfoService.addUserInfo(userInfo);

                userDeleteLog.setTelephoneNumber(mainInfoVo.getTelephoneNumber());
                mainInfoVo.setTelephoneNumber("");
                userDeleteLog.setEmail(mainInfoVo.getEmail());
                mainInfoVo.setEmail("");
                //记录一个main info 状态
                mainInfoVo.setStatus(UserStatus.PENDING.ordinal());
                //删除apple_info信息
                AppleInfoVo appleInfo = appleInfoService.getVo(userId);
                if (appleInfo != null) {
                    userDeleteLog.setAppleId(appleInfo.getAppleId());
                    appleInfoService.delete(appleInfo.getUserId());
                }
                WxInfoVo wxInfo = wxInfoService.getVo(userId);
                if (wxInfo != null) {
                    userDeleteLog.setOpenid(wxInfo.getOpenid());
                    userDeleteLog.setUnionid(wxInfo.getUnionid());
                    wxInfoService.delete(wxInfo.getUserId());
                }
                //删除其他玩家添加的好友关系，friendID 字段相关删除即可。其他暂不做处理
                //这里friendId 传入自己的id
                friendInfoService.deleteFriendInfosByFriendId(userId);

                userDeleteLog.setUpdateTime(DateUtil.date());
                //记录一个log状态
                userDeleteLog.setStatus(UserDeleteStatus.PENDING.ordinal());
                userDeleteLog.setType(type);
                userDeleteLogService.save(userDeleteLog);
                super.save(mainInfoVo);
            }
//            mainInfoRepository.deleteById(userId);
        } catch (UserException e) {
            return "error";
        }
        return "success";
    }

    /**
     * 恢复数据时候，需要判断对应恢复的数据是否使用
     * 比如手机，邮箱，绑定的苹果登录id，wxid等是否已经被使用，如果被使用，不允许恢复
     * @param userId
     * @return
     */
    @Override
    public MainInfoVo restoreMainInfoById(String userId) {
        UserDeleteLogVo userDeleteLog = userDeleteLogService.getVo(userId);

        if(!userDeleteLog.getStatus().equals(UserDeleteStatus.PENDING.ordinal())){
            throw new RuntimeException("UserDeleteStatus 状态异常！");
        }

        //苹果信息处理
        if(StringUtils.hasText(userDeleteLog.getAppleId())){
            AppleInfo appleInfo = appleInfoService.findByAppleId(userDeleteLog.getAppleId());
            if(appleInfo != null)
            {
                throw new RuntimeException("appleid 已被占用，不能恢复！");
            }
        }
        //wx信息处理
        if(StringUtils.hasText(userDeleteLog.getOpenid())){
            WxInfo wxInfo = wxInfoService.findWxInfoByOpenid(userDeleteLog.getOpenid());
            if(wxInfo != null)
            {
                throw new RuntimeException("openid 已被占用，不能恢复！");
            }
        }
        if(StringUtils.hasText(userDeleteLog.getUnionid())){
            WxInfo wxInfo = wxInfoService.findWxInfoByUnionid(userDeleteLog.getUnionid());
            if(wxInfo != null)
            {
                throw new RuntimeException("unionid 已被占用，不能恢复！");
            }
        }

        /**
         * 电话号码，邮箱
         */
        if(StringUtils.hasText(userDeleteLog.getTelephoneNumber())){
            MainInfo mainInfo = findMainInfoByPhoneNumber(userDeleteLog.getTelephoneNumber());
            if(mainInfo != null)
            {
                throw new RuntimeException("Telephone 已被占用，不能恢复！");
            }
        }

        if(StringUtils.hasText(userDeleteLog.getEmail())){
            MainInfo mainInfo = findMainInfoByEmail(userDeleteLog.getEmail());
            if(mainInfo != null)
            {
                throw new RuntimeException("Email 已被占用，不能恢复！");
            }
        }
        MainInfoVo mainInfoVo = super.getVo(userId);
        if(mainInfoVo == null){
            throw new RuntimeException("mainInfoVo 数据异常！");
        }
        mainInfoVo.setTelephoneNumber(userDeleteLog.getTelephoneNumber());
        mainInfoVo.setEmail(userDeleteLog.getEmail());
        //设置为恢复信息状态
        mainInfoVo.setStatus(UserStatus.RESTORE.ordinal());
        super.save(mainInfoVo);
        //恢复绑定的授权信息
        if(StringUtils.hasText(userDeleteLog.getAppleId())){
            AppleInfo appleInfo = new AppleInfo();
            appleInfo.setUserId(mainInfoVo.getUserId());
            appleInfo.setAppleId(userDeleteLog.getAppleId());
            appleInfoService.addAppleInfo(appleInfo);
        }
        if(StringUtils.hasText(userDeleteLog.getOpenid())
                && StringUtils.hasText(userDeleteLog.getUnionid())){
            WxInfo wxInfo = new WxInfo();
            wxInfo.setUserId(mainInfoVo.getUserId());
            wxInfo.setOpenid(userDeleteLog.getOpenid());
            wxInfo.setUnionid(userDeleteLog.getUnionid());
            wxInfoService.addWxInfo(wxInfo);
        }

        //设置恢复状态
        userDeleteLog.setStatus(UserDeleteStatus.RESTORE.ordinal());
        userDeleteLogService.save(userDeleteLog);

        return mainInfoVo;
    }
}
