package com.erp.service;

import com.erp.common.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class DashboardService extends BaseService {

    @Autowired
    private CommonService commonService;

    private static final String NS = "dashboard.";

    // ═══ 대시보드 CRUD (MENU_INFO 단일 본체) ═══

    public Map<String, Object> getDashboardList(Map<String, Object> params) {
        commonService.applyPagination(params);
        int totalCount = sqlSession.selectOne(NS + "getDashboardListCnt", params);
        List<Map<String, Object>> list = sqlSession.selectList(NS + "getDashboardList", params);
        return commonService.buildListResponse(list, totalCount, params);
    }

    public Map<String, Object> getDashboardInfo(Map<String, Object> params) {
        return sqlSession.selectOne(NS + "getDashboardInfo", params);
    }

    @Transactional
    public Map<String, Object> insertDashboard(Map<String, Object> params) {
        String objid = String.valueOf(System.currentTimeMillis());
        params.put("objid", objid);
        params.put("writer", params.get("user_id"));

        // 개인 대시보드 여부: is_personal=true 이면 USER_ID 채움, 아니면 NULL (회사 공용)
        Object isPersonal = params.get("is_personal");
        boolean personal = isPersonal != null
                && (Boolean.TRUE.equals(isPersonal) || "true".equalsIgnoreCase(String.valueOf(isPersonal)));
        if (!personal) {
            params.put("user_id", null);
        }

        // 회사별 자동 시퀀스 = URL. COMPANY_CODE 내 /숫자 형 URL 중 최대값 + 1
        Integer nextSeq = sqlSession.selectOne(NS + "getNextMenuSeq", params);
        if (nextSeq == null) nextSeq = 1;
        String menuUrl = "/" + nextSeq;
        params.put("seq", String.valueOf(nextSeq));
        params.put("menu_url", menuUrl);

        sqlSession.insert(NS + "insertDashboard", params);

        Map<String, Object> result = new HashMap<>();
        result.put("objid", objid);
        result.put("dashboard_id", objid); // 프론트 하위호환
        result.put("menu_url", menuUrl);
        result.put("seq", nextSeq);
        return result;
    }

    @Transactional
    public void updateDashboard(Map<String, Object> params) {
        sqlSession.update(NS + "updateDashboard", params);
    }

    @Transactional
    public int deleteDashboard(Map<String, Object> params) {
        return sqlSession.update(NS + "deleteDashboard", params);
    }

    // ═══ 카드 CRUD ═══

    public List<Map<String, Object>> getDashboardCardList(Map<String, Object> params) {
        return sqlSession.selectList(NS + "getDashboardCardList", params);
    }

    @Transactional
    public Map<String, Object> insertDashboardCard(Map<String, Object> params) {
        String cardId = "card_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        params.put("card_id", cardId);
        if (params.get("position_x") == null) params.put("position_x", 50);
        if (params.get("position_y") == null) params.put("position_y", 50);
        if (params.get("width") == null) params.put("width", 600);
        if (params.get("height") == null) params.put("height", 400);
        if (params.get("display_order") == null) params.put("display_order", 0);
        sqlSession.insert(NS + "insertDashboardCard", params);
        Map<String, Object> result = new HashMap<>();
        result.put("card_id", cardId);
        return result;
    }

    @Transactional
    public void updateDashboardCard(Map<String, Object> params) {
        sqlSession.update(NS + "updateDashboardCard", params);
    }

    @Transactional
    public void deleteDashboardCard(Map<String, Object> params) {
        sqlSession.update(NS + "deleteDashboardCard", params);
    }

    @Transactional
    @SuppressWarnings("unchecked")
    public void updateCardPositions(Map<String, Object> params) {
        List<Map<String, Object>> cards = (List<Map<String, Object>>) params.get("cards");
        if (cards != null) {
            for (Map<String, Object> card : cards) {
                sqlSession.update(NS + "updateCardPosition", card);
            }
        }
    }
}
