package com.nokia.tsl_data.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.extern.slf4j.Slf4j;

/**
 * 原始数据入库
 */
@Slf4j
@Service
public class TslWaraHouseService {

    private final JdbcTemplate jdbcTemplate;

    // 河北_CEM移网质量投诉明细 相关
    @Value("${tslTask.source.MOBILE_COMP_SQL}")
    private String MOBILE_COMP_SQL;
    @Value("${tslTask.source.MOBILE_COMP_DIR}")
    private String MOBILE_COMP_DIR;
    @Value("${tslTask.source.MOBILE_COMP_PREFIX}")
    private String MOBILE_COMP_PREFIX;
    @Value("${tslTask.source.MOBILE_COMP_FIELD_NUM}")
    private int MOBILE_COMP_FIELD_NUM;

    // 河北_CEM高品质2日统计 相关 he_d_high_quality
    @Value("${tslTask.source.HIGH_QUALITY_SQL}")
    private String HIGH_QUALITY_SQL;
    @Value("${tslTask.source.HIGH_QUALITY_DIR}")
    private String HIGH_QUALITY_DIR;
    @Value("${tslTask.source.HIGH_QUALITY_PREFIX}")
    private String HIGH_QUALITY_PREFIX;
    @Value("${tslTask.source.HIGH_QUALITY_FIELD_NUM}")
    private int HIGH_QUALITY_FIELD_NUM;

    public TslWaraHouseService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public String check(String day) {
        String filePath1 = MOBILE_COMP_DIR + MOBILE_COMP_PREFIX + day + ".csv";
        String filePath2 = HIGH_QUALITY_DIR + HIGH_QUALITY_PREFIX + day + ".csv";
        File file1 = new File(filePath1);
        File file2 = new File(filePath2);
        StringBuffer stringBuffer = new StringBuffer();
        if (!file1.exists()) {
            stringBuffer.append("河北_CEM移网质量投诉明细_HE_D_MOBILE_COMP 表账期 ").append(day).append(" 缺失。");
        }
        if (!file2.exists()) {
            stringBuffer.append("河北_CEM高品质2日统计_HE_D_HIGH_QUALITY 表账期 ").append(day).append(" 缺失。");
        }
        if (stringBuffer.length() == 0) {
            stringBuffer.append("账期").append(day).append("数据源正常。");
        }
        return stringBuffer.toString();
    }

    /**
     * 河北_CEM移网质量投诉明细 数据入库
     * report_auto.he_d_mobile_comp
     * 
     * @throws IOException
     * @throws FileNotFoundException
     */
    @Transactional(rollbackFor = Exception.class)
    public void waraHouseMobileComp(String day) throws FileNotFoundException, IOException {
        String filePath = MOBILE_COMP_DIR + MOBILE_COMP_PREFIX + day + ".csv";
        try (Reader reader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8)) {
            CSVParser parser = CSVFormat.DEFAULT.builder()
                    .setRecordSeparator("\n")
                    .setQuote(null)
                    .setDelimiter("||")
                    .setSkipHeaderRecord(false)
                    .build().parse(reader);

            List<CSVRecord> records = parser.getRecords();
            List<Object[]> list = new ArrayList<>();
            for (CSVRecord record : records) {
                Object[] ps = new Object[MOBILE_COMP_FIELD_NUM];
                list.add(ps);
                for (int i = 0; i < ps.length; i++) {
                    ps[i] = record.get(i);
                }
            }
            jdbcTemplate.batchUpdate(MOBILE_COMP_SQL, list);
            log.debug("河北_CEM移网质量投诉明细 {} 入库成功", day);
        }
    }

    /**
     * 河北_CEM高品质2日统计 数据入库
     * report_auto.he_d_high_quality
     * 
     * @throws IOException
     * @throws FileNotFoundException
     */
    @Transactional(rollbackFor = Exception.class)
    public void waraHouseHighQuality(String day) throws FileNotFoundException, IOException {
        String filePath = HIGH_QUALITY_DIR + HIGH_QUALITY_PREFIX + day + ".csv";
        try (Reader reader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8)) {
            CSVParser parser = CSVFormat.DEFAULT.builder()
                    .setRecordSeparator("\n")
                    .setQuote(null)
                    .setDelimiter(",")
                    .setSkipHeaderRecord(false)
                    .build().parse(reader);

            List<CSVRecord> records = parser.getRecords();
            List<Object[]> list = new ArrayList<>();
            for (CSVRecord record : records) {
                Object[] ps = new Object[HIGH_QUALITY_FIELD_NUM];
                list.add(ps);
                for (int i = 0; i < ps.length; i++) {
                    ps[i] = record.get(i);
                }
            }
            jdbcTemplate.batchUpdate(HIGH_QUALITY_SQL, list);
            log.debug("河北_CEM高品质2日统计 {} 入库成功", day);
        }
    }
}
