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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.bean.dto.SchoolDto;
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.mapper.BasicSchoolMapper;
import com.qmth.teachcloud.common.service.BasicSchoolService;
import com.qmth.teachcloud.common.service.CommonCacheService;
import com.qmth.teachcloud.common.util.FileStoreUtil;
import org.springframework.stereotype.Service;
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
    DictionaryConfig dictionaryConfig;

    @Resource
    FileStoreUtil fileStoreUtil;

    @Resource
    CommonCacheService commonCacheService;

    @Override
    public List<SchoolDto> listSchool() {
        return this.baseMapper.listSchool();
    }

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

        if (logo != null) {
            try {
                String toBase64 = "data:image/png;base64," + new String(Base64.getEncoder().encode(logo.getBytes()), SystemConstant.CHARSET);
                basicSchool.setLogo(toBase64);
            } catch (Exception e) {
                log.error(SystemConstant.LOG_ERROR, e);
            } finally {
                commonCacheService.removeSchoolCache(basicSchool.getCode());
                commonCacheService.removeSchoolCache(basicSchool.getId());
            }
        }
        return this.updateById(basicSchool);
    }
}
