package com.zhongshu.card.server.core.service.school;

import com.google.common.collect.Lists;
import com.zhongshu.card.client.model.base.IDsParam;
import com.zhongshu.card.client.model.org.OidAboutInfo;
import com.zhongshu.card.client.model.school.AreaModel;
import com.zhongshu.card.client.model.school.AreaParam;
import com.zhongshu.card.client.model.school.AreaSimpleModel;
import com.zhongshu.card.client.model.school.DictInfoParam;
import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.zhongshu.card.client.service.school.AreaService;
import com.zhongshu.card.client.utils.ITree;
import com.zhongshu.card.client.utils.TreeUtil;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.server.core.dao.school.AreaDao;
import com.zhongshu.card.server.core.dao.school.DictInfoDao;
import com.zhongshu.card.server.core.domain.school.Area;
import com.zhongshu.card.server.core.domain.school.DictInfo;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.orgManager.OrganizationManagerServiceImpl;
import com.zhongshu.card.server.core.util.BeanUtils;
import com.zhongshu.card.server.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author TRX
 * @date 2024/6/3
 */
@Slf4j
@Service
public class AreaServiceImpl extends SuperService implements AreaService {

    @Autowired
    AreaDao areaDao;

    @Autowired
    DictInfoDao dictInfoDao;

    @Autowired
    OrganizationManagerServiceImpl organizationManagerService;

    /**
     * 添加院级
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent<Area> addArea(AreaParam param) {
        initDefaultUserAndOidNoExcept(param);

        if (CommonUtil.longIsEmpty(param.getSort())) {
            param.setSort(1L);
        }
        if (StringUtils.isEmpty(param.getParentId())) {
            param.setParentId(ITree.ROOT_ID);
        }
        if (!param.getParentId().equals(ITree.ROOT_ID)) {
            Area temp = areaDao.findTopById(param.getParentId());
            if (ObjectUtils.isEmpty(temp)) {
                return ResultContent.buildFail(String.format("上级数据ID不存在：%s", param.getParentId()));
            }
        }
        if (StringUtils.isNotEmpty(param.getId()) && param.getId().equals(param.getParentId())) {
            return ResultContent.buildFail("parentId不能为当前节点");
        }

        if (param.getState() == null) {
            param.setState(DataState.Enable);
        }
        Area entity = null;
        if (StringUtils.isNotEmpty(param.getId())) {
            entity = areaDao.findTopById(param.getId());
            if (ObjectUtils.isEmpty(entity)) {
                return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
            }
            if (StringUtils.isNotEmpty(param.getCode())) {
                entity = areaDao.findTopByCodeAndOid(param.getCode(), param.getOid());
                if (ObjectUtils.isNotEmpty(entity) && !entity.getId().equals(param.getId())) {
                    return ResultContent.buildFail(String.format("%s code已存在", param.getCode()));
                }
            }
        } else {
            if (StringUtils.isNotEmpty(param.getCode())) {
                entity = areaDao.findTopByCodeAndOid(param.getCode(), entity.getOid());
                if (ObjectUtils.isNotEmpty(entity)) {
                    return ResultContent.buildFail(String.format("%s code已存在", param.getCode()));
                }
            }
            entity = new Area();
        }
        BeanUtils.copyProperties(param, entity);
        DictInfo dictInfo = null;
        if (StringUtils.isNotEmpty(param.getDictInfoId())) {
            dictInfo = dictInfoDao.findTopById(param.getDictInfoId());
        }
        entity.setDictInfo(dictInfo);

        OidAboutInfo oidAboutInfo = organizationManagerService.getOidAboutInfo(param.getOid());
        entity.setProjectOid(oidAboutInfo.getProjectOid());
        entity.setAboutOid(oidAboutInfo.getOid());
        entity.setAboutAuthType(oidAboutInfo.getAuthType());

        areaDao.save(entity);
        return ResultContent.buildSuccess(entity);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public ResultContent deleteArea(String id) {
        String oid = getCurrentOid();
        Area entity = areaDao.findTopById(id);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        List<Area> childrens = areaDao.findByParentIdAndOid(id, oid);
        if (ObjectUtils.isNotEmpty(childrens)) {
            return ResultContent.buildFail(String.format("%s 有下级数据，不能删除", entity.getName()));
        }
        areaDao.delete(entity);
        return ResultContent.buildSuccess();
    }

    /**
     * 删除多个
     *
     * @param param
     * @return
     */
    public ResultContent deleteAreas(IDsParam param) {
        if (ObjectUtils.isEmpty(param.getIds())) {
            return ResultContent.buildFail("ids不能为空");
        }
        areaDao.deleteAllById(param.getIds());
//        for (String id : param.getIds()) {
//            ResultContent resultContent = deleteArea(id);
//            if (resultContent.isFailed()) {
//                return resultContent;
//            }
//        }
        return ResultContent.buildSuccess();
    }

    /**
     * 得到所有信息 (树形结构)
     *
     * @param oid
     * @return
     */
    @Override
    public ResultContent<List<ITree>> getAreaTree(String oid) {
        if (StringUtils.isEmpty(oid)) {
            oid = getCurrentOid();
        }
        List<Area> list = areaDao.findByOidOrderBySortAsc(oid);
        List<ITree> models = list.stream().map(this::toModel).collect(Collectors.toList());
        List<ITree> iTrees = TreeUtil.buildTree(models, ITree.ROOT_ID);
        return ResultContent.buildSuccess(iTrees);
    }

    /**
     * 加载当前区域的所有上级区域（包括自己）
     *
     * @param id
     * @return
     */
    public List<AreaSimpleModel> getParents(String id) {
        List<Area> list = new ArrayList<>();
        loopLoad(id, list);
        List<AreaSimpleModel> models = list.stream().map(this::toSimpleModel).collect(Collectors.toList());
        return models;
    }

    public List<AreaSimpleModel> getParents(Area area) {
        if (ObjectUtils.isNotEmpty(area)) {
            return getParents(area.getId());
        }
        return Lists.newArrayList();
    }

    /**
     * 得到所有上级数据ID包括自己的
     *
     * @param id
     * @return
     */
    public List<String> getAllParents(String id) {
        List<Area> list = new ArrayList<>();
        loopLoad(id, list);
        List<String> strings = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(list)) {
            Collections.reverse(list);
            strings = list.stream().map(it -> it.getId()).collect(Collectors.toList());
        }
        return strings;
    }

    private void loopLoad(String id, List<Area> list) {
        Area area = areaDao.findTopById(id);
        if (ObjectUtils.isNotEmpty(area)) {
            list.add(area);
            if (StringUtils.isNotEmpty(area.getParentId()) && !area.getParentId().equals(ITree.ROOT_ID)) {
                loopLoad(area.getParentId(), list);
            }
        }
    }

    public AreaModel toModel(Area entity) {
        AreaModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new AreaModel();
            BeanUtils.copyProperties(entity, model);
            DictInfo dictInfo = entity.getDictInfo();
            if (dictInfo != null) {
                DictInfoParam param = new DictInfoParam();
                BeanUtils.copyProperties(dictInfo, param);
                model.setDictInfo(param);
            }
        }
        return model;
    }

    public AreaSimpleModel toSimpleModel(Area entity) {
        AreaSimpleModel model = new AreaSimpleModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }

}
