package io.gisbi.application.baseinfo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.gisbi.application.baseinfo.domain.Application;
import io.gisbi.application.baseinfo.mapper.ApplicationMapper;
import io.gisbi.application.baseinfo.service.IApplicationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.gisbi.application.module.service.IModuleService;
import io.gisbi.utils.AuthUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 应用系统 服务实现类
 * </p>
 *
 * @author zhengsl
 * @since 2025-03-24
 */
@Service
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, Application> implements IApplicationService {
    @Resource
    private IModuleService moduleService;

    @Resource
    private ApplicationMapper applicationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createApplication(Application application) {
        // 参数校验
        if (application == null) {
            throw new IllegalArgumentException("应用信息不能为空");
        }
        if (application.getName() == null || application.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("应用名称不能为空");
        }

        // 检查应用名称是否已存在
        long count = this.count(new QueryWrapper<Application>().eq("name", application.getName()));
        if (count > 0) {
            throw new IllegalArgumentException("应用名称已存在");
        }

        // 生成自增编号逻辑
        try {
            Integer maxCode = applicationMapper.getMaxCode();
            maxCode = (maxCode != null) ? maxCode : 0;
            String formattedCode = String.format("%06d", maxCode + 1);
            application.setCode(formattedCode);
        } catch (Exception e) {
            throw new RuntimeException("生成应用编号失败", e);
        }

        // 设置基础字段
        LocalDateTime now = LocalDateTime.now();
        application.setType("01");  // 数据分析类项目
        application.setStatus("01"); // 初始创建
        application.setCreatedate(now);
        application.setLastmodifier(AuthUtils.getUser().getUserId().toString());
        application.setLastmodifydate(now);
        
        // 保存应用并初始化模块
        try {
            this.save(application);
            moduleService.initAppModules(application.getId());
            return true;
        } catch (Exception e) {
            throw new RuntimeException("创建应用失败", e);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(String id) {
        if (StrUtil.isNotBlank(id)) {
            applicationMapper.deleteById(id);
            moduleService.deleteModulesByAppID(id);
        }
      return true;
    }
}
