package com.yunzhupaas.base.service.impl;

import com.yunzhupaas.base.model.base.SystemBaeModel;
import com.yunzhupaas.base.service.SuperServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunzhupaas.base.entity.*;
import com.yunzhupaas.base.mapper.SystemMapper;
import com.yunzhupaas.base.service.*;
import com.yunzhupaas.constant.YunzhupaasConst;
import com.yunzhupaas.constant.PermissionConst;
import com.yunzhupaas.permission.entity.OrganizeAdministratorEntity;
import com.yunzhupaas.permission.service.AuthorizeService;
import com.yunzhupaas.permission.service.OrganizeAdministratorService;
import com.yunzhupaas.permission.service.PermissionGroupService;
import com.yunzhupaas.util.RandomUtil;
import com.yunzhupaas.util.StringUtil;
import com.yunzhupaas.util.UserProvider;
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.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2023/09/27
 */
@Service
public class SystemServiceImpl extends SuperServiceImpl<SystemMapper, SystemEntity> implements SystemService {

    @Autowired
    private ModuleService moduleService;
    @Autowired
    private AuthorizeService authorizeApi;
    @Autowired
    private OrganizeAdministratorService organizeAdminTratorApi;
    @Autowired
    private PermissionGroupService permissionGroupApi;

    @Override
    public List<SystemEntity> getList() {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(SystemEntity::getSortCode)
                .orderByDesc(SystemEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<SystemEntity> getList(String keyword, Boolean filterEnableMark, boolean verifyAuth, Boolean filterMain,
            boolean isList, List<String> moduleAuthorize) {
        List<String> systemIds = new ArrayList<>();
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        // 是否为列表，特殊处理
        if (isList) {
            systemIds.addAll(authorizeApi.getAuthorizeByUser(true).getSystemList().stream().map(SystemBaeModel::getId)
                    .collect(Collectors.toList()));
        }
        if (StringUtil.isNotEmpty(keyword)) {
            queryWrapper.lambda()
                    .and(t -> t.like(SystemEntity::getFullName, keyword).or().like(SystemEntity::getEnCode, keyword)
                            .or().like(SystemEntity::getDescription, keyword));
        }
        if (filterEnableMark == null) {
            queryWrapper.lambda().eq(SystemEntity::getEnabledMark, 0);
        } else if (filterEnableMark) {
            queryWrapper.lambda().eq(SystemEntity::getEnabledMark, 1);
        }
        if (verifyAuth) {
            List<String> systemList = authorizeApi.getAuthorizeByUser(false).getSystemList()
                    .stream().map(SystemBaeModel::getId).collect(Collectors.toList());
            if (systemList.size() == 0) {
                return new ArrayList<>();
            }
            systemIds.addAll(systemList);
            queryWrapper.lambda().in(SystemEntity::getId, systemIds);
        }
        // 过滤掉开发平台
        if (filterMain != null && filterMain) {
            queryWrapper.lambda().ne(SystemEntity::getEnCode, YunzhupaasConst.MAIN_SYSTEM_CODE);
        }
        if (moduleAuthorize.size() > 0) {
            queryWrapper.lambda().notIn(SystemEntity::getId, moduleAuthorize);
        }
        queryWrapper.lambda().orderByAsc(SystemEntity::getSortCode).orderByDesc(SystemEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public SystemEntity getInfo(String id) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public Boolean isExistFullName(String id, String fullName) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getFullName, fullName);
        if (StringUtil.isNotEmpty(id)) {
            queryWrapper.lambda().ne(SystemEntity::getId, id);
        }
        return this.count(queryWrapper) > 0;
    }

    @Override
    public Boolean isExistEnCode(String id, String enCode) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getEnCode, enCode);
        if (StringUtil.isNotEmpty(id)) {
            queryWrapper.lambda().ne(SystemEntity::getId, id);
        }
        return this.count(queryWrapper) > 0;
    }

    @Override
    @Transactional
    public Boolean create(SystemEntity entity) {
        entity.setId(RandomUtil.uuId());
        entity.setIsMain(0);
        entity.setCreatorUserId(UserProvider.getUser().getUserId());
        entity.setCreatorTime(new Date());
        boolean save = this.save(entity);
        if (!UserProvider.getUser().getIsAdministrator() && save) {
            // 当前用户创建的组织要赋予权限
            OrganizeAdministratorEntity organizeAdministratorEntity = new OrganizeAdministratorEntity();
            organizeAdministratorEntity.setUserId(UserProvider.getUser().getUserId());
            organizeAdministratorEntity.setOrganizeId(entity.getId());
            organizeAdministratorEntity.setOrganizeType(PermissionConst.SYSTEM);
            organizeAdminTratorApi.save(organizeAdministratorEntity);
        }
        return save;
    }

    @Override
    @Transactional
    public Boolean update(String id, SystemEntity entity) {
        entity.setId(id);
        if (entity.getIsMain() == null) {
            entity.setIsMain(0);
        }
        entity.setLastModifyUserId(UserProvider.getUser().getUserId());
        entity.setLastModifyTime(new Date());
        return this.updateById(entity);
    }

    @Override
    @Transactional
    public Boolean delete(String id) {
        moduleService.deleteBySystemId(id);
        return this.removeById(id);
    }

    @Override
    public List<SystemEntity> getListByIds(List<String> list, List<String> moduleAuthorize) {
        List<SystemEntity> systemList = new ArrayList<>(16);
        if (list.size() > 0) {
            QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
            if (moduleAuthorize != null && moduleAuthorize.size() > 0) {
                queryWrapper.lambda().notIn(SystemEntity::getId, moduleAuthorize);
            }
            queryWrapper.lambda().in(SystemEntity::getId, list);
            queryWrapper.lambda().eq(SystemEntity::getEnabledMark, 1);
            queryWrapper.lambda().orderByAsc(SystemEntity::getSortCode).orderByDesc(SystemEntity::getCreatorTime);
            return this.list(queryWrapper);
        }
        return systemList;
    }

    @Override
    public SystemEntity getInfoByEnCode(String enCode) {
        if (StringUtil.isEmpty(enCode)) {
            return null;
        }
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemEntity::getEnCode, enCode);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<SystemEntity> findSystemAdmin(int mark, String mainSystemCode, List<String> moduleAuthorize) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        if (mark == 1) {
            queryWrapper.lambda().eq(SystemEntity::getEnabledMark, mark)
                    .ne(SystemEntity::getEnCode, mainSystemCode);
        }
        if (moduleAuthorize != null && moduleAuthorize.size() > 0) {
            queryWrapper.lambda().notIn(SystemEntity::getId, moduleAuthorize);
        }
        queryWrapper.lambda().orderByAsc(SystemEntity::getSortCode).orderByDesc(SystemEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<SystemEntity> findSystemAdmin(int mark, String mainSystemCode) {
        QueryWrapper<SystemEntity> queryWrapper = new QueryWrapper<>();
        if (mark == 1) {
            queryWrapper.lambda().eq(SystemEntity::getEnabledMark, mark)
                    .ne(SystemEntity::getEnCode, mainSystemCode);
        }
        queryWrapper.lambda().orderByAsc(SystemEntity::getSortCode).orderByDesc(SystemEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

}
