package incheon.ags.ias.dataHoprReg.service.impl;

import incheon.ags.ias.dataHoprReg.mapper.KbRtmsSyncMapper;
import incheon.ags.ias.dataHoprReg.service.KbRtmsPyongSyncService;
import incheon.ags.ias.dataHoprReg.util.KbRtmsFileRefiner;
import incheon.ags.ias.dataHoprReg.vo.KbRtmsPyongVO;
import incheon.com.cmm.exception.BusinessException;
import incheon.com.file.service.ComFileService;
import incheon.com.file.vo.ComFileDtlVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * KB RTMS 평형 동기화 서비스
 *
 * 파일: 222인천_평형.txt ("|" 구분, 12컬럼)
 * 컬럼: unq_key | blnc_accto_se_no | splyar | splyar_se | xuar | ...
 * 동기화 방식: DELETE ALL + INSERT
 */
@Slf4j
@Service("kbRtmsPyongSyncService")
@RequiredArgsConstructor
public class KbRtmsPyongSyncServiceImpl extends EgovAbstractServiceImpl implements KbRtmsPyongSyncService {

    private static final int EXPECTED_COLS = 12;

    private final KbRtmsSyncMapper kbRtmsSyncMapper;
    private final ComFileService comFileService;

    @Value("${Globals.comfile.storage.path:../upload}")
    private String uploadPath;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int syncFromFile(String atchFileId, String operatorId) throws Exception {
        log.info("========== KB RTMS 평형 동기화 시작 ==========");

        File file = resolveFile(atchFileId);

        // filterIncheon=false, fixDoublePipe=false (평형은 "인천광역시" 미포함)
        List<List<String>> rows = KbRtmsFileRefiner.readAndRefine(file, false, false, EXPECTED_COLS);

        if (rows.isEmpty()) {
            throw new BusinessException("파싱된 데이터가 없습니다. 평형 파일인지 확인해주세요.");
        }

        // 첫 행 검증: 평형 파일은 첫 컬럼=unq_key(비어있지 않음), 둘째 컬럼=blnc_accto_se_no(숫자)
        List<String> firstRow = rows.get(0);
        String firstCol = firstRow.get(0);
        String secondCol = firstRow.get(1);
        if (firstCol == null || firstCol.isEmpty()) {
            throw new BusinessException("평형 파일 형식이 아닙니다. 첫 컬럼(unq_key)이 비어있습니다.");
        }
        if (secondCol == null || !secondCol.matches("\\d+")) {
            throw new BusinessException("평형 파일 형식이 아닙니다. 둘째 컬럼(blnc_accto_se_no)이 숫자가 아닙니다. 현재값: " + secondCol);
        }

        // 전체 삭제 후 재적재
        int deleted = kbRtmsSyncMapper.deletePyongAll();
        log.info("기존 평형 삭제: {} 건", deleted);

        int processedCount = 0;
        for (List<String> c : rows) {
            KbRtmsPyongVO vo = new KbRtmsPyongVO();
            vo.setUnqKey(c.get(0));
            BigDecimal blncAcctoSeNo = toBigDecimal(c.get(1));
            if (blncAcctoSeNo == null) {
                log.warn("평형 {}행: blnc_accto_se_no 누락, 스킵", processedCount + 1);
                continue;
            }
            vo.setBlncAcctoSeNo(blncAcctoSeNo);
            vo.setSplyar(toBigDecimal(c.get(2)));
            vo.setSplyarSe(c.get(3));
            vo.setXuar(toBigDecimal(c.get(4)));
            vo.setHhCnt(toBigDecimal(c.get(5)));
            vo.setRmCnt(toBigDecimal(c.get(6)));
            vo.setBthrmCnt(toBigDecimal(c.get(7)));
            vo.setUnitAcctoUntprc(toBigDecimal(c.get(8)));
            vo.setCmpxDrc(c.get(9));
            vo.setBldgAtrb(c.get(10));
            vo.setAddArea(c.get(11));
            vo.setOperatorId(operatorId);

            kbRtmsSyncMapper.insertPyong(vo);
            processedCount++;
        }

        log.info("========== KB RTMS 평형 동기화 완료: {} 건 ==========", processedCount);
        return processedCount;
    }

    private BigDecimal toBigDecimal(String value) {
        if (value == null || value.trim().isEmpty()) return null;
        try {
            return new BigDecimal(value.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private File resolveFile(String atchFileId) throws Exception {
        if (atchFileId == null || atchFileId.trim().isEmpty()) {
            throw new BusinessException("첨부파일 ID가 없습니다.");
        }

        List<ComFileDtlVO> fileList = comFileService.selectComFileDtlList(atchFileId);
        if (fileList == null || fileList.isEmpty()) {
            throw new BusinessException("파일을 찾을 수 없습니다.");
        }

        ComFileDtlVO fileInfo = fileList.get(0);
        log.info("파일 정보: {} ({}bytes)", fileInfo.getOrgnlFileNm(), fileInfo.getFileSz());

        Path basePath = Paths.get(uploadPath).toAbsolutePath().normalize();
        Path filePath = basePath.resolve(fileInfo.getStrgPathNm()).resolve(fileInfo.getStrgFileNm());
        File file = filePath.toFile();

        if (!file.exists()) {
            throw new BusinessException("파일이 존재하지 않습니다: " + filePath);
        }

        return file;
    }
}
