package com.fs.his.service.impl;

import java.io.InputStream;
import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.QRutils;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.course.domain.FsUserCourse;
import com.fs.his.domain.FsAppVersion;
import com.fs.his.domain.FsUser;
import com.fs.his.domain.FsUserInvited;
import com.fs.his.enums.FsUserIntegralLogTypeEnum;
import com.fs.his.mapper.FsUserInvitedMapper;
import com.fs.his.param.FsUserAddIntegralParam;
import com.fs.his.param.FsUserAddIntegralTemplateParam;
import com.fs.his.service.IFsAppVersionService;
import com.fs.his.service.IFsUserIntegralLogsService;
import com.fs.his.service.IFsUserInvitedService;
import com.fs.his.service.IFsUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户填写邀请码记录Service业务层处理
 *
 * @author fs
 * @date 2025-03-06
 */
@Service
public class FsUserInvitedServiceImpl extends ServiceImpl<FsUserInvitedMapper, FsUserInvited> implements IFsUserInvitedService {
    @Autowired
    private IFsAppVersionService appVersionService;
    @Autowired
    private IFsUserService userService;
    @Autowired
    private IFsUserIntegralLogsService integralLogsService;

    /**
     * 查询用户填写邀请码记录
     *
     * @param id 用户填写邀请码记录主键
     * @return 用户填写邀请码记录
     */
    @Override
    public FsUserInvited selectFsUserInvitedById(Long id) {
        return baseMapper.selectFsUserInvitedById(id);
    }

    /**
     * 查询用户填写邀请码记录列表
     *
     * @param fsUserInvited 用户填写邀请码记录
     * @return 用户填写邀请码记录
     */
    @Override
    public List<FsUserInvited> selectFsUserInvitedList(FsUserInvited fsUserInvited) {
        return baseMapper.selectFsUserInvitedList(fsUserInvited);
    }

    /**
     * 新增用户填写邀请码记录
     *
     * @param fsUserInvited 用户填写邀请码记录
     * @return 结果
     */
    @Override
    public int insertFsUserInvited(FsUserInvited fsUserInvited) {
        fsUserInvited.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertFsUserInvited(fsUserInvited);
    }

    /**
     * 修改用户填写邀请码记录
     *
     * @param fsUserInvited 用户填写邀请码记录
     * @return 结果
     */
    @Override
    public int updateFsUserInvited(FsUserInvited fsUserInvited) {
        fsUserInvited.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateFsUserInvited(fsUserInvited);
    }

    /**
     * 批量删除用户填写邀请码记录
     *
     * @param ids 需要删除的用户填写邀请码记录主键
     * @return 结果
     */
    @Override
    public int deleteFsUserInvitedByIds(Long[] ids) {
        return baseMapper.deleteFsUserInvitedByIds(ids);
    }

    /**
     * 删除用户填写邀请码记录信息
     *
     * @param id 用户填写邀请码记录主键
     * @return 结果
     */
    @Override
    public int deleteFsUserInvitedById(Long id) {
        return baseMapper.deleteFsUserInvitedById(id);
    }

    @Override
    public String getDownloadPoster() {
        //获取下载地址
        FsAppVersion newUserAppVersion = appVersionService.getNewUserAppVersion(1);//当前默认安卓
        if (newUserAppVersion == null) {
            return null;
        }
        String link = newUserAppVersion.getH5Url();
        if (StringUtils.isNotBlank(link)) {
            //二维码
            InputStream qrCodeStream = QRutils.getQRCodeImageInputStream(link, 250, 250);
            InputStream mainImageStream = null;
            String imgUrl = "https://cos.his.cdwjyyh.com/fs/20250308/038f33f3cd4b4b7786e5647f2d5ca609.jpg"; //暂时固定
            try {
                mainImageStream = QRutils.downloadAndEncodeImageToInputStream(imgUrl);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            try {
                String url = QRutils.embedQRCode(mainImageStream, qrCodeStream);
                if (StringUtils.isNotBlank(url)) {
                    return url;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    /**
     * 填写邀请码
     *
     * @param fsUserInvited
     * @return
     */
    @Override
    @Transactional
    public AjaxResult fillInvCode(FsUserInvited fsUserInvited) {
        //1.参数校验
        Long userId = fsUserInvited.getUserId();
        Long invitedUserId = fsUserInvited.getInvitedUserId();
        //1.1 是否已经获取奖励
        FsUser invitedUser = userService.selectFsUserByUserId(invitedUserId);
        if (invitedUser == null) {
            return AjaxResult.error("参数异常");
        }
        if (invitedUser.getParentId() != null) {
            return AjaxResult.error("邀请码奖励每个账号只能领取1次");
        }
        //1.2 不能是本人id
        if (invitedUserId.equals(userId)) {
            return AjaxResult.error("不能填写本账号的邀请码");
        }
        //1.3查看邀请人是否存在
        FsUser fsUser = userService.selectFsUserByUserId(userId);
        if (fsUser == null) {
            return AjaxResult.error("邀请码不合法");
        }
        //1.4 不能互相绑定
        if (fsUser.getParentId() != null) {
            if (Objects.equals(fsUser.getParentId(), invitedUserId)) {
                return AjaxResult.error("邀请码不合法");
            }
        }
        //1.4 被邀请人注册超过7天填写不奖励
        Date createTime = invitedUser.getCreateTime();
        if (createTime != null) {
            Date nowDate = DateUtils.getNowDate();
            if (nowDate.after(DateUtils.addDays(createTime, 7))) {
                return AjaxResult.error("超时填写，无奖励");
            }
        }
        //2.添加奖励
        //2.1被邀请人获得2000芳华币
        FsUserAddIntegralTemplateParam invitedParam = new FsUserAddIntegralTemplateParam();
        invitedParam.setLogType(FsUserIntegralLogTypeEnum.TYPE_19.getValue());
        invitedParam.setUserId(invitedUserId);
        invitedParam.setBusinessId(userId.toString());
        R invitedR = integralLogsService.addIntegralTemplate(invitedParam);
        //2.2邀请人A获得1000芳华币
        FsUserAddIntegralTemplateParam param = new FsUserAddIntegralTemplateParam();
        param.setUserId(userId);
        param.setLogType(FsUserIntegralLogTypeEnum.TYPE_18.getValue());
        param.setBusinessId(invitedUserId.toString());
        R r = integralLogsService.addIntegralTemplate(param);
//        return AjaxResult.success(invitedR.get("msg").toString() + r.get("msg").toString());
        if ("200".equals(invitedR.get("code").toString()) && "200".equals(r.get("code").toString())){
            FsUser temp = new FsUser();
            temp.setParentId(userId);
            temp.setUserId(invitedUserId);
            userService.updateFsUser(temp);
        }
        return AjaxResult.success();
    }
}
