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

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qmth.teachcloud.common.base.BaseEntity;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicSchool;
import com.qmth.teachcloud.common.entity.SysOrg;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.OrgTypeEnum;
import com.qmth.teachcloud.common.service.BasicSchoolService;
import com.qmth.teachcloud.common.service.CallApiOrgCenterService;
import com.qmth.teachcloud.common.service.OrgCenterDataDisposeService;
import com.qmth.teachcloud.common.service.SysOrgService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 机构数据中心数据处理服务实现类
 * @Author: CaoZixuan
 * @Date: 2021-04-02
 */
@Service
public class OrgCenterDataDisposeServiceImpl implements OrgCenterDataDisposeService {
    @Resource
    private CallApiOrgCenterService callApiOrgCenterService;
    @Resource
    private BasicSchoolService basicSchoolService;
    @Resource
    private SysOrgService sysOrgService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSchoolInfo() throws IOException {
        List<Map> result = callApiOrgCenterService.callOrgInfo();
        if (Objects.isNull(result) || result.size() == 0) {
            return;
        }
        // 禁用原有学校
        List<BasicSchool> basicSchoolList = basicSchoolService.list();
        basicSchoolService.update(new UpdateWrapper<BasicSchool>().lambda().set(BasicSchool::getEnable, false).gt(BasicSchool::getId, 0));

        // 禁用原有顶级机构（学校）
        List<SysOrg> sysOrgList = sysOrgService.list();
        sysOrgService.update(new UpdateWrapper<SysOrg>().lambda().set(SysOrg::getEnable, false).eq(SysOrg::getType, OrgTypeEnum.SCHOOL));

        // 要更改的学校数据
        List<BasicSchool> updateSchoolList = new ArrayList<>();
        // 要更改的机构数据
        List<SysOrg> updateSysOrgList = new ArrayList<>();

        for (Map map : result) {
            Long orgCenterAppSchoolId = SystemConstant.convertIdToLong(String.valueOf(map.get("id"))); // 机构中心的id
            String code = String.valueOf(map.get("code"));
            String name = String.valueOf(map.get("name"));
            String logo = String.valueOf(map.get("logo"));
            String accessKey = String.valueOf(map.get("accessKey"));
            String accessSecret = String.valueOf(map.get("accessSecret"));
//            Map typeMap = JSONObject.parseObject(String.valueOf(map.get("type")));
//            String typeCode = String.valueOf(typeMap.get("code"));
//            String typeName = String.valueOf(typeMap.get("name"));

            List<BasicSchool> oldSchoolList = basicSchoolList.stream().filter(e -> e.getCode().equals(code)).collect(Collectors.toList());
            if (oldSchoolList.size() > 1) {
                throw ExceptionResultEnum.ERROR.exception("学校信息异常");
            }
            Long schoolId;
            if (oldSchoolList.size() > 0) {
                // 系统中原先就有该学校 -》 更新
                BasicSchool oldSchool = oldSchoolList.get(0);
                schoolId = oldSchool.getId();
            } else {
                // 系统中没有该学校 -》 新增 (优先使用机构中心id如果该id在系统中已经被占用则会使用分布式id)
                if (basicSchoolList.stream().map(BaseEntity::getId).collect(Collectors.toSet()).contains(orgCenterAppSchoolId)) {
                    schoolId = SystemConstant.getDbUuid();
                } else {
                    schoolId = orgCenterAppSchoolId;
                }
            }
            // 断言schoolId非空
            if (!SystemConstant.longNotNull(schoolId)) {
                throw ExceptionResultEnum.ERROR.exception();
            }

            // 基础学校数据处理
            BasicSchool school = new BasicSchool();
            school.setId(schoolId);
            school.setCode(code);
            school.setName(name);
            school.setEnable(true);
            school.setAccessKey(accessKey);
            school.setAccessSecret(accessSecret);
            school.setLogo(logo);
            updateSchoolList.add(school);

            // 学校机构处理
            List<SysOrg> schoolOrgList = sysOrgList.stream().filter(e -> schoolId.equals(e.getSchoolId()) && OrgTypeEnum.SCHOOL.equals(e.getType())).collect(Collectors.toList());
            SysOrg sysOrg = new SysOrg();
            if (schoolOrgList.size() == 0) {
                // 机构表没有该学校作为的顶级机构 -》 新增机构并把该学校所属的学院级机构挂在该学校下
                Long id = SystemConstant.getDbUuid();
                sysOrg.setId(id);
                sysOrg.setSchoolId(schoolId);
                sysOrg.setType(OrgTypeEnum.SCHOOL);
                sysOrg.setName(name);
                sysOrg.setEnable(true);

                // 处理该学校下的学院级机构的指向关系
                List<SysOrg> collegeOrgList = sysOrgList.stream()
                        .filter(e -> schoolId.equals(e.getSchoolId()) &&
                                (OrgTypeEnum.COLLEGE.equals(e.getType()) || OrgTypeEnum.PRINTING_HOUSE.equals(e.getType()) || !SystemConstant.longNotNull(e.getParentId())))
                        .peek(e -> e.setParentId(id))
                        .collect(Collectors.toList());
                updateSysOrgList.addAll(collegeOrgList);
            } else if (schoolOrgList.size() == 1) {
                // 机构表有该学校作为的顶级机构 -》 启用
                sysOrg = schoolOrgList.get(0);
                sysOrg.setEnable(true);
                sysOrg.setName(name);
            } else {
                throw ExceptionResultEnum.ERROR.exception("机构数据异常 - 存在多条数据");
            }
            updateSysOrgList.add(sysOrg);
        }
        basicSchoolService.saveOrUpdateBatch(updateSchoolList);
        sysOrgService.saveOrUpdateBatch(updateSysOrgList);

        // 权限表未匹配到的学校权限新增
//        Set<Long> schoolIdSet = basicSchoolService.list().stream().map(BaseEntity::getId).collect(Collectors.toSet());
//        teachcloudCommonService.addSchoolPrivilege(schoolIdSet);
    }
}
