package com.storlead.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.system.mapper.MenuMapper;
import com.storlead.system.mapper.SysAppMapper;
import com.storlead.system.pojo.dto.SysAppPageDTO;
import com.storlead.system.pojo.entity.MenuEntity;
import com.storlead.system.pojo.entity.SysAppEntity;
import com.storlead.system.service.SysAppService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 系统应用服务实现
 */
@Service
public class SysAppServiceImpl extends MyBaseServiceImpl<SysAppMapper, SysAppEntity> implements SysAppService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public IPage<SysAppEntity> pageQuery(SysAppPageDTO dto) {
        IPage<SysAppEntity> page = new Page<>(dto.getPageIndex(), dto.getPageSize());
        LambdaQueryWrapper<SysAppEntity> w = new LambdaQueryWrapper<>();
        w.eq(SysAppEntity::getIsDelete, 0);
        if (dto.getAppCode() != null) {
            w.eq(SysAppEntity::getAppCode, dto.getAppCode());
        }
        if (StrUtil.isNotBlank(dto.getAppName())) {
            w.like(SysAppEntity::getAppName, dto.getAppName().trim());
        }
        if (dto.getEnabled() != null) {
            w.eq(SysAppEntity::getEnabled, dto.getEnabled());
        }
        w.orderByAsc(SysAppEntity::getSort).orderByAsc(SysAppEntity::getId);
        return page(page, w);
    }

    @Override
    public List<SysAppEntity> listEnabled() {
        return list(new LambdaQueryWrapper<SysAppEntity>()
                .eq(SysAppEntity::getIsDelete, 0)
                .eq(SysAppEntity::getEnabled, 1)
                .orderByAsc(SysAppEntity::getSort)
                .orderByAsc(SysAppEntity::getId));
    }

    @Override
    public SysAppEntity getDetail(Long id) {
        if (id == null) {
            return null;
        }
        return getOne(new LambdaQueryWrapper<SysAppEntity>()
                .eq(SysAppEntity::getId, id)
                .eq(SysAppEntity::getIsDelete, 0));
    }

    @Override
    public Result<?> saveApp(SysAppEntity body) {
        if (body == null || body.getAppCode() == null || StrUtil.isBlank(body.getAppName())) {
            return Result.error("appCode、appName 不能为空");
        }
        body.setAppName(body.getAppName().trim());
        if (StrUtil.isNotBlank(body.getAppTitle())) {
            body.setAppTitle(body.getAppTitle().trim());
        }
//        if (StrUtil.isNotBlank(body.getDomainName())) {
//            body.setDomainName(body.getDomainName().trim());
//        }

        Long userId = LoginUserUtil.getCurrentUserId();
        Date now = new Date();
        if (body.getId() == null) {
            body.setCreateBy(userId);
            body.setCreateTime(now);
        }

        LambdaQueryWrapper<SysAppEntity> dup = new LambdaQueryWrapper<SysAppEntity>()
                .eq(SysAppEntity::getAppCode, body.getAppCode())
                .eq(SysAppEntity::getIsDelete, 0);
        if (body.getId() != null) {
            dup.ne(SysAppEntity::getId, body.getId());
        }
        if (count(dup) > 0) {
            return Result.error("应用编码已存在: " + body.getAppCode());
        }

        body.setUpdateBy(userId);
        body.setUpdateTime(now);
        saveOrUpdate(body);
        return Result.result(body.getId());
    }

    @Override
    public Result<?> enableApp(Long id, Boolean enabled) {
        if (id == null || enabled == null) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<SysAppEntity> uw = new LambdaUpdateWrapper<>();
        uw.set(SysAppEntity::getEnabled, Boolean.TRUE.equals(enabled) ? 1 : 0);
        uw.set(SysAppEntity::getUpdateTime, new Date());
        uw.set(SysAppEntity::getUpdateBy, LoginUserUtil.getCurrentUserId());
        uw.eq(SysAppEntity::getId, id).eq(SysAppEntity::getIsDelete, 0);
        if (!update(uw)) {
            return Result.error("更新失败，应用不存在或已删除");
        }
        return Result.ok();
    }

    @Override
    public Result<?> deleteApp(Long id) {
        if (Objects.isNull(id)) {
            return Result.error("id 不能为空");
        }
        if (!trySoftDelete(id)) {
            return Result.error("删除失败：仍存在关联菜单，或记录不存在");
        }
        return Result.ok();
    }

    /**
     * 逻辑删除；存在关联菜单时返回 false。
     */
    private boolean trySoftDelete(Long id) {
        long menuCnt = menuMapper.selectCount(
                new LambdaQueryWrapper<MenuEntity>().eq(MenuEntity::getAppId, id));
        if (menuCnt > 0) {
            return false;
        }
        LambdaUpdateWrapper<SysAppEntity> uw = new LambdaUpdateWrapper<>();
        uw.set(SysAppEntity::getIsDelete, 1);
        uw.set(SysAppEntity::getUpdateTime, new Date());
        uw.set(SysAppEntity::getUpdateBy, LoginUserUtil.getCurrentUserId());
        uw.eq(SysAppEntity::getId, id).eq(SysAppEntity::getIsDelete, 0);
        return update(uw);
    }
}
