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

import com.github.microservice.auth.client.constant.AuthConstant;
import com.github.microservice.auth.client.content.ResultState;
import com.github.microservice.auth.client.model.RoleGroupModel;
import com.github.microservice.auth.client.model.RoleModel;
import com.github.microservice.auth.client.model.UserAuthModel;
import com.github.microservice.auth.client.model.UserModel;
import com.github.microservice.auth.client.service.OrganizationUserService;
import com.github.microservice.auth.client.service.RoleService;
import com.github.microservice.auth.client.service.UserService;
import com.github.microservice.auth.client.type.LoginType;
import com.github.microservice.auth.security.helper.AuthHelper;
import com.github.microservice.auth.security.type.AuthType;
import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.github.microservice.netdisk.client.service.NetDiskAccountService;
import com.zhongshu.card.client.model.org.*;
import com.zhongshu.card.client.model.project.ProjectSaveParam;
import com.zhongshu.card.client.service.org.OrganizationService;
import com.zhongshu.card.client.type.*;
import com.zhongshu.card.client.utils.DateUtils;
import com.zhongshu.card.server.core.dao.org.*;
import com.zhongshu.card.server.core.dataConfig.CardSystemDefault;
import com.zhongshu.card.server.core.domain.org.*;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.devices.ProjectSyncIotCenterService;
import com.zhongshu.card.server.core.service.orgManager.OrganizationManagerServiceImpl;
import com.zhongshu.card.server.core.service.orgManager.ProjectBindOrgServiceImpl;
import com.zhongshu.card.server.core.service.projectAbout.ProjectCommonConfigService;
import com.zhongshu.card.server.core.service.projectAbout.ProjectIotInfoService;
import com.zhongshu.card.server.core.service.projectAbout.ProjectWeChatInfoService;
import com.zhongshu.card.server.core.service.user.DepartmentServiceImpl;
import com.zhongshu.card.server.core.service.user.RoleServiceImpl;
import com.zhongshu.card.server.core.service.user.UserAccountServiceImpl;
import com.zhongshu.card.server.core.util.BeanUtils;
import com.zhongshu.card.server.core.util.NextNoUtil;
import com.zhongshu.card.server.core.util.ValidateResult;
import com.zhongshu.card.server.core.util.ValidateUtils;
import com.zhongshu.opengateway.client.service.SignService;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

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

/**
 * 机构管理
 *
 * @author TRX
 * @date 2024/5/31
 */
@Slf4j
@Service
public class OrganizationServiceImpl extends SuperService implements OrganizationService {

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private com.github.microservice.auth.client.service.OrganizationService organizationService;

    @Autowired
    private OrganizationUserService organizationUserService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserCountDao userCountDao;

    @Autowired
    private UserAccountServiceImpl userAccountService;

    @Autowired
    private OrganizationUserDao organizationUserDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private DepartmentServiceImpl departmentService;

    @Autowired
    private AuthHelper authHelper;

    @Autowired
    private RegionDao regionDao;

    @Autowired
    private OrganizationRelationDao organizationRelationDao;

    @Autowired
    private ProjectSyncIotCenterService projectSyncIotCenterService;

    @Autowired
    private OrganizationUserServiceImpl organizationUserServiceImpl;

    @Autowired
    private RoleServiceImpl roleServiceImpl;

    @Autowired
    private ProjectIotInfoService projectIotInfoService;

    @Autowired
    private ProjectWeChatInfoService projectWeChatInfoService;

    @Autowired
    private ProjectCommonConfigService projectCommonConfigService;

    @Autowired
    private OrganizationManagerServiceImpl organizationManagerService;

    @Autowired
    private ProjectBindOrgServiceImpl projectBindOrgServiceImpl;

    @Autowired
    private SignService signService;

    @Autowired
    private NetDiskAccountService netDiskAccountService;

    /**
     * 保存项目信息
     *
     * @param param
     * @return
     */
    @Transactional
    public ResultContent saveProjectInfo(ProjectSaveParam param) {
        AuthType authType = param.getAuthType();
        String code = param.getCode();
        if (StringUtils.isEmpty(code)) {
            code = NextNoUtil.getNextNo(authType.getCode().toUpperCase());
            param.setCode(code);
        }
        String name = param.getName();
        if (ObjectUtils.isEmpty(param.getManagerUserIds())) {
            return ResultContent.buildFail("项目负责人不能为空");
        }
        String currentOid = getCurrentOid();
        // 管理员
        List<UserAccount> userAccounts = userAccountService.getUserAccounts(param.getManagerUserIds());
        if (userAccounts.size() != param.getManagerUserIds().size()) {
            return ResultContent.buildFail("managerUserIds错误");
        }
        Organization organization = null;
        Organization nameOrganization = organizationDao.findTopByNameAndAuthType(name, authType);
        if (StringUtils.isNotEmpty(param.getId())) {
            // 编辑
            organization = organizationDao.findTopById(param.getId());
            if (ObjectUtils.isEmpty(organization)) {
                return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
            }
            if (ObjectUtils.isNotEmpty(nameOrganization) && !nameOrganization.getId().equals(organization.getId())) {
                return ResultContent.buildFail(String.format(ResultMessage.NAME_EXIST, param.getName()));
            }
            // 项目修改更新特定的字段
            organization.setName(param.getName());
            organization.setDataAuthType(param.getDataAuthType());
            organization.setState(param.getState());
            organization.setManagerUserIds(param.getManagerUserIds());
            organization.setRemark(param.getRemark());

            initUpdateEntity(organization);
            if (StringUtils.isEmpty(organization.getProjectOid())) {
                organization.setProjectOid(organization.getOid());
            }
            organizationDao.save(organization);
            // 编辑权限中心的机构信息
            authCenterUpdateOrgInfo(organization.getProjectOid(), organization.getName(), organization.getAuthType(), organization.getRemark());
        } else {
            if (ObjectUtils.isNotEmpty(nameOrganization)) {
                return ResultContent.buildFail(String.format(ResultMessage.NAME_EXIST, param.getName()));
            }
            // 初始权限中心的项目（机构）信息
            ResultContent<String> initOrgContent = authCenterAddOrgInfo(name, authType, param.getRemark());
            if (initOrgContent.isFailed()) {
                return ResultContent.buildFail(initOrgContent.getMsg());
            }
            String oid = initOrgContent.getContent();
            organization = new Organization();
            BeanUtils.copyProperties(param, organization);
            initEntityNoCheckOid(organization);

            organization.setOid(oid);
            organization.setProjectOid(oid);
            organization.setAboutOid(currentOid);
            organization.setCreateUserId(getCurrentUserId());
            organizationDao.save(organization);
        }
        // 初始项目的默认管理员角色
        roleServiceImpl.initOrgManagerRole(organization);

        //todo  同步名称至openApi网关
        signService.syncBusinessName(organization.getOid(), organization.getName());

        // 把管理员用户加入到项目中
        organizationUserServiceImpl.orgBindManager(organization, userAccounts);

        // 创建项目的文件中心账号
        com.github.microservice.netdisk.client.content.ResultContent<String> resultContent = netDiskAccountService.create(organization.getOid());
        log.info("创建文件账号： {}", resultContent.getState());
        return ResultContent.buildSuccess();
    }

    /**
     * 当前用户能查看 项目分页数据
     *
     * @param param
     * @param pageable
     * @return
     */
    @Override
    public ResultContent<Page<ProjectOrgModel>> pageProject(OrganizationSearchParam param, Pageable pageable) {
        initSearchParam(param);
        String userId = getCurrentUserId();
        Boolean isSuperAdmin = roleServiceImpl.isSuperAdmin(userId);
        if (isSuperAdmin == null || !isSuperAdmin) {
            // 不是平台管理员，只能查看自己为项目负责人的数据
            param.setManagerUserId(userId);
        }
        Page<Organization> page = organizationDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toProjectModel));
    }

    //------------------------------------------------------------------------------------

    /**
     * 权限中心添加结构信息
     *
     * @param name
     * @param authType
     * @param remark
     * @return
     */
    public ResultContent<String> authCenterAddOrgInfo(String name, AuthType authType, String remark) {
        String oid = "";
        com.github.microservice.auth.client.model.OrganizationModel organizationModel = new com.github.microservice.auth.client.model.OrganizationModel();
        organizationModel.setName(name);
        organizationModel.setAuthType(authType);
        organizationModel.setRemark(remark);
        com.github.microservice.auth.client.content.ResultContent<String> resultContent = organizationService.add(organizationModel);
        if (resultContent.getState() == ResultState.Success) {
            log.info("机构添加： {}", resultContent.getContent());
            oid = resultContent.getContent();
        } else {
            String msg = resultContent.getMsg();
            if (StringUtils.isEmpty(msg) && resultContent.getException() != null) {
                msg = resultContent.getException().getMessage();
            }
            log.info("authCenterAddOrgInfo {}", msg);
            return ResultContent.buildFail(msg);
        }
        return ResultContent.buildSuccess(oid);
    }

    public ResultContent<String> authCenterUpdateOrgInfo(String id, String name, AuthType authType, String remark) {
        String oid = "";
        com.github.microservice.auth.client.model.OrganizationModel organizationModel = new com.github.microservice.auth.client.model.OrganizationModel();
        organizationModel.setName(name);
        organizationModel.setAuthType(authType);
        organizationModel.setRemark(remark);
        organizationModel.setId(id);
        com.github.microservice.auth.client.content.ResultContent<String> resultContent = organizationService.update(organizationModel);
        if (resultContent.getState() == ResultState.Success) {
            log.info("机构编辑成功： {}", resultContent.getContent());
            oid = resultContent.getContent();
        } else {
            String msg = resultContent.getMsg();
            if (StringUtils.isEmpty(msg) && resultContent.getException() != null) {
                msg = resultContent.getException().getMessage();
            }
            log.info("authCenterUpdateOrgInfo error: {}", msg);
            return ResultContent.buildFail(msg);
        }
        return ResultContent.buildSuccess(oid);
    }

    /**
     * 添加机构 （只是添加、没得编辑）
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent<Organization> addOrganization(OrganizationAddParam param) {
        if (StringUtils.isNotEmpty(param.getPassword())) {
            // 验证密码是否符合格式
            ValidateResult validateResult = ValidateUtils.validatePassWord(param.getPassword());
            if (!validateResult.isSuccess()) {
                return ResultContent.buildFail(validateResult.getMsg());
            }
        }
        param.setId(null);
        // 验证数据
        Organization temp = organizationDao.findTopByName(param.getName());
        if (ObjectUtils.isNotEmpty(temp)) {
            return ResultContent.buildFail(String.format(ResultMessage.NAME_EXIST, param.getName()));
        }
        AuthType authType = param.getAuthType();
        if (authType == AuthType.Platform) {
            return ResultContent.buildFail("机构类型错误");
        }
        String contactPhone = param.getContactPhone();
        List<AuthType> authTypes = List.of(AuthType.School, AuthType.BusinessMain, AuthType.Enterprise);
        if (authTypes.contains(authType)) {
            Assert.hasText(contactPhone, "contactPhone 不能为空");
        }

        String code = param.getCode();
        if (StringUtils.isEmpty(code)) {
            code = NextNoUtil.getNextNo(authType.getCode().toUpperCase());
        }
        temp = organizationDao.findTopByCode(code);
        if (ObjectUtils.isNotEmpty(temp)) {
            return ResultContent.buildFail(String.format("编码已存在，请重新再试：%s", code));
        }
        param.setCode(code);

        String oid = "";
        com.github.microservice.auth.client.model.OrganizationModel organizationModel = new com.github.microservice.auth.client.model.OrganizationModel();
        organizationModel.setName(param.getName());
        organizationModel.setAuthType(authType);
        organizationModel.setRemark(param.getRemark());
        com.github.microservice.auth.client.content.ResultContent<String> resultContent = organizationService.add(organizationModel);

        if (resultContent.getState() == ResultState.Success) {
            log.info("平台初始成功： {}", resultContent.getContent());
            oid = resultContent.getContent();
        } else {
            String msg = resultContent.getMsg();
            if (StringUtils.isEmpty(msg) && resultContent.getException() != null) {
                msg = resultContent.getException().getMessage();
            }
            log.info("initSuperOrganization {}", msg);
            return ResultContent.buildFail(msg);
        }

        Organization organization = new Organization();
        BeanUtils.copyProperties(param, organization);
        organization.setOid(oid);
        organization.setCreateUserId(getCurrentUserId());
        organizationDao.save(organization);

        // 不为项目的时候，要初始数据
        if (authType != AuthType.Project) {
            // 初始机构数据
            initOrganization(organization, param.getPassword());
        }

        // 同步项目信息
        if (authType == AuthType.Project) {
            projectSyncIotCenterService.noticeSyncProject(organization);
        }

        return ResultContent.buildSuccess(organization);
    }

    /**
     * 编辑项目
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent updateProject(ProjectUpdateParam param) {
        Assert.hasText(param.getId(), "id不能为空");
        Assert.hasText(param.getName(), "name不能为空");
        Organization organization = organizationDao.findTopById(param.getId());
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
        }
        Organization tempOrganization = organizationDao.findTopByName(param.getName());
        if (ObjectUtils.isNotEmpty(tempOrganization) && !ObjectUtils.equals(organization.getId(), tempOrganization.getId())) {
            return ResultContent.buildFail(String.format(ResultMessage.NAME_EXIST, param.getName()));
        }
        BeanUtils.copyProperties(param, organization);
        organizationDao.save(organization);
        if (organization.getAuthType() == AuthType.Project) {
            projectSyncIotCenterService.noticeSyncProject(organization);
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 添加学校
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent addSchool(SchoolAddParam param) {
        Assert.hasText(param.getProjectOid(), "projectId 项目ID不能为空");
        Assert.hasText(param.getPassword(), "密码不能为空");
        Assert.hasText(param.getContactPhone(), "手机号不能为空");

        String projectId = param.getProjectOid();
        Organization organization = organizationDao.findTopByOid(projectId);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildSuccess(String.format("项目不存在：%s", projectId));
        }

        OrganizationAddParam addParam = new SchoolAddParam();
        BeanUtils.copyProperties(param, addParam);
        ResultContent<Organization> resultContent = addOrganization(addParam);
        if (resultContent.isSuccess()) {
            Organization main = resultContent.getContent();
            OrganizationRelation organizationRelation = organizationRelationDao.findTopByMainOrganizationAndRelationType(main, OrganizationRelationType.SchoolToProject);
            if (ObjectUtils.isEmpty(organizationRelation)) {
                organizationRelation = new OrganizationRelation();
            }
            organizationRelation.setAuthType(AuthType.School);
            organizationRelation.setMainOrganization(main);
            organizationRelation.setMainName(main.getName());
            organizationRelation.setRelOrganization(organization);
            organizationRelation.setRelName(organization.getName());
            organizationRelation.setRelationType(OrganizationRelationType.SchoolToProject);
            organizationRelationDao.save(organizationRelation);
        } else {
            return ResultContent.buildFail(resultContent.getMsg());
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 得到平台机构信息
     *
     * @return
     */
    @Override
    public ResultContent<OrganizationModel> getPlatformInfo() {
        Organization organization = organizationDao.findTopByAuthType(AuthType.Platform);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail("平台端未初始化，请联系管理员");
        }
        OrganizationModel model = toModel(organization);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 编辑学校
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent updateSchool(SchoolUpdateParam param) {
        Assert.hasText(param.getProjectOid(), "projectId 项目ID不能为空");
        Assert.hasText(param.getContactPhone(), "手机号不能为空");

        String projectId = param.getProjectOid();
        Organization projectOrg = organizationDao.findTopByOid(projectId);
        if (ObjectUtils.isEmpty(projectOrg)) {
            return ResultContent.buildSuccess(String.format("项目不存在：%s", projectId));
        }
        Organization schoolInfo = organizationDao.findTopById(param.getId());
        if (ObjectUtils.isEmpty(schoolInfo)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
        }
        if (param.getState() == null) {
            param.setState(OrganizationState.Normal);
        }
        BeanUtils.copyProperties(param, schoolInfo);
        organizationDao.save(schoolInfo);

        // 找出关联的项目
        OrganizationRelation organizationRelation = organizationRelationDao.findTopByMainOrganizationAndRelationType(schoolInfo, OrganizationRelationType.SchoolToProject);
        if (ObjectUtils.isEmpty(organizationRelation)) {
            organizationRelation = new OrganizationRelation();
        }
        organizationRelation.setAuthType(AuthType.School);
        organizationRelation.setMainOrganization(schoolInfo);
        organizationRelation.setMainName(schoolInfo.getName());
        organizationRelation.setRelOrganization(projectOrg);
        organizationRelation.setRelName(projectOrg.getName());
        organizationRelation.setRelationType(OrganizationRelationType.SchoolToProject);
        organizationRelationDao.save(organizationRelation);

        return ResultContent.buildSuccess();
    }

    /**
     * 得到学校绑定项目 绑定学校
     *
     * @param schoolOid
     * @return
     */
    public OrganizationRelation getSchoolRelationProject(String schoolOid) {
        Organization schoolOrg = organizationDao.findTopByOid(schoolOid);
        if (ObjectUtils.isNotEmpty(schoolOrg)) {
            OrganizationRelation organizationRelation = organizationRelationDao.findTopByMainOrganizationAndRelationType(schoolOrg, OrganizationRelationType.SchoolToProject);
            return organizationRelation;
        }
        return null;
    }

    /**
     * 编辑机构 (编辑基本信息)
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent update(OrganizationUpdateParam param) {
        Organization organization = organizationDao.findTopById(param.getId());
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
        }
        Organization temp = organizationDao.findTopByName(param.getName());
        if (ObjectUtils.isNotEmpty(temp)) {
            if (!temp.getId().equals(param.getId())) {
                return ResultContent.buildFail(String.format(ResultMessage.NAME_EXIST, param.getName()));
            }
        }

        BeanUtils.copyProperties(param, organization);
        organizationDao.save(organization);
        return ResultContent.buildSuccess();
    }

    /**
     * 删除机构
     *
     * @param oid
     * @return
     */
    @Transactional
    public ResultContent deleteOrganization(String oid) {
        Assert.hasText(oid, "oid不能为空");
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, oid));
        }
        if (organization.getAuthType() == AuthType.Platform) {
            return ResultContent.buildFail(String.format("该类型数据不能删除： %s", organization.getAuthType().getRemark()));
        }
        String currentOid = getCurrentOid();
        if (StringUtils.isNotEmpty(currentOid) && currentOid.equals(oid)) {
            return ResultContent.buildFail(String.format("不能删除当前机构"));
        }

        // 删除
        organizationDao.delete(organization);

        // 删除用户关系
        organizationUserDao.deleteByOrganization(organization);

        // 删除角色？

        // 删除部门

        return ResultContent.buildSuccess();
    }

    /**
     * 查询结构详情
     *
     * @param oid
     * @return
     */
    public ResultContent<OrganizationSimpleModel> getDetail(String oid) {
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format("机构不存在：%s", oid));
        }
        OrganizationSimpleModel model = toSimpleModel(organization);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 得到项目详情
     *
     * @param projectOid
     * @return
     */
    @Override
    public ResultContent<ProjectOrgModel> getProjectDetail(String projectOid) {
        Organization organization = organizationDao.findTopByOid(projectOid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, projectOid));
        }
        ProjectOrgModel model = toProjectModel(organization);
        return ResultContent.buildSuccess(model);
    }

    @Override
    public ResultContent deleteProject(String projectOid) {
        Organization organization = organizationDao.findTopByOid(projectOid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, projectOid));
        }

        // 判断项目是否可以删除
        long count = projectBindOrgServiceImpl.countProjectBindNumber(projectOid);
        if (count > 0) {
            return ResultContent.buildFail(String.format("%s 项目下包含机构，不能删除", organization.getName()));
        }
        // 删除项目信息
        organizationDao.delete(organization);

        // 删除项目关联的信息

        return ResultContent.buildSuccess();
    }

    /**
     * 得到学校详情
     *
     * @param schoolOid
     * @return
     */
    @Override
    public ResultContent<OrganizationModel> getSchoolDetail(String schoolOid) {
        Organization organization = organizationDao.findTopByOid(schoolOid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, schoolOid));
        }
        OrganizationModel model = toModel(organization);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 得到商户信息
     *
     * @param businessMainOid
     * @return
     */
    @Override
    public ResultContent<OrganizationModel> getBusinessMainDetail(String businessMainOid) {
        Organization organization = organizationDao.findTopByOid(businessMainOid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, businessMainOid));
        }
        OrganizationModel model = toModel(organization);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 得到学校所在的项目信息
     *
     * @param schoolOid 学校oid
     * @return
     */
    @Override
    public ResultContent<ProjectOrgModel> getSchoolProjectDetail(String schoolOid) {
        Organization schoolOrg = organizationDao.findTopByOid(schoolOid);
        if (ObjectUtils.isEmpty(schoolOrg)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, schoolOid));
        }
        ProjectOrgModel model = null;
        OrganizationRelation relation = organizationRelationDao.findTopByMainOrganizationAndRelationType(schoolOrg, OrganizationRelationType.SchoolToProject);
        if (ObjectUtils.isNotEmpty(relation)) {
            model = toProjectModel(relation.getRelOrganization());
        }
        return ResultContent.buildSuccess(model);
    }

    /**
     * 得到oid对应的关联oid信息
     *
     * @param oid
     * @return
     */
    public OidAboutInfo getOidAboutOrgInfo(String oid) {
        OidAboutInfo aboutInfo = new OidAboutInfo();
        if (StringUtils.isNotEmpty(oid)) {
            aboutInfo.setOid(oid);

            String projectOid = "";
            String schoolOid = "";
            String shopOid = "";

            Organization organization = organizationDao.findTopByOid(oid);
            if (ObjectUtils.isNotEmpty(organization)) {
                AuthType authType = organization.getAuthType();
                aboutInfo.setAuthType(authType);

                if (authType == AuthType.Project) {
                    // 如果是项目
                    projectOid = oid;
                } else if (authType == AuthType.School) {
                    // 如果是学校
                    ResultContent<ProjectOrgModel> projectContent = getSchoolProjectDetail(oid);
                    schoolOid = oid;
                    // 查询出项目的oid
                    if (projectContent.isSuccess()) {
                        projectOid = projectContent.getContent().getOid();
                    }
                } else if (authType == AuthType.BusinessMain) {
                    // 如果是商户
                    shopOid = oid;
                    // 商户绑定的学校信息
                    OrganizationRelation relation = organizationRelationDao.findTopByMainOrganizationAndRelationType(organization, OrganizationRelationType.ShopToSchool);
                    if (ObjectUtils.isNotEmpty(relation)) {
                        Organization schoolOrg = relation.getRelOrganization();
                        if (ObjectUtils.isNotEmpty(schoolOrg)) {
                            schoolOid = schoolOrg.getOid();

                            // 学校绑定的项目信息
                            ResultContent<ProjectOrgModel> projectContent = getSchoolProjectDetail(schoolOid);
                            // 查询出项目的oid
                            if (projectContent.isSuccess()) {
                                projectOid = projectContent.getContent().getOid();
                            }
                        }
                    }
                }
                aboutInfo.setProjectOid(projectOid);
                aboutInfo.setSchoolOid(schoolOid);
                aboutInfo.setShopOid(shopOid);
            } else {
                aboutInfo.setMsg("oid不属于机构信息");
            }
        } else {
            aboutInfo.setMsg("oid为空");
        }
        return aboutInfo;
    }

    /**
     * 分页数据
     *
     * @param param
     * @param pageable
     * @return
     */
    @Override
    public ResultContent<Page<OrganizationModel>> page(OrganizationSearchParam param, Pageable pageable) {
        List<Long> times = param.getTimes();
        if (ObjectUtils.isNotEmpty(times) && times.size() == 2) {
            Long startTime = times.get(0);
            startTime = DateUtils.getDayStartTime(startTime);
            Long endTime = times.get(1);
            endTime = DateUtils.getDayEndTime(endTime);
            param.setStartTime(startTime);
            param.setEndTime(endTime);
        }

        // 学校查询的特有参数
        if (param.getAuthType() == AuthType.School) {
            if (StringUtils.isNotEmpty(param.getProjectOid())) {
                // 查询项目已绑定的学校数据
                Organization organization = organizationDao.findTopByOid(param.getProjectOid());
                List<OrganizationRelation> list = organizationRelationDao.findByRelOrganizationAndRelationType(organization, OrganizationRelationType.SchoolToProject);
                if (ObjectUtils.isNotEmpty(list)) {
                    // 项目关联的信息oid
                    List<String> oids = list.stream().map(it -> {
                        return it.getMainOrganization().getOid();
                    }).collect(Collectors.toList());
                    param.setOids(oids);
                } else {
                    // 如果项目没关联学校，那就查不出来
                    List<String> oids = new ArrayList<>();
                    oids.add("UnKnow");
                    param.setOids(oids);
                }
            }
        }
        Page<Organization> page = organizationDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    /**
     * 得到可用的机构信息 （学校、商户）
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent<List<OrganizationSimpleModel>> list(OrganizationSearchParam param) {
        param.setState(OrganizationState.Normal);
        Pageable pageable = PageRequest.of(0, Integer.MAX_VALUE);
        Page<Organization> page = organizationDao.page(pageable, param);
        List<Organization> list = page.getContent();
        List<OrganizationSimpleModel> models = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(list)) {
            models = list.stream().map(this::toSimpleModel).collect(Collectors.toList());
        }
        return ResultContent.buildSuccess(models);
    }

    /**
     * 得到机构详情
     *
     * @param oid
     * @return
     */
    @Override
    public ResultContent<OrganizationModel> getOrgDetail(String oid) {
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format("oid数据不存在：%s", oid));
        }
        OrganizationModel model = toModel(organization);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 根据oid查询机构entity信息
     *
     * @param oid
     * @return
     */
    public Organization getOrgByOid(String oid) {
        Organization organization = organizationDao.findTopByOid(oid);
        return organization;
    }

    /**
     * 判断oid是否是商户
     *
     * @param oid
     * @return
     */
    public boolean oidIsBusinessMain(String oid) {
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isNotEmpty(organization) && organization.getAuthType() == AuthType.BusinessMain) {
            return true;
        }
        return false;
    }

    /**
     * 判断oid是否是学校
     *
     * @param oid
     * @return
     */
    public boolean oidIsSchool(String oid) {
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isNotEmpty(organization) && organization.getAuthType() == AuthType.School) {
            return true;
        }
        return false;
    }

    /**
     * 判断oid是否是项目
     *
     * @param oid
     * @return
     */
    public boolean oidIsProject(String oid) {
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isNotEmpty(organization) && organization.getAuthType() == AuthType.Project) {
            return true;
        }
        return false;
    }

    /**
     * 查询用户所有 指定类型 机构的数据
     *
     * @param userId
     * @return
     */
    public List<Organization> getUserAllOrgs(String userId, AuthType authType) {
        List<Organization> orgs = new ArrayList<>();
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isNotEmpty(userAccount)) {
            List<OrganizationUser> _list = organizationUserDao.findByUserAndAuthType(userAccount, authType);
            if (ObjectUtils.isNotEmpty(_list)) {
                orgs = _list.stream().map(it -> {
                    return it.getOrganization();
                }).collect(Collectors.toList());
            }
        }
        return orgs;
    }


    /**
     * 查询所有可用的项目
     *
     * @return
     */
    public ResultContent<List<OrganizationSimpleModel>> getProjectList() {
        List<Organization> list = organizationDao.findByAuthTypeAndStateOrderByCreateTimeDesc(AuthType.Project, OrganizationState.Normal);
        List<OrganizationSimpleModel> models = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(list)) {
            models = list.stream().map(this::toSimpleModel).collect(Collectors.toList());
        }
        return ResultContent.buildSuccess(models);
    }

    /**
     * 查询用户加入的机构列表
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent<List<OrganizationModel>> getUserOrgList(OrganizationUserSearch param) {
        List<OrganizationModel> models = new ArrayList<>();
        String userId = param.getUserId();
        if (StringUtils.isEmpty(userId)) {
            userId = getCurrentUserId();
        }
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        List<OrganizationUser> list = organizationUserDao.findByUserAndAuthTypeAndState(userAccount, param.getAuthType(), param.getState());
        if (ObjectUtils.isNotEmpty(list)) {
            models = list.stream().map(it -> {
                return toModel(it.getOrganization());
            }).collect(Collectors.toList());
        }
        return ResultContent.buildSuccess(models);
    }

    /**
     * 生成编码
     *
     * @param authType
     * @return
     */
    public ResultContent buildCode(AuthType authType) {
        String code = NextNoUtil.getNextNo(authType.getCode().toUpperCase());
        return ResultContent.buildSuccess(code);
    }

    /**
     * 初始平台信息
     *
     * @return
     */
    @Override
    public ResultContent initSuperOrganization() {
        String oid = "";

        AuthType authType = AuthType.Platform;
        Organization organization = organizationDao.findTopByAuthType(authType);
        if (ObjectUtils.isEmpty(organization)) {
            log.info("initSuperOrganization 开始初始平台结构信息");
            com.github.microservice.auth.client.model.OrganizationModel organizationModel = new com.github.microservice.auth.client.model.OrganizationModel();
            organizationModel.setName(CardSystemDefault.DEFAULT_PLATFORM_NAME);
            organizationModel.setAuthType(authType);
            organizationModel.setRemark("系统自动初始化");
            com.github.microservice.auth.client.content.ResultContent<String> resultContent = organizationService.add(organizationModel);

            if (resultContent.getState() == ResultState.Success) {
                log.info("平台初始成功： {}", resultContent.getContent());
                oid = resultContent.getContent();
            } else {
                String msg = resultContent.getMsg();
                if (StringUtils.isEmpty(msg) && resultContent.getException() != null) {
                    msg = resultContent.getException().getMessage();
                }
                log.info("initSuperOrganization {}", msg);
                return ResultContent.buildFail(msg);
            }

            // 保存企业信息
            organization = new Organization();
            organization.setAuthType(authType);
            organization.setOid(oid);
            organization.setName(organizationModel.getName());
            organization.setRemark(organizationModel.getRemark());
            organization.setCode("000001");
            organization.setContactPhone(CardSystemDefault.SUPER_ADMIN_NAME);
            organizationDao.save(organization);
            // 初始用户信息
            initOrganization(organization, "");
        } else {
            oid = organization.getOid();
            log.info("平台管理员账号已存在...");
        }
        netDiskAccountService.create(oid);
        return ResultContent.buildSuccess(oid);
    }

    /**
     * 初始 机构用户这些信息 （以机构联系人电话为 登录账号，创建管理员用户）
     *
     * @param organization
     * @return
     */
    public ResultContent initOrganization(Organization organization, String password) {
        String userId = "";
        // 查询用户是否存在
        com.github.microservice.auth.client.content.ResultContent<UserModel> userModelResult = userService.queryFromLoginType(LoginType.Phone, organization.getContactPhone());
        if (userModelResult.getState() != ResultState.Success) {
            //未注册
            //TODO 权限中心: 注册用户
            if (StringUtils.isEmpty(password)) {
                password = CardSystemDefault.DEFAULT_PASSWORD;
            }
            com.github.microservice.auth.client.content.ResultContent<String> addModelResult = userService.add(UserAuthModel.builder().loginType(LoginType.Phone).loginValue(organization.getContactPhone()).passWord(password).build());
            userId = addModelResult.getContent();
            log.info("初始权限中心 用户成功：{}", userId);
        } else {
            userId = userModelResult.getContent().getUserId();
        }

        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        if (userAccount == null) {
            // 初始企业中心的用户
            userAccount = userAccountService.initUserAccountOrg(userId, organization);
        }

        // 用户没在这个企业
        if (!organizationUserDao.existsByOrganizationAndUser(organization, userAccount)) {
            //本地： 绑定机构和用户的关系
            OrganizationUser organizationUser = new OrganizationUser();
            organizationUser.setCode("0000001");
            organizationUser.setUser(userAccount);
            organizationUser.setOrganization(organization);
            organizationUser.setOid(organization.getOid());
            organizationUser.setName(userAccount.getName());
            organizationUser.setPhone(userAccount.getPhone());
            organizationUser.setIsAdmin(Boolean.TRUE);
            organizationUser.setState(UserState.Normal);
            organizationUser.setUserId(userAccount.getUserId());
            organizationUser.setAuthType(organization.getAuthType());
            organizationUser.setUserType(OrganizationUserType.Manager);
            organizationUserDao.save(organizationUser);

            // 权限中心：用户和机构的关系
            com.github.microservice.auth.client.content.ResultContent<Void> resultContent = organizationUserService.update(organization.getOid(), new String[]{userId});
            if (resultContent.getState() == ResultState.Success) {
                log.info("权限中心：绑定机构和用户关系成功");
            } else {
                log.error("权限中心：绑定机构和用户关系出错：{}", resultContent.getMsg());
            }
        }
        initResource(organization, userId);
        return ResultContent.buildSuccess();
    }

    /**
     * 初始机构角色等信息 （管理员角色 并绑定到用户） 初始顶级部门信息
     *
     * @param organization
     * @param userId
     * @return
     */
    public ResultContent initResource(Organization organization, String userId) {
        UserAccount userAccount = userCountDao.findTopByUserId(userId);

        Role adminRole = roleDao.findTopByNameAndOid(CardSystemDefault.DEFAULT_ROLE_NAME, organization.getOid());
        if (ObjectUtils.isEmpty(adminRole)) {
            Set<String> auth = Set.of(AuthConstant.Admin);
            if (organization.getAuthType().equals(AuthType.Platform)) {
                auth = Set.of(AuthConstant.SuperAdmin);
            }

            String oid = organization.getOid();
            // 权限中心: 角色组
            RoleGroupModel admin = new RoleGroupModel();
            admin.setName(CardSystemDefault.DEFAULT_ROLE_NAME);
            admin.setRemark(CardSystemDefault.DEFAULT_ROLE_NAME);
            admin.setOrganizationId(oid);
            admin.setIdentity(auth);
            com.github.microservice.auth.client.content.ResultContent<String> updateRoleGroupAdmin = roleService.updateRoleGroup(admin);
            String groupId = updateRoleGroupAdmin.getContent();
            log.info("初始权限中心角色组成功：{}", groupId);

            if (!StringUtils.isEmpty(groupId)) {
                // 权限中心: 角色信息
                RoleModel roleModel = new RoleModel();
                roleModel.setOrganizationId(oid);
                roleModel.setName(CardSystemDefault.DEFAULT_ROLE_NAME);
                roleModel.setRemark(CardSystemDefault.DEFAULT_ROLE_NAME);
                roleModel.setAuth(auth);
                com.github.microservice.auth.client.content.ResultContent<String> updateRole = roleService.updateRole(roleModel);
                String roleId = updateRole.getContent();
                roleService.addRoleToRoleGroup(groupId, new String[]{roleId});
                log.info("权限中心：初始角色和角色组关系成功");

                // 添加本地角色信息
                adminRole = new Role();
                if (organization.getAuthType().equals(AuthType.Platform)) {
                    adminRole.setCode(AuthConstant.SuperAdmin);
                } else {
                    adminRole.setCode(AuthConstant.Admin);
                }
                adminRole.setAuth(auth);
                adminRole.setOid(oid);
                adminRole.setRoleGroupId(groupId);
                adminRole.setName(CardSystemDefault.DEFAULT_ROLE_NAME);
                adminRole.setRemark(CardSystemDefault.DEFAULT_ROLE_NAME);
                adminRole.setRoleType(RoleType.BuildIn);
                adminRole.setIsAdmin(Boolean.TRUE);
                adminRole.setRoleId(roleId);
                adminRole.setAuthType(organization.getAuthType());
                roleDao.save(adminRole);

                //权限中心: 将用户添加进管理员角色组
                roleService.addUserToRoleGroup(groupId, new String[]{userId});
                log.info("权限中心：绑定角色和用户关系成功");
            }
        }

        // 本地：保存用户角色信息
        if (ObjectUtils.isNotEmpty(adminRole)) {
            OrganizationUser organizationUser = organizationUserDao.findTopByOrganizationAndUser(organization, userAccount);
            organizationUser.setRoles(List.of(adminRole));
            organizationUserDao.save(organizationUser);
        }

        // 本地：初始顶级部门
        departmentService.initOrgDepartment(organization);

        log.info("-------------初始换所有成功-------------");
        return ResultContent.buildSuccess();
    }

    /**
     * @param code
     * @return
     */
    public OrganizationSimpleModel getOrgInfoByCode(String code) {
        OrganizationSimpleModel model = null;
        if (StringUtils.isNotEmpty(code)) {
            Organization organization = organizationDao.findTopByCode(code);
            if (ObjectUtils.isNotEmpty(organization)) {
                model = toSimpleModel(organization);
            }
        }
        return model;
    }

    /**
     * 根据code查询机构信息
     *
     * @param code
     * @return
     */
    public String getOrgNameByCode(String code) {
        if (StringUtils.isNotEmpty(code)) {
            Organization organization = organizationDao.findTopByCode(code);
            if (ObjectUtils.isNotEmpty(organization)) {
                return organization.getName();
            }
        }
        return "";
    }

    /**
     * 得到平台机构信息
     *
     * @return
     */
    public Organization getPlatForm() {
        return organizationDao.findTopByAuthType(AuthType.Platform);
    }

    /**
     * 得到用户加入的商户列表信息
     *
     * @param userId
     */
    public List<UserJoinBusOrgModel> getUserAboutShopList(String userId) {
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        List<OrganizationUser> list = organizationUserDao.findByUserAndAuthType(userAccount, AuthType.BusinessMain);
        List<UserJoinBusOrgModel> busOrgModels = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(list)) {
            busOrgModels = list.stream().map(it -> {
                UserJoinBusOrgModel model = new UserJoinBusOrgModel();
                Organization organization = it.getOrganization();
                model.setBusOid(organization.getOid());
                model.setBusName(organization.getName());
                model.setBusCode(organization.getCode());
                model.setBusLogo(organization.getLogo());

                String projectOid = it.getProjectOid();
                model.setProjectOid(projectOid);
                Organization projectInfo = organizationDao.findTopByOid(projectOid);
                if (ObjectUtils.isNotEmpty(projectInfo)) {
                    model.setProjectName(projectInfo.getName());
                }
                return model;
            }).collect(Collectors.toUnmodifiableList());
        }
        return busOrgModels;
    }

    public OrganizationModel toModel(Organization entity) {
        OrganizationModel model = new OrganizationModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);

            // 判断不同的类型
            if (entity.getAuthType() == AuthType.School) {
                // 学校：查询出关联的项目信息
                OrganizationRelation organization = organizationRelationDao.findTopByMainOrganizationAndRelationType(entity, OrganizationRelationType.SchoolToProject);
                if (ObjectUtils.isNotEmpty(organization)) {
                    model.setProjectModel(toSimpleModel(organization.getRelOrganization()));
                }
            }

            // 区域信息
            String adminDivisionItemCode = entity.getAdminDivisionItemCode();
            if (StringUtils.isNotEmpty(adminDivisionItemCode)) {
                List<String> codes = List.of(adminDivisionItemCode.split(","));
                List<Region> regions = regionDao.findByCodeInOrderByIndexAsc(codes);
                List<RegionModel> regionList = regions.stream().map(it -> {
                    RegionModel regionModel = new RegionModel();
                    BeanUtils.copyProperties(it, regionModel);
                    return regionModel;
                }).collect(Collectors.toList());
                model.setRegionList(regionList);
            }
        }
        return model;
    }

    /**
     * 项目的信息模型
     *
     * @param entity
     * @return
     */
    public ProjectOrgModel toProjectModel(Organization entity) {
        ProjectOrgModel model = new ProjectOrgModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);
            // 统计学校数量
            Long number = organizationRelationDao.countByRelOrganizationAndRelationType(entity, OrganizationRelationType.SchoolToProject);
            model.setSchoolNumber(number);

            model.setManagerUserList(userAccountService.toListSimpleModel(userAccountService.getUserAccounts(entity.getManagerUserIds())));

            // 在线设备数量

            // 是否完成配置
            model.setIsFinishWeChat(projectWeChatInfoService.isFinishConfig(entity.getOid()));
            model.setIsFinishIot(projectIotInfoService.isFinishConfig(entity.getOid()));
            model.setIsFinishCommon(projectCommonConfigService.isFinishConfig(entity.getOid()));
        }
        return model;
    }

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

}
