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.RoleBindAllParam;
import com.zhongshu.card.client.model.scene.RoleBindSceneParam;
import com.zhongshu.card.client.model.scene.RoleSceneInfoModel;
import com.zhongshu.card.client.model.scene.SceneInfoAboutComModel;
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.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.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 org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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;

    public ResultContent bindScene(RoleBindSceneParam param) {
        ProjectSceneInfo entity = projectSceneInfoDao.findTopById(param.getId());
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
        }
        Role role = roleDao.findTopById(param.getRoleId());
        if (ObjectUtils.isEmpty(role)) {
            return ResultContent.buildFail("角色不存在");
        }
//        RoleSceneInfo roleSceneInfo = roleSceneInfoDao.findTopByProjectSceneInfoIdAndRoleId(entity.getId(), role.getId());
//        if (ObjectUtils.isNotEmpty(roleSceneInfo)) {
//            return ResultContent.buildFail(String.format("角色已存在场景：%s", entity.getName()));
//        }
        RoleSceneInfo roleSceneInfo = buildProjectSceneInfo(entity, role);
        long index = roleSceneInfoDao.countByRoleId(role.getId());
        roleSceneInfo.setSort(index + 1);
        roleSceneInfoDao.save(roleSceneInfo);
        return ResultContent.buildSuccess();
    }

    @Transactional
    public ResultContent bindList(RoleBindAllParam param) {
        Role role = roleDao.findTopById(param.getRoleId());
        if (ObjectUtils.isEmpty(role)) {
            return ResultContent.buildFail("角色不存在");
        }
        List<RoleSceneInfo> list = new ArrayList<>();
        List<String> projectSceneInfoIds = param.getProjectSceneInfoIds();
        if (ObjectUtils.isNotEmpty(projectSceneInfoIds)) {
            long i = 1;
            for (String projectSceneInfoId : projectSceneInfoIds) {
                // 项目的场景
                ProjectSceneInfo projectSceneInfo = projectSceneInfoDao.findTopById(projectSceneInfoId);
                if (ObjectUtils.isNotEmpty(projectSceneInfo)) {
                    RoleSceneInfo roleSceneInfo = buildProjectSceneInfo(projectSceneInfo, role);
                    roleSceneInfo.setSort(i);
                    i++;
                    list.add(roleSceneInfo);
                }
            }
        }
        if (ObjectUtils.isNotEmpty(list)) {
            roleSceneInfoDao.saveAll(list);
        }
        return ResultContent.buildSuccess();
    }

    public RoleSceneInfo buildProjectSceneInfo(ProjectSceneInfo projectSceneInfo, Role role) {
        RoleSceneInfo roleSceneInfo = roleSceneInfoDao.findTopByProjectSceneInfoIdAndRoleId(projectSceneInfo.getId(), role.getId());
        if (ObjectUtils.isEmpty(roleSceneInfo)) {
            roleSceneInfo = new RoleSceneInfo();
            initEntityNoCheckOid(roleSceneInfo);
            roleSceneInfo.setSceneInfo(projectSceneInfo.getSceneInfo());
            roleSceneInfo.setSceneInfoId(projectSceneInfo.getId());
            roleSceneInfo.setProjectSceneInfo(projectSceneInfo);
            roleSceneInfo.setProjectSceneInfoId(projectSceneInfo.getId());
        } else {
            initUpdateEntity(roleSceneInfo);
        }
        roleSceneInfo.setProjectOid(projectSceneInfo.getProjectOid());
        roleSceneInfo.setRole(role);
        roleSceneInfo.setRoleId(role.getId());
        return roleSceneInfo;
    }

    /**
     * 查询角色绑定的所有的数据
     *
     * @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);
    }

    /**
     * 查询角色可用的场景
     *
     * @param roleId
     * @return
     */
    public List<SceneInfoAboutComModel> getAllEnableScenes(String roleId) {
        List<SceneInfoAboutComModel> models = new ArrayList<>();

        if (StringUtils.isNotEmpty(roleId)) {
            // 角色关联的场景数据
            List<RoleSceneInfo> list = roleSceneInfoDao.findByRoleIdOrderBySortAsc(roleId);
            if (ObjectUtils.isNotEmpty(list)) {
                list.stream().forEach(it -> {
                    SceneInfo sceneInfo = it.getSceneInfo();
                    ProjectSceneInfo projectSceneInfo = it.getProjectSceneInfo();
                    if (ObjectUtils.isNotEmpty(projectSceneInfo) && ObjectUtils.isNotEmpty(sceneInfo)) {
                        if (projectSceneInfo.getState() == DataState.Enable && sceneInfo.getState() == DataState.Enable) {
                            models.add(sceneInfoService.toAboutComModel(sceneInfo));
                        }
                    }
                });
            }
        }
        return models;
    }

    public List<SceneInfoAboutComModel> getUserAllEnableScenes() {
        // 得到当前用户所有的角色
        ResultContent<List<RoleSimpleModel>> content = roleServiceImpl.xcxGetCurrentRoles();
        if (content.isSuccess()) {
            List<RoleSimpleModel> roles = content.getContent();
            if (ObjectUtils.isNotEmpty(roles)) {
                List<SceneInfoAboutComModel> models = new ArrayList<>();

                List<String> roleIds = roles.stream().map(it -> it.getId()).collect(Collectors.toUnmodifiableList());
                List<RoleSceneInfo> list = roleSceneInfoDao.findByRoleIdInOrderBySortAsc(roleIds);
                if (ObjectUtils.isNotEmpty(list)) {
                    list.stream().forEach(it -> {
                        SceneInfo sceneInfo = it.getSceneInfo();
                        ProjectSceneInfo projectSceneInfo = it.getProjectSceneInfo();
                        if (ObjectUtils.isNotEmpty(projectSceneInfo) && ObjectUtils.isNotEmpty(sceneInfo)) {
                            if (projectSceneInfo.getState() == DataState.Enable && sceneInfo.getState() == DataState.Enable) {
                                models.add(sceneInfoService.toAboutComModel(sceneInfo));
                            }
                        }
                    });
                }
                List<SceneInfoAboutComModel> reModels = new ArrayList<>();
                HashMap<String, String> map = new HashMap<>();
                for (SceneInfoAboutComModel model : models) {
                    if(!map.containsKey(model.getId())) {
                        map.put(model.getId(), model.getName());
                        reModels.add(model);
                    }
                }
                // 去重
                return reModels;
            }
        }
        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));
    }

    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 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 (ObjectUtils.isNotEmpty(projectSceneInfoId)) {
            roleSceneInfoDao.deleteByProjectSceneInfoId(projectSceneInfoId);
        }
        return ResultContent.buildSuccess();
    }

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

    /**
     * 根据角色id删除数据
     *
     * @param roleId
     * @return
     */
    public ResultContent deleteByRoleId(String roleId) {
        if (ObjectUtils.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()));
        }
        return model;
    }

}
