package com.fp.person.rules.save;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.Map;

import javax.persistence.Query;

import com.fp.common.logger.APPLogger;
import com.fp.dto.save.SaveRequest;
import com.fp.excel.ExcelToMap;
import com.fp.general.exception.GeneralException;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pcustomer.balance.TcustBalanceAccount;
import com.fp.persistence.pcustomer.balance.TcustBalanceFinancial;
import com.fp.persistence.pcustomer.balance.TcustBalanceFinancialKey;
import com.fp.persistence.pcustomer.balance.TcustPersonBalance;
import com.fp.persistence.pgeneral.image.TgeneFilesDetail;
import com.fp.persistence.pgeneral.image.TgeneFilesDetailKey;

/**
 * Clase que graba la data recibida de Excel en la tabla TcustBalanceFinancial
 * 
 * @author BPTWPA
 */
public class FinancialSituation {

    /**
     * Mï¿½todo que graba en la base de datos las cuentas del balance subido en excel
     * 
     * @param tcustPersonBalance Objeto TcustPersonBalance
     * @param excelMap Mapa obtenido del archivo de excel
     * @throws Exception
     */
    // public List<TcustBalanceFinancial> completeFinancialSituation(TcustPersonBalance tcustPersonBalance, SaveRequest
    // pSaveRequest) throws Exception {
    public void completeFinancialSituation(TcustPersonBalance tcustPersonBalance, SaveRequest pSaveRequest) throws Exception {
        // List<TcustBalanceFinancial> lTcustBalanceFinancial = new ArrayList<TcustBalanceFinancial>();
    	boolean isNew= (Boolean) pSaveRequest.get("nuevo");
        Map<String, Object> mapExcel;
        if (tcustPersonBalance == null) {
            return;// lTcustBalanceFinancial;
        }
        TgeneFilesDetailKey tgeneFilesDetailKey = new TgeneFilesDetailKey(tcustPersonBalance.getCode(), FormatDates.getDefaultExpiryTimestamp());
        TgeneFilesDetail tgeneFilesDetail = TgeneFilesDetail.find(PersistenceHelper.getEntityManager(), tgeneFilesDetailKey);
        if (tgeneFilesDetail == null) {
            return;// lTcustBalanceFinancial;
        }
        if (tgeneFilesDetail.getExtension().equals("xls") || tgeneFilesDetail.getExtension().equals("xlsx")) {
            APPLogger.getLogger().error("2");
            ExcelToMap excelMap = new ExcelToMap(tgeneFilesDetail.getImage(), tgeneFilesDetail.getExtension());
            mapExcel = excelMap.getExcelMap();
            APPLogger.getLogger().error("3");
            if ((mapExcel == null) || mapExcel.isEmpty()) {
            	throw new GeneralException("CUST-0009","ARCHIVO NO CUMPLE CON FORMATO REQUERIDO");
            }
            APPLogger.getLogger().error("3.1");
            
            if(!isNew)
            this.update(tcustPersonBalance.getPk().getPersoncode(), tcustPersonBalance.getPk().getBalancedate(), tcustPersonBalance.getPk()
                    .getBalancecatalog(), tcustPersonBalance.getPk().getBalancecatalogcode());
            if (tcustPersonBalance.getPk().getBalancecatalog().compareTo("BG") == 0) {
                APPLogger.getLogger().error("3.2");
                Integer rows = mapExcel.size() / 4;
                if (!String.valueOf(mapExcel.get("1:0")).equals("") ||!String.valueOf(mapExcel.get("0:1")).equals("ACTIVOS")) {
                    throw new GeneralException("CUST-0004", "El ARCHIVO NO ES EL CORRECTO - BG");
                }
                APPLogger.getLogger().error("3.3");
                for (int i = 1; i <= rows; i++) {
                    TcustBalanceFinancial tcustBalanceFinancial = new TcustBalanceFinancial();
                    String parameter = i + ":3";
                    if (mapExcel.containsKey(parameter)) {
                        TcustBalanceAccount tcustBalanceAccount = TcustBalanceAccount.findPerParameter(PersistenceHelper.getEntityManager(),
                                parameter);
                        if (tcustBalanceAccount != null) {
                            Object value = mapExcel.get(parameter);
                            TcustBalanceFinancialKey tcustBalanceFinancialKey = new TcustBalanceFinancialKey();
                            tcustBalanceFinancialKey.setPersoncode(tcustPersonBalance.getPk().getPersoncode());
                            tcustBalanceFinancialKey.setBalancedate(tcustPersonBalance.getPk().getBalancedate());
                            tcustBalanceFinancialKey.setBalancecatalog(tcustPersonBalance.getPk().getBalancecatalog());
                            tcustBalanceFinancialKey.setBalancecatalogcode(tcustPersonBalance.getPk().getBalancecatalogcode());
                            tcustBalanceFinancialKey.setDateto(FormatDates.getDefaultExpiryTimestamp());
                            tcustBalanceFinancialKey.setAccountcode(tcustBalanceAccount.getPk().getAccountcode());
                            tcustBalanceFinancial.setPk(tcustBalanceFinancialKey);
                            tcustBalanceFinancial.setValueaccount(new BigDecimal(value.getClass().getSimpleName().equals("BigDecimal") ? String
                                    .valueOf(value) : "0"));
                            tcustBalanceFinancial.setIngressuser(pSaveRequest.getUser());
                            PersistenceHelper.save(tcustBalanceFinancial);
                            // lTcustBalanceFinancial.add(tcustBalanceFinancial);

                        }
                    }
                }
                APPLogger.getLogger().error("3.2");
            } else {
                APPLogger.getLogger().error("3.4");
                Integer rows = mapExcel.size() / 3;
                if (String.valueOf(mapExcel.get("1:0")).equals("") ||!String.valueOf(mapExcel.get("0:1")).equals("Nombre de la Cuenta")) {
                    throw new GeneralException("CUST-0005", "El ARCHIVO NO ES EL CORRECTO - BG(IFIS)");
                }
                for (int i = 1; i <= rows; i++) {
                    TcustBalanceFinancial tcustBalanceFinancial = new TcustBalanceFinancial();
                    String keyCode = i + ":0";
                    String keyValue = i + ":2";
                    if (mapExcel.containsKey(keyCode) && mapExcel.containsKey(keyValue)) {
                        Object code = mapExcel.get(keyCode);
                        Object value = mapExcel.get(keyValue);
                        TcustBalanceFinancialKey tcustBalanceFinancialKey = new TcustBalanceFinancialKey();
                        tcustBalanceFinancialKey.setPersoncode(tcustPersonBalance.getPk().getPersoncode());
                        tcustBalanceFinancialKey.setBalancedate(tcustPersonBalance.getPk().getBalancedate());
                        tcustBalanceFinancialKey.setBalancecatalog(tcustPersonBalance.getPk().getBalancecatalog());
                        tcustBalanceFinancialKey.setBalancecatalogcode(tcustPersonBalance.getPk().getBalancecatalogcode());
                        tcustBalanceFinancialKey.setDateto(FormatDates.getDefaultExpiryTimestamp());
                        tcustBalanceFinancialKey.setAccountcode(String.valueOf(code));
                        tcustBalanceFinancial.setPk(tcustBalanceFinancialKey);
                        tcustBalanceFinancial.setValueaccount(new BigDecimal(value.getClass().getSimpleName().equals("BigDecimal") ? String
                                .valueOf(value) : "0"));
                        tcustBalanceFinancial.setIngressuser(pSaveRequest.getUser());
                        PersistenceHelper.save(tcustBalanceFinancial);
                        // lTcustBalanceFinancial.add(tcustBalanceFinancial);
                    }
                }
                APPLogger.getLogger().error("3.5");
            }
        } else {
            throw new GeneralException("CUST-0006", "EXTENSIÓN INCORRECTA DEL ARCHIVO");
        }
        APPLogger.getLogger().error("4");
        // return lTcustBalanceFinancial;
    }

    private void update(Integer pPerson, Date pDate, String pCatalog, String pCatalogCode) throws Exception {
        String sql = "update TCUSTBALANCEFINANCIAL set dateto=:dateto where PERSONCODE=:PERSON and BALANCEDATE=:date"
                + " and BALANCECATALOG=:TYPE and BALANCECATALOGCODE=:TYPECODE and dateto=:vig";
        Query q = PersistenceHelper.createNativeQuery(sql);
        q.setParameter("dateto", FormatDates.getInstance().getDataBaseTimestamp());
        q.setParameter("PERSON", pPerson);
        q.setParameter("date", pDate);
        q.setParameter("TYPE", pCatalog);
        q.setParameter("TYPECODE", pCatalogCode);
        q.setParameter("vig", FormatDates.getDefaultExpiryTimestamp());
        q.executeUpdate();
    }
}
