package com.yida.data.school.index.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.GenerateUrlLink;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.school.EduDeptHomeApp;
import com.yida.data.common.core.entity.system.EduBaseApp;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.enums.UserTypeEnum;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.WxPublicUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.school.dto.index.SaveDeptHomeAppDTO;
import com.yida.data.school.index.mapper.EduDeptHomeAppMapper;
import com.yida.data.school.index.service.EduDeptHomeAppService;
import com.yida.data.system.feign.RemoteBaseAppService;
import javax.sound.sampled.Line.Info;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 部门微官网应用配置 Service实现
 *
 * @author ZYJ
 * @date 2023-06-28 15:24:25
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class EduDeptHomeAppServiceImpl extends ServiceImpl
    <EduDeptHomeAppMapper, EduDeptHomeApp> implements EduDeptHomeAppService {

    private final RemoteBaseAppService remoteBaseAppService;

    private final CommonService commonService;

    private final WxPublicUtil wxPublicUtil;

    private final RedisService redisService;

    @Override
    public void addDeptHomeApp(SaveDeptHomeAppDTO dto) {
        EduDeptHomeApp already = this
            .getOne(Wrappers.<EduDeptHomeApp>lambdaQuery().eq(EduDeptHomeApp::getDeptId, FebsUtil.getDeptId())
                .eq(EduDeptHomeApp::getBaseAppId, dto.getBaseAppId()));

        if (ObjectUtil.isNull(dto.getId())) {
            Asserts.isTrue(ObjectUtil.isNull(already), "该学校已创建此应用");
        } else {
            if (ObjectUtil.isNotNull(already) && ObjectUtil.notEqual(dto.getId(), already.getId())) {
                throw new FebsException("该学校已创建此应用");
            }
        }
        EduBaseApp baseApp = null;
        if (dto.getAppType() == 0) {
            baseApp = remoteBaseAppService.getById(dto.getBaseAppId()).getData();
            Asserts.isTrue(ObjectUtil.isNotNull(baseApp), "不存在此基础应用");
        }

        EduDeptHomeApp homeApp = new EduDeptHomeApp();
        BeanUtils.copyProperties(dto, homeApp);
        homeApp.setDeptId(FebsUtil.getDeptId());
        if (dto.getAppType() == 0) {
            homeApp.setAppSrc(baseApp.getAppSrc());
            homeApp.setCode(baseApp.getCode());
        }
        if (ObjectUtil.isNotNull(dto.getId())) {
            redisService.del(CachePrefixConstant.DEPT_HOME_APP_INFO, String.valueOf(dto.getId()));
        }
        saveOrUpdate(homeApp);
    }

    @Override
    public void enableApp(Long id, Integer status) {
        EduDeptHomeApp homeApp = new EduDeptHomeApp();
        homeApp.setId(id);
        homeApp.setEnableStatus(status);
        updateById(homeApp);
    }

    @Override
    public String getWxPublicURLLink(String schoolId, Long userId, Integer userType, Long localAppId) {
        if (redisService.hasKey(CachePrefixConstant.USER_GENERATE_URL_LINK + userId + "" + userType + "" + localAppId)) {
            return (String) redisService
                .get(CachePrefixConstant.USER_GENERATE_URL_LINK + userId + "" + userType + "" + localAppId);
        }

        EduDeptHomeApp homeApp = null;
        if (redisService.hHasKey(CachePrefixConstant.DEPT_HOME_APP_INFO, String.valueOf(localAppId))) {
            homeApp = (EduDeptHomeApp) redisService.hget(CachePrefixConstant.DEPT_HOME_APP_INFO, String.valueOf(localAppId));
        } else {
            homeApp = getById(localAppId);
            if (ObjectUtil.isNotNull(homeApp)) {
                redisService.hset(CachePrefixConstant.DEPT_HOME_APP_INFO, String.valueOf(localAppId), homeApp);
            }
        }
        if (ObjectUtil.isNull(homeApp)) {
            log.error("获取小程序链接失败：【{}】", localAppId);
            throw new FebsException("获取小程序链接失败");
        }
        String avatar = "";
        if (ObjectUtil.equals(UserTypeEnum.PARENT_USER_TYPE.getType(), userType)) {
            EduStudent student = commonService.getStudentById(userId);
            if (ObjectUtil.isNull(student)) {
                log.error("获取小程序链接失败：用户信息不存在：【{}】", userId);
                throw new FebsException("获取小程序链接失败，用户信息不存在");
            }
            if (ObjectUtil.isNull(student.getAvatar())) {
                log.error("获取小程序链接失败：用户头像信息不存在：【{}】", userId);
                throw new FebsException("获取小程序链接失败，用户头像信息不存在");
            }
            avatar = student.getAvatar();
        } else {
            EduStaff staff = commonService.getStaffById(userId);
            if (ObjectUtil.isNull(staff)) {
                log.error("获取小程序链接失败：用户信息不存在：【{}】", userId);
                throw new FebsException("获取小程序链接失败，用户信息不存在");
            }
            if (ObjectUtil.isNull(staff.getAvatar())) {
                log.error("获取小程序链接失败：用户头像信息不存在：【{}】", userId);
                throw new FebsException("获取小程序链接失败，用户头像信息不存在");
            }
            avatar = staff.getAvatar();
        }
        GenerateUrlLink generateUrlLink = new GenerateUrlLink();
        generateUrlLink.setPath(homeApp.getAppSrc());
        generateUrlLink.setExpireType(1);
        generateUrlLink.setQuery("schoolId=" + schoolId + "&userId=" + userId + "&userType=" + userType + "&avatar=" + avatar);
        String urlLink = wxPublicUtil
            .generateUrlLink(wxPublicUtil.getAccessToken(homeApp.getAppId(), homeApp.getAppSecret()), generateUrlLink);
        //缓存学生信息 29天
        redisService.set(CachePrefixConstant.USER_GENERATE_URL_LINK + userId + "" + userType + "" + localAppId, urlLink,
            60 * 60 * 24 * 29L);
        return urlLink;
    }
}
