package com.qmth.teachcloud.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.bean.vo.FilePathVo;
import com.qmth.teachcloud.common.config.DictionaryConfig;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicSchool;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.UploadFileEnum;
import com.qmth.teachcloud.common.mapper.BasicSchoolMapper;
import com.qmth.teachcloud.common.service.BasicSchoolService;
import com.qmth.teachcloud.common.service.CommonCacheService;
import com.qmth.teachcloud.common.service.FileUploadService;
import com.qmth.teachcloud.common.service.SysUserService;
import com.qmth.teachcloud.common.util.Base64Util;
import com.qmth.teachcloud.common.util.FileStoreUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.List;

/**
 * <p>
 * 学校表 服务实现类
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Service
public class BasicSchoolServiceImpl extends ServiceImpl<BasicSchoolMapper, BasicSchool> implements BasicSchoolService {

    @Resource
    FileUploadService fileUploadService;

    @Resource
    CommonCacheService commonCacheService;

    @Resource
    SysUserService sysUserService;

    @Override
    public List<BasicSchool> listSchool(String code) {
        List<BasicSchool> schoolDtos = this.baseMapper.listSchool(code);
        for (BasicSchool schoolDto : schoolDtos) {
            if (StringUtils.isNotBlank(schoolDto.getInitPassword())) {
                schoolDto.setInitPassword(new String(Base64Util.decode(schoolDto.getInitPassword())));
            }
            String backgroundImageUrl = null;
            if (StringUtils.isNotBlank(schoolDto.getBackgroundImage())) {
                try {
                    backgroundImageUrl = fileUploadService.filePreview(schoolDto.getBackgroundImage());
                } catch (Exception e) {

                }
            }
            schoolDto.setBackgroundImage(backgroundImageUrl);
        }
        return schoolDtos;
    }

    @Override
    public boolean updateSchool(Long id, String code, String name, String initPassword, Boolean defaultSchool, Boolean hasPaperNumber, MultipartFile logo, String logoMd5, MultipartFile backgroundImage, String backgroundImageMd5) {
        BasicSchool basicSchool = this.getById(id);
        basicSchool.setCode(code);
        basicSchool.setName(name);

        // 学校logo
        if (logo != null) {
            try {
                if (!DigestUtils.md5DigestAsHex(logo.getBytes()).equals(logoMd5)) {
                    throw ExceptionResultEnum.ERROR.exception("学校logo图片上传有误");
                }
                String toBase64 = "data:image/png;base64," + new String(Base64.getEncoder().encode(logo.getBytes()), SystemConstant.CHARSET);
                basicSchool.setLogo(toBase64);
            } catch (Exception e) {
                throw ExceptionResultEnum.ERROR.exception(e.getMessage());
            }
        }
        // 登录页背景图
        if (backgroundImage != null) {
            try {
                if (!DigestUtils.md5DigestAsHex(backgroundImage.getBytes()).equals(backgroundImageMd5)) {
                    throw ExceptionResultEnum.ERROR.exception("登录页背景图片上传有误");
                }
                String backgroundFileName = basicSchool.getCode() + FilenameUtils.getExtension(backgroundImage.getOriginalFilename());
                FilePathVo filePathVo = fileUploadService.uploadFile(backgroundImage, UploadFileEnum.FILE, backgroundFileName, backgroundImageMd5);
                basicSchool.setBackgroundImage(JSON.toJSONString(filePathVo));
            } catch (Exception e) {
                throw ExceptionResultEnum.ERROR.exception(e.getMessage());
            }
        }

        // 修改密码时，同步更新上一次初始密码的用户密码
        String oldInitPassword = Base64Util.encode(SystemConstant.OLD_INIT_PASSWORD.getBytes());
        String currentInitPassword = basicSchool.getInitPassword();
        String newInitPassword = Base64Util.encode(initPassword.getBytes());
        if (StringUtils.isBlank(currentInitPassword) || !currentInitPassword.equals(initPassword)) {
            UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().set(SysUser::getPassword, newInitPassword)
                    .eq(SysUser::getSchoolId, id)
                    .and(q -> q.eq(SysUser::getPassword, oldInitPassword).or().eq(SysUser::getPassword, currentInitPassword));
            sysUserService.update(updateWrapper);
        }

        if (defaultSchool && !basicSchool.getDefaultSchool()) {
            List<BasicSchool> basicSchools = this.listByDefaultSchool(true);
            if (CollectionUtils.isNotEmpty(basicSchools)) {
                for (BasicSchool school : basicSchools) {
                    this.updateDefaultSchool(school.getId(), false);
                    // 清除学校缓存
                    commonCacheService.removeSchoolCache(school.getCode());
                    commonCacheService.removeSchoolCache(school.getId());
                }
            }
        }
        basicSchool.setDefaultSchool(defaultSchool);
        basicSchool.setHasPaperNumber(hasPaperNumber);

        // 清除学校缓存
        commonCacheService.removeSchoolCache(basicSchool.getCode());
        commonCacheService.removeSchoolCache(basicSchool.getId());

        basicSchool.setInitPassword(newInitPassword);
        return this.updateById(basicSchool);
    }

    @Override
    public List<BasicSchool> listByDefaultSchool(boolean defaultSchool) {
        QueryWrapper<BasicSchool> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicSchool::getDefaultSchool, defaultSchool);
        return this.list(queryWrapper);
    }

    @Override
    public void updateDefaultSchool(Long id, boolean defaultSchool) {
        UpdateWrapper<BasicSchool> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(BasicSchool::getDefaultSchool, defaultSchool)
                .eq(BasicSchool::getId, id);
        this.update(updateWrapper);
    }
}
