package org.xyzh.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import java.util.Date;
import java.util.Collections;
import java.util.List;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xyzh.api.system.service.ViewService;
import org.xyzh.api.system.vo.PermissionVO;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.dto.sys.TbSysViewDTO;
import org.xyzh.common.dto.sys.TbSysViewPermissionDTO;
import org.xyzh.common.utils.id.IdUtil;
import org.xyzh.common.utils.StringUtils;
import org.xyzh.system.mapper.view.TbSysViewMapper;
import org.xyzh.system.mapper.view.TbSysViewPermissionMapper;

/**
 * @description    视图服务实现类
 * @filename    ViewServiceImpl.java
 */
@DubboService(
    version = "1.0.0",
    group = "system",
    timeout = 3000,
    retries = 0
)
public class ViewServiceImpl implements ViewService {

    private static final Logger logger = LoggerFactory.getLogger(ViewServiceImpl.class);
    private static final String MSG_VIEW_ID_REQUIRED = "视图ID不能为空";
    private static final String MSG_QUERY_PARAM_REQUIRED = "查询条件不能为空";
    private static final String MSG_PAGE_PARAM_REQUIRED = "分页参数不能为空";

    @Resource
    private TbSysViewMapper viewMapper;

    @Resource
    private TbSysViewPermissionMapper viewPermissionMapper;

    @Override
    public ResultDomain<TbSysViewDTO> insertView(TbSysViewDTO viewDTO) {
        if (viewDTO == null) {
            return ResultDomain.failure("视图参数不能为空");
        }
        if (StringUtils.isBlank(viewDTO.getViewId())) {
            viewDTO.setViewId(IdUtil.generateID());
        }
        if (viewDTO.getCreateTime() == null) {
            viewDTO.setCreateTime(new Date());
        }
        if (viewDTO.getDeleted() == null) {
            viewDTO.setDeleted(false);
        }
        int rows = viewMapper.insertView(viewDTO);
        if (rows > 0) {
            logger.info("新增视图成功, viewId={}", viewDTO.getViewId());
            return ResultDomain.success("新增视图成功", viewDTO);
        }
        logger.warn("新增视图失败, viewId={}", viewDTO.getViewId());
        return ResultDomain.failure("新增视图失败");
    }

    @Override
    public ResultDomain<TbSysViewDTO> updateView(TbSysViewDTO viewDTO) {
        if (viewDTO == null || StringUtils.isBlank(viewDTO.getViewId())) {
            return ResultDomain.failure(MSG_VIEW_ID_REQUIRED);
        }
        viewDTO.setUpdateTime(new Date());
        int rows = viewMapper.updateView(viewDTO);
        if (rows > 0) {
            logger.info("更新视图成功, viewId={}", viewDTO.getViewId());
            return ResultDomain.success("更新视图成功", viewDTO);
        }
        logger.warn("更新视图失败, viewId={}", viewDTO.getViewId());
        return ResultDomain.failure("更新视图失败");
    }

    @Override
    public ResultDomain<Boolean> deleteView(TbSysViewDTO viewDTO) {
        if (viewDTO == null || StringUtils.isBlank(viewDTO.getViewId())) {
            return ResultDomain.failure(MSG_VIEW_ID_REQUIRED);
        }
        int rows = viewMapper.deleteView(viewDTO);
        if (rows > 0) {
            logger.info("删除视图成功, viewId={}", viewDTO.getViewId());
            return ResultDomain.success("删除视图成功", Boolean.TRUE);
        }
        logger.warn("删除视图失败, viewId={}", viewDTO.getViewId());
        return ResultDomain.failure("删除视图失败");
    }

    @Override
    public ResultDomain<PermissionVO> getView(PermissionVO filter) {
        TbSysViewDTO dto = PermissionVO.toViewDTO(filter);
        if (dto == null) {
            return ResultDomain.failure(MSG_QUERY_PARAM_REQUIRED);
        }
        List<TbSysViewDTO> list = viewMapper.getViewByFilter(dto);
        if (list == null || list.isEmpty()) {
            return ResultDomain.failure("未找到视图");
        }
        PermissionVO result = PermissionVO.fromViewDTO(list.get(0));
        return ResultDomain.success("获取视图成功", result);
    }

    @Override
    public ResultDomain<PermissionVO> getViewList(PermissionVO filter) {
        TbSysViewDTO dto = PermissionVO.toViewDTO(filter);
        List<TbSysViewDTO> list = viewMapper.getViewByFilter(dto);
        List<PermissionVO> result = PermissionVO.fromViewDTOList(list);
        return ResultDomain.success("获取视图列表成功", result);
    }

    @Override
    public ResultDomain<PermissionVO> getViewPage(PageRequest<PermissionVO> pageRequest) {
        if (pageRequest == null) {
            return ResultDomain.failure(MSG_PAGE_PARAM_REQUIRED);
        }
        PageParam pageParam = pageRequest.getPageParam();
        TbSysViewDTO filter = PermissionVO.toViewDTO(pageRequest.getFilter());
        int total = viewMapper.getViewCount(filter);
        pageParam.setTotal(total);
        pageParam.setTotalPages(pageParam.getPageSize() == 0 ? 0 : (int) Math.ceil((double) total / pageParam.getPageSize()));
        List<TbSysViewDTO> list = viewMapper.getViewPageByFilter(filter, pageParam);
        List<PermissionVO> data = PermissionVO.fromViewDTOList(list);
        PageDomain<PermissionVO> pageDomain = new PageDomain<>(pageParam, data);
        return ResultDomain.success("分页查询视图成功", pageDomain);
    }

    @Override
    public ResultDomain<PermissionVO> getViewTree(PermissionVO filter) {
        return getViewList(filter);
    }

    @Override
    public ResultDomain<PermissionVO> setViewPermissions(PermissionVO permissionVO) {
        if (permissionVO == null || StringUtils.isBlank(permissionVO.getViewId())) {
            return ResultDomain.failure(MSG_VIEW_ID_REQUIRED);
        }
        viewPermissionMapper.delete(new QueryWrapper<TbSysViewPermissionDTO>()
            .eq("view_id", permissionVO.getViewId()));
        List<String> permissionIds = permissionVO.getPermissionIdList();
        if (permissionIds != null && !permissionIds.isEmpty()) {
            Date now = new Date();
            for (String permissionId : permissionIds) {
                if (StringUtils.isBlank(permissionId)) {
                    continue;
                }
                TbSysViewPermissionDTO dto = new TbSysViewPermissionDTO();
                dto.setViewId(permissionVO.getViewId());
                dto.setPermissionId(permissionId);
                dto.setCreateTime(now);
                dto.setDeleted(false);
                viewPermissionMapper.insertViewPermission(dto);
            }
        }
        logger.info("视图权限设置成功, viewId={}, count={}",
            permissionVO.getViewId(),
            permissionIds == null ? 0 : permissionIds.size());
        return ResultDomain.success("设置视图权限成功", permissionVO);
    }

    @Override
    public ResultDomain<PermissionVO> getViewPermissionList(PermissionVO permissionVO) {
        TbSysViewPermissionDTO dto = new TbSysViewPermissionDTO();
        if (permissionVO != null) {
            dto.setViewId(permissionVO.getViewId());
            if (permissionVO.getPermissionIdList() != null && !permissionVO.getPermissionIdList().isEmpty()) {
                dto.setPermissionId(permissionVO.getPermissionIdList().get(0));
            } else {
                dto.setPermissionId(permissionVO.getPermissionId());
            }
            dto.setDeptPath(permissionVO.getDeptPath());
            dto.setDeleted(permissionVO.getDeleted());
        }
        List<PermissionVO> list = viewPermissionMapper.getViewPermissionByFilter(dto);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("获取视图权限列表成功", list);
    }

}
