package com.cf.imes.module.system.service.permission;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.organ.core.aop.OrganIgnore;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.system.controller.admin.permission.vo.menu.MenuListReqVO;
import com.cf.imes.module.system.controller.admin.permission.vo.menu.MenuSaveVO;
import com.cf.imes.module.system.controller.admin.permission.vo.menu.MenuTransReqVO;
import com.cf.imes.module.system.dal.dataobject.permission.MenuDO;
import com.cf.imes.module.system.dal.dataobject.permission.MenuI18nDO;
import com.cf.imes.module.system.dal.mysql.permission.MenuMapper;
import com.cf.imes.module.system.dal.mysql.permission.MenuI18nMapper;
import com.cf.imes.module.system.dal.redis.RedisKeyConstants;
import com.cf.imes.module.system.enums.common.LanguageEnum;
import com.cf.imes.module.system.enums.permission.MenuSourceTypeEnum;
import com.cf.imes.module.system.enums.permission.MenuTypeEnum;
import com.cf.imes.module.system.framework.trans.config.TransApi;
import com.cf.imes.module.system.framework.trans.config.TransProperties;
import com.cf.imes.module.system.service.organ.OrganService;
import com.cf.imes.module.system.util.locale.LocaleUtils;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.cf.imes.framework.common.util.collection.CollectionUtils.convertList;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.*;
import static com.cf.imes.module.system.framework.executor.config.SystemThreadPoolConfiguration.SYSTEM_PERMISSION_THREAD_POOL_TASK_EXECUTOR;

/**
 * 菜单 Service 实现
 *
 * @author 晨丰科技
 */
@Service
@Slf4j
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private PermissionService permissionService;
    @Resource
    @Lazy // 延迟，避免循环依赖报错
    private OrganService organService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private MenuI18nMapper menui18nMapper;

    @Resource
    private TransProperties transProperties;

    @Resource(name = SYSTEM_PERMISSION_THREAD_POOL_TASK_EXECUTOR)
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    private static final String FIELD_CHARACTER = ":*:%s";

    @Override
    @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST, key = "#createReqVO.permission",
            condition = "#createReqVO.permission != null")
    public Long createMenu(MenuSaveVO createReqVO) {
        // 校验父菜单存在
        validateParentMenu(createReqVO.getParentId(), null);
        // 校验菜单（自己）
        validateMenu(createReqVO.getParentId(), createReqVO.getName(), null, createReqVO.getSourceType());
        // 校验管理端菜单增删改必须是晨丰组织下用户
        validateManageSourceTypeOperatePermission(createReqVO.getSourceType());

        // 插入数据库
        MenuDO menu = BeanUtils.toBean(createReqVO, MenuDO.class);
        initMenuProperty(menu);
        menuMapper.insert(menu);

        Long menuId = menu.getId();
        // 清理缓存
        flushCacheWhenOperateMenu(menuId, createReqVO.getPermission(), null);

        // 返回
        return menuId;
    }

    @Override
    @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
            allEntries = true) // allEntries 清空所有缓存，因为 permission 如果变更，涉及到新老两个 permission。直接清理，简单有效
    public void updateMenu(MenuSaveVO updateReqVO) {
        // 校验更新的菜单是否存在
        MenuDO menuDO = menuMapper.selectById(updateReqVO.getId());
        if (menuDO == null) {
            throw new ServiceException(MENU_NOT_EXISTS);
        }
        // 校验父菜单存在
        validateParentMenu(updateReqVO.getParentId(), updateReqVO.getId());
        // 校验菜单（自己）
        validateMenu(updateReqVO.getParentId(), updateReqVO.getName(), updateReqVO.getId(), updateReqVO.getSourceType());
        // 校验管理端菜单增删改必须是晨丰组织下用户
        validateManageSourceTypeOperatePermission(updateReqVO.getSourceType());

        // 更新到数据库
        MenuDO updateObj = BeanUtils.toBean(updateReqVO, MenuDO.class);
        initMenuProperty(updateObj);
        menuMapper.updateById(updateObj);

        // 权限串发生改变清空缓存
        String oldPermission = menuDO.getPermission();
        String newPermission = updateReqVO.getPermission();
        if (ObjectUtil.notEqual(oldPermission, newPermission)) {
            flushCacheWhenOperateMenu(menuDO.getId(), newPermission, oldPermission);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
            allEntries = true) // allEntries 清空所有缓存，因为此时不知道 id 对应的 permission 是多少。直接清理，简单有效
    public void deleteMenu(Long id) {
        // 校验是否还有子菜单
        if (menuMapper.selectCountByParentId(id) > 0) {
            throw new ServiceException(MENU_EXISTS_CHILDREN);
        }
        // 校验删除的菜单是否存在
        MenuDO menuDO = menuMapper.selectById(id);
        if (menuDO == null) {
            throw new ServiceException(MENU_NOT_EXISTS);
        }
        // 校验管理端菜单增删改必须是晨丰组织下用户
        validateManageSourceTypeOperatePermission(menuDO.getSourceType());
        // 标记删除
        menuMapper.deleteById(id);
        // 删除授予给角色的权限
        permissionService.processMenuDeleted(id);

        // 清理缓存
        flushCacheWhenOperateMenu(id, null, menuDO.getPermission());
    }

    /**
     * 校验管理端菜单增删改必须是晨丰组织下用户
     *
     * @param sourceType
     */
    private void validateManageSourceTypeOperatePermission(Integer sourceType) {
        if (!SecurityFrameworkUtils.isCfOrg() && MenuSourceTypeEnum.MANAGEMENT.getType().equals(sourceType)) {
            throw new ServiceException(MANAGEMENT_MENU_OPERATION_PERMISSION_ERROR);
        }
    }

    /**
     * 菜单增删改时清理缓存
     *
     * @param menuId        菜单id
     * @param newPermission 新权限串
     * @param oldPermission 旧权限串
     */
    private void flushCacheWhenOperateMenu(Long menuId, String newPermission, String oldPermission) {
        CompletableFuture.runAsync(() -> {
            try {
                if (ObjectUtil.isNotNull(oldPermission)) {
                    // 移除 USER_ROLE_ID_LIST:*:旧的permission
                    String oldMenuPerPattern = String.format(String.valueOf(new StringBuffer(RedisKeyConstants.PERMISSION_MENU_ID_LIST).append(FIELD_CHARACTER)), oldPermission);
                    Long oldBatchDelPerNum = scanAndDelKeys(oldMenuPerPattern);
                    log.info("[updateMenu] 批量删除redis[{}]数量:{}", oldMenuPerPattern, oldBatchDelPerNum);
                }

                if (ObjectUtil.isNotNull(newPermission)) {
                    // 移除 USER_ROLE_ID_LIST:*:新的permission
                    String newMenuPerPattern = String.format(String.valueOf(new StringBuffer(RedisKeyConstants.PERMISSION_MENU_ID_LIST).append(FIELD_CHARACTER)), newPermission);
                    Long newBatchDelPerNum = scanAndDelKeys(newMenuPerPattern);
                    log.info("[updateMenu] 批量删除redis[{}]数量:{}", newMenuPerPattern, newBatchDelPerNum);
                }

                // 移除 MENU_ROLE_ID_LIST:*:menuId
                String menuRolePattern = String.format(String.valueOf(new StringBuffer(RedisKeyConstants.MENU_ROLE_ID_LIST).append(FIELD_CHARACTER)), menuId);
                Long batchDelRoleNum = scanAndDelKeys(menuRolePattern);
                log.info("[deleteMenu] 批量删除redis[{}]数量:{}", menuRolePattern, batchDelRoleNum);

                // 清空本地缓存
                redisTemplate.convertAndSend(com.cf.imes.framework.redis.constants.RedisKeyConstants.PERMISSION_REFRESH, "");
            } catch (Exception e) {
                log.error("[deleteMenu] redis 清空PERMISSION_MENU_ID_LIST或message发送失败, topic:{}, 异常:{}", com.cf.imes.framework.redis.constants.RedisKeyConstants.PERMISSION_REFRESH, e);
            }
        }, threadPoolTaskExecutor);
    }


    /**
     * scan所有匹配的redis key并删除
     *
     * @param keyPattern 模糊匹配的表达式
     */
    private Long scanAndDelKeys(String keyPattern) {
        // 根据keyPattern scan匹配的redis key
        List<String> delKeys = new ArrayList<>();
        Cursor<String> cursor = redisTemplate.scan(ScanOptions.scanOptions().match(keyPattern).count(200).build());
        while (cursor.hasNext()) {
            delKeys.add(cursor.next());
        }
        cursor.close();
        // 删除匹配到的key
        if (CollUtil.isNotEmpty(delKeys)) {
            return redisTemplate.delete(delKeys);
        }
        return 0L;
    }

    @Override
    public List<MenuDO> getMenuList() {
        return menuMapper.selectList();
    }

    @Override
    public List<MenuDO> getMenuListByOrgan(MenuListReqVO reqVO) {
        List<MenuDO> menus = getMenuList(reqVO);
        // 开启多组织的情况下，需要过滤掉未开通的菜单
        organService.handleOrganMenu(menuIds -> menus.removeIf(menu -> !CollUtil.contains(menuIds, menu.getId())));
        return menus;
    }

    @Override
    public List<MenuDO> getMenuList(MenuListReqVO reqVO) {
        return menuMapper.selectList(reqVO);
    }

    @Override
    @Cacheable(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST, key = "#permission")
    public List<Long> getMenuIdListByPermissionFromCache(String permission) {
        List<MenuDO> menus = menuMapper.selectListByPermission(permission);
        return convertList(menus, MenuDO::getId);
    }

    @Override
    public MenuDO getMenu(Long id) {
        return menuMapper.selectById(id);
    }

    @Override
    public List<MenuDO> getMenuList(Collection<Long> ids) {
        return menuMapper.selectByIds(ids);
    }

    @Override
    @OrganIgnore
    public List<MenuDO> getMenuList1(Collection<Long> ids) {
        if(CollUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return menuMapper.selectByIds(ids);
    }

    /**
     * 校验父菜单是否合法
     * <p>
     * 1. 不能设置自己为父菜单
     * 2. 父菜单不存在
     * 3. 父菜单必须是 {@link MenuTypeEnum#MENU} 菜单类型
     *
     * @param parentId 父菜单编号
     * @param childId  当前菜单编号
     */
    @VisibleForTesting
    void validateParentMenu(Long parentId, Long childId) {
        if (parentId == null || MenuDO.ID_ROOT.equals(parentId)) {
            return;
        }
        // 不能设置自己为父菜单
        if (parentId.equals(childId)) {
            throw new ServiceException(MENU_PARENT_ERROR);
        }
        MenuDO menu = menuMapper.selectById(parentId);
        // 父菜单不存在
        if (menu == null) {
            throw new ServiceException(MENU_PARENT_NOT_EXISTS);
        }
        // 父菜单必须是目录或者菜单类型
        if (MenuTypeEnum.BUTTON.getType().equals(menu.getType())) {
            throw new ServiceException(MENU_PARENT_NOT_DIR_OR_MENU);
        }
    }

    /**
     * 校验菜单是否合法
     * <p>
     * 1. 校验相同父菜单编号下，是否存在相同的菜单名
     *
     * @param name     菜单名字
     * @param parentId 父菜单编号
     * @param id       菜单编号
     */
    @VisibleForTesting
    void validateMenu(Long parentId, String name, Long id, Integer sourceType) {
        MenuDO menu = menuMapper.selectByParentIdAndNameAndSourceType(parentId, name, sourceType);
        if (menu == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的菜单
        if (id == null) {
            throw new ServiceException(MENU_NAME_DUPLICATE);
        }
        if (!menu.getId().equals(id)) {
            throw new ServiceException(MENU_NAME_DUPLICATE);
        }
    }

    /**
     * 初始化菜单的通用属性。
     * <p>
     * 例如说，只有目录或者菜单类型的菜单，才设置 icon
     *
     * @param menu 菜单
     */
    private void initMenuProperty(MenuDO menu) {
        // 菜单为按钮类型时，无需 component、icon、path 属性，进行置空
        if (MenuTypeEnum.BUTTON.getType().equals(menu.getType())) {
            menu.setComponent("");
            menu.setComponentName("");
            menu.setIcon("");
            menu.setPath("");
        }
    }

    @Override
    @OrganIgnore
    public List<MenuDO> getManageEndPointMenuList(Collection<Long> ids) {
        return menuMapper.selectListIn(ids, true, LocaleUtils.getLocale());
    }

    @Override
    @OrganIgnore
    public List<MenuDO> getCustomEndPointMenuList(Collection<Long> ids) {
        return menuMapper.selectListIn(ids, false, LocaleUtils.getLocale());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void trans(MenuTransReqVO reqVO) {
        String to = reqVO.getTargetLanguage();
        // 清理对应语种下的历史记录
        int delete = menui18nMapper.delete(new LambdaQueryWrapper<MenuI18nDO>()
                .eq(MenuI18nDO::getLocale, to));
        log.info("========== 【菜单国际化】{}清理历史记录，删除 {} 条 =====", to, delete);

        // 查询所有有效的菜单类型 菜单
        List<MenuDO> menuDOS = menuMapper.selectList(new LambdaQueryWrapper<MenuDO>()
                .eq(MenuDO::getDeleted, false)
                .in(MenuDO::getType, MenuTypeEnum.MENU.getType(), MenuTypeEnum.DIR.getType()));

        // 转成有序 map（key = 序号, value = MenuDO）
        Map<Integer, MenuDO> menuMap = IntStream.range(0, menuDOS.size())
                .boxed()
                .collect(Collectors.toMap(
                        i -> i,
                        menuDOS::get,
                        (v1, v2) -> v1,
                        LinkedHashMap::new
                ));

        // 拼接 menu name，用换行分隔
        String namesForQuery = menuMap.values().stream()
                .map(MenuDO::getName)
                .filter(Objects::nonNull)
                .collect(Collectors.joining("\n"));

        // 请求翻译api
        TransApi transApi = new TransApi(transProperties.getAppId(), transProperties.getSecurityKey(), transProperties.getApiHost());
        String transResult = transApi.getTransResult(namesForQuery, "zh", to);

        JSONObject obj = JSON.parseObject(transResult);
        String errorCode = obj.getString("error_code");
        if (StringUtils.isNotEmpty(errorCode)) {
            throw new ServiceException(MENU_TRANS_ERROR, errorCode);
        }
        JSONArray arr = obj.getJSONArray("trans_result");

        List<MenuI18nDO> i18nList = new ArrayList<>();
        for (int i = 0; i < arr.size(); i++) {
            MenuDO menuDO = menuMap.get(i);
            JSONObject item = arr.getJSONObject(i);
            String src = item.getString("src");
            String dst = item.getString("dst");

            if (!menuDO.getName().equals(UnicodeUtil.toString(src))) {
                continue;
            }

            String name = UnicodeUtil.toString(dst);
            MenuI18nDO i18n = new MenuI18nDO();
            i18n.setMenuId(menuDO.getId());
            i18n.setLocale(to);
            i18n.setMenuName(name);
            if (LanguageEnum.EN.getLanguage().equals(to)) {
                i18n.setMenuName(Arrays.stream(name.split("\\s+"))
                        .filter(s -> !s.isEmpty())
                        .map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1))
                        .collect(Collectors.joining(" ")));
            } else {
                i18n.setMenuName(name);
            }

            i18nList.add(i18n);
        }

        if (CollUtil.isNotEmpty(i18nList)) {
            menui18nMapper.insertBatch(i18nList);
            log.info("========== 【菜单国际化】{}成功，插入 {} 条 =====", to, i18nList.size());
        }
    }
}
