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

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.school.EduSchoolMatter;
import com.yida.data.common.core.entity.school.EduSchoolMatterMatterGroup;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.common.core.utils.WxPublicUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.school.news.mapper.EduSchoolMatterMapper;
import com.yida.data.school.news.mapper.EduSchoolMatterMatterGroupMapper;
import com.yida.data.school.news.service.EduSchoolMatterMatterGroupService;
import com.yida.data.school.news.service.EduSchoolMatterService;
import com.yida.data.school.vo.index.MatterPageInfoVO;
import com.yida.data.system.feign.RemoteDeptService;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service实现
 *
 * @author zhanghaijun
 * @date 2021-07-19 17:21:58
 */
@Service
@Slf4j
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EduSchoolMatterServiceImpl extends ServiceImpl
    <EduSchoolMatterMapper, EduSchoolMatter> implements EduSchoolMatterService {

    private final EduSchoolMatterMatterGroupService eduSchoolMatterMatterGroupService;
    private final EduSchoolMatterMatterGroupMapper eduSchoolMatterMatterGroupMapper;
    private final WxPublicUtil wxPublicUtil;
    private final RemoteDeptService remoteDeptService;
    private final CommonService commonService;

    @Override
    public IPage<MatterPageInfoVO> listMatterPage(Page page, Long schoolId, Integer type, String keyword,
        Long groupId) {
        return baseMapper.listMatterPage(page, schoolId, type, keyword, groupId);
    }

    @Override
    public void saveMatter(EduSchoolMatter matter) {
        if (matter.getId() == null
            && count(Wrappers.lambdaQuery(new EduSchoolMatter()).eq(EduSchoolMatter::getSchoolId, matter.getSchoolId())
            .eq(EduSchoolMatter::getUrl, matter.getUrl())) == 0) {
            Dept school = commonService.getDept(matter.getSchoolId());
            String path = FileUtil.downloadToLocal(matter.getUrl());
            File file = new File(path);
            double size = file.length() / 1024D / 1024D;
            switch (matter.getType()) {
                case 0:
                    Asserts.isTrue(size < 10D, "图片最大为10M");
                    break;
                case 1:
                    Asserts.isTrue(size < 10D, "视频最大为10M");
                    break;
                case 2:
                    Asserts.isTrue(size < 10D, "音频最大为2M");
                    break;
                default:
                    break;
            }
            saveOrUpdate(matter);
            if (matter.getGroupId() != null) {
                batchCluster(matter.getGroupId(), new Long[]{matter.getId()});
            }
            // TODO: 2022/3/31 暂时屏蔽上传到微信公众号
//            if (StrUtil.isNotBlank(school.getWxPublicAppId())) {
//                // 上传文件到微信公众号素材库
//                String token = wxPublicUtil.getAccessToken(school.getWxPublicAppId(), school.getWxPublicSecret());
//                String videoTitle = matter.getType() == 1 ? matter.getName() : null;
//                String videoDescription = matter.getType() == 1 ? "上传视频" : null;
//                String mediaId = wxPublicUtil
//                    .uploadMaterial(EduSchoolMatter.FILE_TYPE.get(matter.getType()), videoTitle, videoDescription, file, token);
//                matter.setWxPublicMediaId(mediaId);
//                updateById(matter);
//            }
        }
    }

    @Override
    public void saveMatterBatch(List<String> urls, Long schoolId, Integer type) {
        for (String url : urls) {
            if (count(Wrappers.<EduSchoolMatter>lambdaQuery().eq(EduSchoolMatter::getSchoolId, schoolId)
                .eq(EduSchoolMatter::getUrl, url)) == 0) {
                EduSchoolMatter matter = new EduSchoolMatter();
                matter.setUrl(url);
                matter.setSchoolId(schoolId);
                matter.setType(type);
                matter.setName(StrUtil.uuid().replace("-", ""));
                try {
                    saveMatter(matter);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("上传素材失败,url:[{}],schoolId:[{}],msg:[{}],stack:[{}]", url, schoolId, e.getMessage(),
                        e.getStackTrace());
                }
            }
        }
    }

    @Override
    @Transactional
    public void delMatterBatch(List<Long> ids, Long schoolId) {
        Collection<EduSchoolMatter> eduSchoolMatters = listByIds(ids);
        Dept school = commonService.getDept(schoolId);
        // 删除素材
        removeByIds(ids);
        // 删除关联关系
        eduSchoolMatterMatterGroupService.remove(Wrappers.lambdaQuery(new EduSchoolMatterMatterGroup())
            .in(EduSchoolMatterMatterGroup::getMatterId, ids));
        if (StrUtil.isNotBlank(school.getWxPublicAppId())) {
            String token;
            try {
                token = wxPublicUtil.getAccessToken(school.getWxPublicAppId(), school.getWxPublicSecret());
            } catch (Exception e) {
                log.error("获取token失败", e);
                return;
            }
            for (EduSchoolMatter matter : eduSchoolMatters) {
                if (StrUtil.isNotBlank(matter.getWxPublicMediaId())) {
                    try {
                        wxPublicUtil.deleteMaterial(matter.getWxPublicMediaId(), token);
                    } catch (Exception e) {
                        log.error("删除微信公众号素材失败", e);
                    }

                }
            }
        }
    }

    @Override
    public void batchCluster(Long groupId, Long[] matterIds) {
        List<EduSchoolMatterMatterGroup> saveList = new ArrayList<>();
        for (Long matterId : matterIds) {
            EduSchoolMatterMatterGroup matterMatterGroup = new EduSchoolMatterMatterGroup();
            matterMatterGroup.setMatterId(matterId);
            matterMatterGroup.setMatterGroupId(groupId);
            if (eduSchoolMatterMatterGroupService.count(Wrappers.lambdaQuery(new EduSchoolMatterMatterGroup())
                .eq(EduSchoolMatterMatterGroup::getMatterId, matterId)
                .eq(EduSchoolMatterMatterGroup::getMatterGroupId, groupId)) == 0) {
                saveList.add(matterMatterGroup);
            }
        }
        eduSchoolMatterMatterGroupService.saveBatch(saveList);
    }

    @Override
    public void batchUnCluster(Long groupId, Long[] matterIds) {
        eduSchoolMatterMatterGroupService.remove(Wrappers.lambdaQuery(new EduSchoolMatterMatterGroup())
            .eq(EduSchoolMatterMatterGroup::getMatterGroupId, groupId)
            .in(EduSchoolMatterMatterGroup::getMatterId, matterIds));
    }

    @Override
    public EduSchoolMatter getMatterByUrl(String url, Long schoolId) {
        return getOne(Wrappers.lambdaQuery(new EduSchoolMatter()).eq(EduSchoolMatter::getSchoolId, schoolId)
            .eq(EduSchoolMatter::getUrl, url));
    }
}
