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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.school.EduSchoolHomeMicro;
import com.yida.data.common.core.entity.school.EduSchoolHomeMicroCol;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduYidaApp;
import com.yida.data.common.core.utils.AppUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.school.index.mapper.EduSchoolHomeMicroMapper;
import com.yida.data.school.index.service.EduSchoolHomeMicroColService;
import com.yida.data.school.index.service.EduSchoolHomeMicroService;
import com.yida.data.school.news.service.EduSchoolMatterService;
import com.yida.data.system.feign.RemoteYidaAppService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Service实现
 *
 * @author zhanghaijun
 * @date 2021-07-19 17:21:58
 */
@Slf4j
@Service
@RefreshScope
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EduSchoolHomeMicroServiceImpl extends ServiceImpl
        <EduSchoolHomeMicroMapper, EduSchoolHomeMicro> implements EduSchoolHomeMicroService {
    private final static String INFO_URL = "/schoolHomePage/";
    private final EduSchoolHomeMicroColService eduSchoolHomeMicroColService;
    private final EduSchoolMatterService eduSchoolMatterService;
    private final RemoteYidaAppService remoteYidaAppService;
    private final CommonService commonService;
    @Value("${febs.pageUrl}")
    private String pageUrl;

    @Override
    public void saveMicro(EduSchoolHomeMicro micro) {
        Dept school = commonService.getDept(micro.getSchoolId());
        EduYidaApp yidaApp = remoteYidaAppService.getAppBySchool(micro.getSchoolId()).getData();
        EduSchoolHomeMicro exist = getOne(Wrappers.lambdaQuery(new EduSchoolHomeMicro())
                .eq(EduSchoolHomeMicro::getSchoolId, micro.getSchoolId()));
        if (exist != null) {
            micro.setId(exist.getId());
            micro.setYidaAppRegionId(exist.getYidaAppRegionId());
        }
        log.info("微官网：[{}],已存在:[{}]", micro, exist);
        // 遍历栏目 进行app端的修改
        JSONArray contenIds = new JSONArray();
        List<String> urlList = new ArrayList<>();
        for (EduSchoolHomeMicroCol microCol : micro.getColList()) {
            if (StrUtil.isNotBlank(microCol.getCoverUrl())) {
                urlList.add(microCol.getCoverUrl());
            }
            microCol.setSchoolId(micro.getSchoolId());
            eduSchoolHomeMicroColService.saveOrUpdate(microCol);
            if (microCol.getIsShow() == 0) {
                if (microCol.getId() != null) {
                    EduSchoolHomeMicroCol existCol = eduSchoolHomeMicroColService.getById(microCol.getId());
                    microCol.setYidaAppFunctionId(existCol.getYidaAppFunctionId());
                }
                // 填充url
                if (microCol.getType() == 0) {
                    microCol.setUrl(pageUrl + INFO_URL + EduSchoolHomeMicroCol.INFO_URL + "?colId=" + microCol.getId());
                } else if (microCol.getType() == 1) {
                    microCol.setUrl(pageUrl + INFO_URL + EduSchoolHomeMicroCol.SCHOOL_URL + "?colId=" + microCol.getId());
                } else if (microCol.getType() == 2) {
                    microCol.setUrl(pageUrl + INFO_URL + EduSchoolHomeMicroCol.TEACHER_URL + "?colId=" + microCol.getId());
                }
                if (school.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
                    String appManuscriptId = AppUtil.functionSave(microCol, yidaApp);
                    contenIds.add(new JSONObject() {{
                        set("id", appManuscriptId);
                        set("sort", microCol.getSort());
                        set("img", microCol.getCoverUrl());
                    }});
                    microCol.setYidaAppFunctionId(appManuscriptId);
                }
                eduSchoolHomeMicroColService.saveOrUpdate(microCol);
            }
        }
        // 保存到素材库
        eduSchoolMatterService.saveMatterBatch(urlList, micro.getSchoolId(), 0);
        List<EduSchoolHomeMicroCol> microCols =
                eduSchoolHomeMicroColService.list(Wrappers.lambdaQuery(new EduSchoolHomeMicroCol()).eq(EduSchoolHomeMicroCol::getSchoolId, micro.getSchoolId()));
        if (CollUtil.isNotEmpty(microCols)) {
            // 已存在栏目，查找此次删除的栏目进行删除
            List<Long> newIds = micro.getColList().stream().filter(x -> x.getId() != null).map(x -> x.getId()).collect(Collectors.toList());
            List<EduSchoolHomeMicroCol> removeCol = microCols.stream().filter(x -> !newIds.contains(x.getId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(removeCol)) {
                eduSchoolHomeMicroColService.removeByIds(removeCol.stream().map(x -> x.getId()).collect(Collectors.toList()));
            }
        }
        if (school.getSchoolType().contains("1")) {
            String regionId = AppUtil.regionUpdate(micro.getYidaAppRegionId(), micro.getName(), 3,
                    school.getYidaAppColId(),
                    AppUtil.REGION_TYPE_INFO, contenIds, yidaApp);
            micro.setYidaAppRegionId(regionId);
        }
        saveOrUpdate(micro);
    }

    @Override
    public EduSchoolHomeMicro getInfo(Long schoolId) {
        return baseMapper.getInfo(schoolId);
    }

    @Override
    public void initMicro(Long schoolId) {
        EduSchoolHomeMicro micro = new EduSchoolHomeMicro();
        micro.setName("微官网");
        micro.setSchoolId(schoolId);
        save(micro);
        EduSchoolHomeMicroCol info = new EduSchoolHomeMicroCol();
        info.setType(0);
        info.setName("学校概况");
        info.setSort(0);
        info.setIsShow(0);
        info.setSchoolId(schoolId);
        EduSchoolHomeMicroCol school = new EduSchoolHomeMicroCol();
        school.setType(1);
        school.setName("校园活动");
        school.setSort(1);
        school.setIsShow(0);
        school.setSchoolId(schoolId);
        EduSchoolHomeMicroCol teacher = new EduSchoolHomeMicroCol();
        teacher.setType(2);
        teacher.setName("教师风采");
        teacher.setSort(2);
        teacher.setIsShow(0);
        teacher.setSchoolId(schoolId);
        List list = new ArrayList();
        list.add(info);
        list.add(school);
        list.add(teacher);
        eduSchoolHomeMicroColService.saveBatch(list);
    }
}
