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

import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.google.common.collect.Lists;
import com.zhongshu.card.client.model.base.SortParam;
import com.zhongshu.card.client.model.org.role.RoleSimpleModel;
import com.zhongshu.card.client.model.scene.*;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.server.core.dao.org.RoleDao;
import com.zhongshu.card.server.core.dao.scene.ProjectSceneInfoDao;
import com.zhongshu.card.server.core.dao.scene.RoleSceneInfoDao;
import com.zhongshu.card.server.core.dao.scene.SceneComponentDao;
import com.zhongshu.card.server.core.dao.scene.SceneInfoDao;
import com.zhongshu.card.server.core.domain.org.Role;
import com.zhongshu.card.server.core.domain.scene.ProjectSceneInfo;
import com.zhongshu.card.server.core.domain.scene.RoleSceneInfo;
import com.zhongshu.card.server.core.domain.scene.SceneComponent;
import com.zhongshu.card.server.core.domain.scene.SceneInfo;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.user.RoleServiceImpl;
import com.zhongshu.card.server.core.util.BeanUtils;
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.*;
import java.util.stream.Collectors;

/**
 * @author TRX
 * @date 2024/11/22
 */
@Slf4j
@Service
public class RoleSceneInfoService extends SuperService {

    @Autowired
    private SceneInfoDao sceneInfoDao;

    @Autowired
    private ProjectSceneInfoDao projectSceneInfoDao;

    @Autowired
    private RoleSceneInfoDao roleSceneInfoDao;

    @Autowired
    private SceneInfoService sceneInfoService;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RoleServiceImpl roleServiceImpl;

    @Autowired
    private SceneComponentDao sceneComponentDao;

    /**
     * 绑定组件
     *
     * @param param
     * @return
     */
    public ResultContent bindScenes(RoleBindsSceneParam param) {
        List<String> ids = param.getIds();
        if (ObjectUtils.isEmpty(ids)) {
            return ResultContent.buildFail("");
        }

        Role role = roleDao.findTopById(param.getRoleId());
        if (ObjectUtils.isEmpty(role)) {
            return ResultContent.buildFail("角色不存在");
        }
        String projectOid = param.getProjectOid();
        if (StringUtils.isEmpty(projectOid)) {
            return ResultContent.buildFail("projectOid不能为空");
        }

        long i = 1;
        List<RoleSceneInfo> list = new ArrayList<>();
        for (String id : ids) {
            SceneComponent sceneComponent = sceneComponentDao.findTopById(id);
            if (ObjectUtils.isEmpty(sceneComponent)) {
                continue;
            }
            SceneInfo sceneInfo = sceneComponent.getSceneInfo();
            ProjectSceneInfo projectSceneInfo = projectSceneInfoDao.findTopBySceneInfoAndProjectOid(sceneInfo, projectOid);
            if (ObjectUtils.isEmpty(projectSceneInfo)) {
                continue;
            }

            RoleSceneInfo roleSceneInfo = roleSceneInfoDao.findTopByRoleIdAndComponentId(role.getId(), sceneComponent);
            if (ObjectUtils.isEmpty(roleSceneInfo)) {
                roleSceneInfo = new RoleSceneInfo();
                initEntityNoCheckOid(roleSceneInfo);
            }
            // 角色信息
            roleSceneInfo.setRole(role);
            roleSceneInfo.setRoleId(role.getId());
            roleSceneInfo.setProjectOid(projectOid);

            // 组件信息
            roleSceneInfo.setComponent(sceneComponent);
            roleSceneInfo.setComponentId(sceneComponent.getId());

            // 应用信息
            roleSceneInfo.setSceneInfo(sceneInfo);
            roleSceneInfo.setSceneInfoId(sceneInfo.getId());

            // 项目管理的应用
            roleSceneInfo.setProjectSceneInfo(projectSceneInfo);
            roleSceneInfo.setProjectSceneInfoId(projectSceneInfo.getId());

            roleSceneInfo.setSort(i);
            list.add(roleSceneInfo);
            i++;
        }
        roleSceneInfoDao.saveAll(list);
        return ResultContent.buildSuccess();
    }


    public ResultContent deleteById(String id) {
        RoleSceneInfo entity = roleSceneInfoDao.findTopById(id);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        // 判断是否可以删除
        roleSceneInfoDao.delete(entity);
        // 删除关联的信息
        return ResultContent.buildSuccess();
    }

    /**
     * 查询角色绑定的所有的数据
     *
     * @param roleId
     * @return
     */
    public ResultContent<List<RoleSceneInfoModel>> list(String roleId) {
        List<RoleSceneInfoModel> models = new ArrayList<>();
        List<RoleSceneInfo> list = roleSceneInfoDao.findByRoleIdOrderBySortAsc(roleId);
        if (ObjectUtils.isNotEmpty(list)) {
            models = list.stream().map(this::toModel).collect(Collectors.toUnmodifiableList());
        }
        return ResultContent.buildSuccess(models);
    }

    public ResultContent<List<RoleSceneComTreeModel>> tree(List<String> roleIds, DataState state) {
        List<RoleSceneComTreeModel> models = new ArrayList<>();
        List<RoleSceneInfo> list = roleSceneInfoDao.findByRoleIdInOrderBySortAsc(roleIds);
        if (ObjectUtils.isNotEmpty(list)) {
            if (state != null) {
                list = list.stream().filter(it -> {
                    return it.getProjectSceneInfo().getState() == state && it.getSceneInfo().getState() == state;
                }).collect(Collectors.toList());
            }
            if (ObjectUtils.isEmpty(list)) {
                return ResultContent.buildSuccess(models);
            }

            // 以项目应用ID
            Map<String, List<RoleSceneInfo>> map = list.stream().collect(
                    Collectors.toMap(RoleSceneInfo::getProjectSceneInfoId, e -> {
                        List<RoleSceneInfo> objects = new ArrayList<>();
                        objects.add(e);
                        return objects;
                    }, (newList, oldList) -> {
                        oldList.addAll(newList);
                        return oldList;
                    }));
            for (String projectSceneInfoId : map.keySet()) {
                ProjectSceneInfo projectSceneInfo = projectSceneInfoDao.findTopById(projectSceneInfoId);
                if (ObjectUtils.isEmpty(projectSceneInfo)) {
                    continue;
                }
                RoleSceneComTreeModel model = new RoleSceneComTreeModel();
                SceneInfoModel sceneInfoModel = sceneInfoService.toModel(projectSceneInfo.getSceneInfo());
                BeanUtils.copyProperties(sceneInfoModel, model);

                model.setProjectSceneInfoId(projectSceneInfoId);
                model.setPSort(projectSceneInfo.getSort());
                model.setPState(projectSceneInfo.getState());

                // 组件信息
                List<RoleSceneInfo> roleSceneInfos = map.get(projectSceneInfoId);
                List<RoleSceneComponentModel> children = roleSceneInfos.stream().map(it -> {
                    RoleSceneComponentModel componentModel = new RoleSceneComponentModel();
                    SceneComponentModel sceneComponentModel = sceneInfoService.toComponentModel(it.getComponent());
                    BeanUtils.copyProperties(sceneComponentModel, componentModel);
                    componentModel.setRoleSceneId(it.getId());
                    componentModel.setProjectSceneInfoId(projectSceneInfoId);

                    return componentModel;
                }).collect(Collectors.toList());

                model.setChildren(children);
                models.add(model);
            }

            // 排序
            Collections.sort(models, new Comparator<RoleSceneComTreeModel>() {
                @Override
                public int compare(RoleSceneComTreeModel o1, RoleSceneComTreeModel o2) {
                    return (int) (o1.getPSort() - o2.getPSort());
                }
            });
        }
        return ResultContent.buildSuccess(models);
    }

    public ResultContent<List<RoleSceneComponentModel>> listByRoleIds(List<String> roleIds, DataState state) {
        List<RoleSceneComponentModel> list = new ArrayList<>();
        ResultContent<List<RoleSceneComTreeModel>> content = tree(roleIds, state);
        if (content.isSuccess()) {
            List<RoleSceneComTreeModel> models = content.getContent();
            if (ObjectUtils.isNotEmpty(models)) {
                models.stream().forEach(it -> {
                    list.addAll(it.getChildren());
                });
            }
        }
        return ResultContent.buildSuccess(list);
    }

    /**
     * 得到当前用户可以的 场景 组件信息
     *
     * @return
     */
    public List<RoleSceneComponentModel> getUserAllEnableScenes() {
        // 得到当前用户所有的角色
        ResultContent<List<RoleSimpleModel>> content = roleServiceImpl.xcxGetCurrentRoles();
        if (content.isSuccess()) {
            List<RoleSimpleModel> roles = content.getContent();
            if (ObjectUtils.isNotEmpty(roles)) {
                ResultContent<List<RoleSceneComponentModel>> treeContent = listByRoleIds(roles.stream().map(RoleSimpleModel::getId).collect(Collectors.toList()), DataState.Enable);
                if (treeContent.isSuccess()) {
                    return treeContent.getContent();
                }
            }
        }
        return Lists.newArrayList();
    }

    public ResultContent<RoleSceneInfoModel> getDetailById(String id) {
        RoleSceneInfo entity = roleSceneInfoDao.findTopById(id);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        return ResultContent.buildSuccess(toModel(entity));
    }

    /**
     * 数据排序
     *
     * @param param
     * @return
     */
    public ResultContent sort(SortParam param) {
        HashMap<String, Long> data = param.getData();
        if (data != null && !data.isEmpty()) {
            List<RoleSceneInfo> list = new ArrayList<>();
            data.keySet().stream().forEach(it -> {
                RoleSceneInfo entity = roleSceneInfoDao.findTopById(it);
                if (ObjectUtils.isNotEmpty(entity)) {
                    entity.setSort(data.get(it));
                    list.add(entity);
                }
            });
            if (ObjectUtils.isNotEmpty(list)) {
                roleSceneInfoDao.saveAll(list);
            }
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 根据项目的应用id删除角色的
     *
     * @param projectSceneInfoId
     * @return
     */
    public ResultContent deleteByProjectSceneId(String projectSceneInfoId) {
        if (StringUtils.isNotEmpty(projectSceneInfoId)) {
            roleSceneInfoDao.deleteByProjectSceneInfoId(projectSceneInfoId);
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 根据平台的应用id删除
     *
     * @param sceneInfoId
     * @return
     */
    public ResultContent deleteBySceneInfoId(String sceneInfoId) {
        if (StringUtils.isNotEmpty(sceneInfoId)) {
            roleSceneInfoDao.deleteBySceneInfoId(sceneInfoId);
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 根据组件ID删除
     *
     * @param componentId
     * @return
     */
    public ResultContent deleteByComponentId(String componentId) {
        if (StringUtils.isNotEmpty(componentId)) {
            roleSceneInfoDao.deleteByComponentId(componentId);
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 根据组件id集合删除
     *
     * @param componentIds
     * @return
     */
    public ResultContent deleteByComponentIds(List<String> componentIds) {
        if (ObjectUtils.isNotEmpty(componentIds)) {
            roleSceneInfoDao.deleteByComponentIdIn(componentIds);
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 根据角色id删除数据
     *
     * @param roleId
     * @return
     */
    public ResultContent deleteByRoleId(String roleId) {
        if (StringUtils.isNotEmpty(roleId)) {
            roleSceneInfoDao.deleteByRoleId(roleId);
        }
        return ResultContent.buildSuccess();
    }

    public RoleSceneInfoModel toModel(RoleSceneInfo entity) {
        RoleSceneInfoModel model = new RoleSceneInfoModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);
            // 关联的应用信息
            model.setSceneInfo(sceneInfoService.toModel(entity.getSceneInfo()));
            // 关联的组件信息
            model.setSceneComponent(sceneInfoService.toComponentModel(entity.getComponent()));
        }
        return model;
    }

}
