package com.czg.service.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.czg.account.dto.RoleTemplateDTO;
import com.czg.account.entity.SysRole;
import com.czg.account.service.SysRoleService;
import com.czg.exception.CzgException;
import com.czg.sa.StpKit;
import com.czg.service.account.mapper.SysRoleTemplateMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.market.entity.SysRoleTemplate;
import com.czg.market.service.SysRoleTemplateService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

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

/**
 * 角色模板 服务层实现。
 *
 * @author zs
 * @since 2025-12-08
 */
@Service
public class SysRoleTemplateServiceImpl extends ServiceImpl<SysRoleTemplateMapper, SysRoleTemplate> implements SysRoleTemplateService {
    @Resource
    private SysRoleService roleService;

    @Override
    public Boolean saveInfo(RoleTemplateDTO dto) {
        SysRoleTemplate roleTemplate = BeanUtil.copyProperties(dto, SysRoleTemplate.class, "roleIdList");
        roleTemplate.setOpUser(StpKit.USER.getAccount());
        if (roleTemplate.getPid() != null) {
            boolean exists = exists(query().eq(SysRoleTemplate::getPid, roleTemplate.getPid()).eq(SysRoleTemplate::getName, roleTemplate.getName()));
            if (exists) {
                throw new CzgException("添加失败，该模板下已存在同名角色");
            }
            SysRole sysRole = new SysRole().setName(roleTemplate.getName()).setCreateUserId(StpKit.USER.getShopId());
            roleService.save(sysRole);
            roleTemplate.setRoleId(sysRole.getId());
        }
        roleTemplate.setOpSysUserId(StpKit.USER.getLoginIdAsLong());
        return save(roleTemplate);
    }

    @Override
    public List<SysRoleTemplate> listInfo(Long pid, Integer isEnable) {
        QueryWrapper queryWrapper = new QueryWrapper()
                .eq(SysRoleTemplate::getPid, pid)
                .eq(SysRoleTemplate::getIsEnable, isEnable)
                .orderBy(SysRoleTemplate::getSort, false);
        List<SysRoleTemplate> list = list(queryWrapper);

        // 转成 map，便于通过 id 找节点
        Map<Integer, SysRoleTemplate> map = list.stream()
                .collect(Collectors.toMap(SysRoleTemplate::getId, v -> v));

        // 存根节点
        List<SysRoleTemplate> roots = new ArrayList<>();

        for (SysRoleTemplate item : list) {
            if (item.getPid() == null || item.getPid() == 0) {
                // 这是根节点
                roots.add(item);
            } else {
                // 找父节点
                SysRoleTemplate parent = map.get(item.getPid());
                if (parent != null) {
                    parent.getChildren().add(item);
                }
            }
        }
        if (isEnable != null && isEnable == 1) {
            roots = roots.stream()
                    .filter(root -> root.getChildren() != null && !root.getChildren().isEmpty())
                    .collect(Collectors.toList());
        }
        return roots;
    }

    @Override
    public Boolean editInfo(RoleTemplateDTO dto) {
        SysRoleTemplate roleTemplate = BeanUtil.copyProperties(dto, SysRoleTemplate.class);
        boolean exists = exists(query().eq(SysRoleTemplate::getPid, roleTemplate.getPid()).eq(SysRoleTemplate::getName, roleTemplate.getName()).ne(SysRoleTemplate::getId, roleTemplate.getId()));
        if (exists) {
            throw new CzgException("添加失败，已存在同名模板");
        }
        roleTemplate.setOpUser(StpKit.USER.getAccount());
        roleTemplate.setOpSysUserId(StpKit.USER.getLoginIdAsLong());
        return updateById(roleTemplate);
    }
}
