/*
 * @Author: Kane
 * @Date: 2023-10-12 00:34:39
 * @LastEditors: Kane
 * @FilePath: /desktop_archievement_backend/src/main/java/com/cpic/xim/web/controllers/dataimport/bi/ImportBIDataController.java
 * @Description: 
 * 
 * Copyright (c) ${2023} by Kane, All Rights Reserved. 
 */
package com.cpic.xim.web.controllers.dataimport.bi;

import java.io.IOException;
import java.util.ArrayList;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cpic.xim.mybatis.mapper.ImportBIArchievementDataMapper;
import com.cpic.xim.mybatis.mapper.TWrTelsalerMapper;
import com.cpic.xim.mybatis.pojo.BIDepartmentAttachingRateRecord;
import com.cpic.xim.mybatis.pojo.BIDepartmentRenewalRateRecord;
import com.cpic.xim.mybatis.pojo.BITelsalerAttachingRateRecord;
import com.cpic.xim.mybatis.pojo.BITelsalerRenewalRateRecord;
import com.cpic.xim.mybatis.pojo.TWrTelsalerRecord;
import com.cpic.xim.mybatis.utils.MybatisUtils;
import com.cpic.xim.utils.data.ImportBIExcelData;
import com.cpic.xim.utils.data.ImportTWRTelsalerData;
import com.cpic.xim.web.controllers.dataimport.ReportType;;

@Controller
@RequestMapping( method = RequestMethod.POST, path = "/import_bi_data" )
public class ImportBIDataController
{
    private static Logger logger = LoggerFactory.getLogger( ImportBIDataRequest.class );

    @RequestMapping( method = RequestMethod.POST, path = "/excel.do" )
    @ResponseBody
    public static ImportBIDataResponse importBIData( @RequestBody ImportBIDataRequest request )
    {
        ImportBIDataResponse response = new ImportBIDataResponse();
        String filePath = request.getFilePath();
        int type = request.getReportType();
        int firstRow = request.getFirstRow();
        int sheetIndex = request.getSheetIndex();
        int importedCount = 0;

        try
        {
            if ( type == ReportType.BiTelsalerAttachingRateReport.getReportTypeCode() )
            {
                importedCount = importBITelsalerAttachingRate( filePath, sheetIndex, firstRow );
            }
            else if ( type == ReportType.BiTelsalerRenewalRateReport.getReportTypeCode() )
            {
                importedCount = importBITeslsalerRenewalRate( filePath, sheetIndex, firstRow );
            }
            else if ( type == ReportType.BiDepartmentAttachingRateReport.getReportTypeCode() )
            {
                importedCount = importBIDepartmentAttachingRate( filePath, sheetIndex, firstRow );
            }
            else if ( type == ReportType.BiDepartmentRenewalRateReport.getReportTypeCode() )
            {
                importedCount = importBIDepartmentRenewalRate( filePath, sheetIndex, firstRow );
            }
            else if ( type == ReportType.TWrTelsalerList.getReportTypeCode() )
            {
                logger.info( "导入机构续保率报表。");
                
                importedCount = importTWrTelsalerList( filePath, sheetIndex, firstRow );
            }

            response.setImportedCount( importedCount );
            response.setSuccess( true );
            response.setMessage( "导入成功" );
        }
        catch ( IOException error )
        {
            String message = "加载文件错误，错误消息：" + error.getMessage();
            response.setSuccess( false );
            response.setMessage( message );

            logger.error( message, error );
        }
        catch ( InvalidFormatException error )
        {
            String message = "Excel文件格式错误，错误消息：" + error.getMessage();
            response.setSuccess( false );
            response.setMessage( message );

            logger.error( message, error );
        }
        catch ( PersistenceException error )
        {
            String message = "Mybatis执行错误，错误消息：" + error.getMessage();
            response.setSuccess( false );
            response.setMessage( message );

            logger.error( message, error );
        }

        return response;
    }


    private static int importBITelsalerAttachingRate( String filePath, int sheetIndex,
            int firstRow ) throws PersistenceException, IOException, InvalidFormatException
    {
        SqlSession session = null;
        int importedCount = 0;

        try
        {
            ArrayList<BITelsalerAttachingRateRecord> records = ImportBIExcelData
                    .importBITelsalerAttachingRateRecordFromXlsx( filePath, sheetIndex, firstRow );

            session = MybatisUtils.getSqlSessionBatch();
            ImportBIArchievementDataMapper mapper =
                    session.getMapper( ImportBIArchievementDataMapper.class );

            mapper.cleanTelsalerAttachingRateData();

            for ( BITelsalerAttachingRateRecord record : records )
            {
                mapper.insertTelsalerAttachingRateDataToDB( record );
                importedCount++;
            }

            session.commit();
        }
        catch ( Exception error )
        {
            if ( session != null )
            {
                session.rollback();
            }

            throw error;
        }

        return importedCount;
    }

    private static int importBITeslsalerRenewalRate( String filePath, int sheetIndex, int firstRow )
            throws PersistenceException, IOException, InvalidFormatException
    {
        ArrayList<BITelsalerRenewalRateRecord> records = null;
        SqlSession session = null;
        ImportBIArchievementDataMapper mapper = null;
        int importedCount = 0;

        try
        {
            records = ImportBIExcelData.importBITelsalerRenewalRateFromXlsx( filePath, sheetIndex,
                    firstRow );

            session = MybatisUtils.getSqlSessionBatch();
            mapper = session.getMapper( ImportBIArchievementDataMapper.class );

            // 清理数据
            mapper.cleanTelsalerRenewalRateData();

            for ( BITelsalerRenewalRateRecord record : records )
            {
                mapper.insertTelsalerRenewalRateDataToDB( record );
                importedCount++;
            }

            session.commit();
        }
        catch ( Exception error )
        {
            if ( session != null )
            {
                session.rollback();
            }

            throw error;
        }

        return importedCount;
    }

    private static int importBIDepartmentAttachingRate( String filePath, int sheetIndex,
            int firstRow ) throws PersistenceException, IOException, InvalidFormatException
    {
        ArrayList<BIDepartmentAttachingRateRecord> records = null;
        SqlSession session = null;
        ImportBIArchievementDataMapper mapper = null;
        int importedCount = 0;

        try
        {
            records = ImportBIExcelData.importBIDepartmentAttachingRateRecordsFromXlsx( filePath,
                    sheetIndex, firstRow );
            session = MybatisUtils.getSqlSessionBatch();
            mapper = session.getMapper( ImportBIArchievementDataMapper.class );

            mapper.cleanDepartmentAttachingRateData();

            for ( BIDepartmentAttachingRateRecord record : records )
            {
                mapper.insertDepartmentAttachingRateDataToDB( record );
                importedCount++;
            }

            session.commit();
        }
        catch ( Exception error )
        {
            if ( session != null )
            {
                session.rollback();
            }

            throw error;
        }

        return importedCount;
    }

    private static int importBIDepartmentRenewalRate( String filePath, int sheetIndex, int firstRow )
            throws PersistenceException, IOException, InvalidFormatException
    {

        ArrayList<BIDepartmentRenewalRateRecord> records = null;
        SqlSession session = null;
        ImportBIArchievementDataMapper mapper = null;
        int importedCount = 0;

        try
        {
            records = ImportBIExcelData.importBIDepartmentRenewalRateRecordsFromXlsx(filePath, sheetIndex, firstRow);
            session = MybatisUtils.getSqlSessionBatch();
            mapper = session.getMapper(ImportBIArchievementDataMapper.class);
            
            mapper.cleanDepartmentRenewalRateData();

            for ( BIDepartmentRenewalRateRecord record : records )
            {
                mapper.insertDepartmentRenewalRateDataToDB(record);

                importedCount++;
            }

            session.commit();
        }
        catch ( Exception error)
        {
            if ( session != null )
            {
                session.rollback();
            }

            throw error;
        }

        return importedCount;
    }

    private static int importTWrTelsalerList( String filePath, int sheetIndex, int firstRow )
            throws PersistenceException, IOException, InvalidFormatException
    {

        ArrayList<TWrTelsalerRecord> records = null;
        SqlSession session = null;
        TWrTelsalerMapper mapper = null;
        int importedCount = 0;

        try
        {
            records = ImportTWRTelsalerData.importTWrTelsalerDataFromExcel(filePath, sheetIndex, firstRow);
            session = MybatisUtils.getSqlSessionBatch();
            mapper = session.getMapper(TWrTelsalerMapper.class);
            
            mapper.cleanTWrTelsalerTeamRecord();

            for ( TWrTelsalerRecord record : records )
            {
                mapper.insertTWrTelsalerRecordToDB(record);

                importedCount++;
            }

            session.commit();
        }
        catch ( Exception error)
        {
            if ( session != null )
            {
                session.rollback();
            }

            throw error;
        }

        return importedCount;
    }
}
