/// <summary>
        /// 
        /// </summary>
        /// <param name="reportIdDest"></param>
        /// <param name="lstReportOptionValuesSource"></param>
        public static int SaveReportOptionValue(Guid idReport, Upsilab.Data.Model.Option option, int idOptionAttribute, string value, string fieldType, string colomnName, int? lineNumber)
        {
            ReportOptionAttributeValue optionAttributeValue2 = null;
            int idOption = option.idOption;
            bool updateDateUpdated = false;
            string completedStatus = Report.ReportBL.Status.Completed.ToString();
            string waitingForClientUpdateStatus = Report.ReportBL.Status.WaitingForClientUpdate.ToString();

            //Insert new OptionValue
            using (UpsilabEntities db = new UpsilabEntities())
            {
                //Get current report
                Data.Model.Report report = (from rep in db.Report
                                            where rep.idReport == idReport
                                            select rep).FirstOrDefault();

                //Check if customer has completed report
                var checkCompletedReport = (from rep in db.Report
                                            where rep.CustomerProspect.idCustomer == report.CustomerProspect.idCustomer
                                                  && rep.Status == completedStatus
                                            select rep).FirstOrDefault();

                if (checkCompletedReport != null)
                {
                    updateDateUpdated = true;
                }

                //#9262 : Check if customer changes the info after Adviser request
                if (!updateDateUpdated)
                {
                    if (report.Status == waitingForClientUpdateStatus && SessionManager.GetUserSession().IsEndUser())
                    {
                        updateDateUpdated = true;
                    }
                }

                #region TEXTBOX, DROPDOWN : txt, dt, enum
                //1- Save option attribute value (simple textbox / textarea)
                if (fieldType == "txt" || fieldType == "dt" || fieldType == "enum")
                {
                    ReportOptionAttributeValue optionAttributeValue = (from roav in db.ReportOptionAttributeValue.Include("ReportOptionValue")
                                                                       where roav.idReport == idReport && roav.idOptionAttribute == idOptionAttribute
                                                                       select roav).FirstOrDefault();

                    if (optionAttributeValue != null)
                    {
                        if (optionAttributeValue.Value != value) //update if not equal
                        {
                            optionAttributeValue.Value = value;
                            optionAttributeValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                            optionAttributeValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                        }
                        else
                        {
                            //Do nothing if equal
                        }
                        optionAttributeValue2 = optionAttributeValue;
                    }
                    else if (!string.IsNullOrEmpty(value)) //Insert if value is not empty
                    {
                        //Check if reportOptionValue exists
                        ReportOptionValue optionValue = (from rov in db.ReportOptionValue
                                                         where rov.idReport == idReport && rov.idOption == idOption
                                                         select rov).FirstOrDefault();

                        if (optionValue == null) //insert option value
                        {
                            optionValue = new ReportOptionValue()
                            {
                                idReport = idReport,
                                idOption = idOption,
                                Value = string.Empty,
                                DateCreated = DateTime.Now,
                                DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                            };

                            //Add ReportOptionValue to DB : don't save yet
                            db.ReportOptionValue.AddObject(optionValue);

                            //Insert parent
                            while (option.idParent.HasValue)
                            {
                                ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                       where rov.idReport == idReport && rov.idOption == option.idParent
                                                                       select rov).FirstOrDefault();

                                if (optionParentValue == null)
                                {
                                    optionParentValue = new ReportOptionValue()
                                    {
                                        idReport = idReport,
                                        idOption = option.idParent.Value,
                                        Value = string.Empty,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    //Add ReportOptionValue to DB : don't save yet
                                    db.ReportOptionValue.AddObject(optionParentValue);

                                    //Check if this parent option has already parent ?
                                    option = optionParentValue.Option;
                                }
                                else
                                {
                                    optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                    break;
                                }
                            }
                        }

                        //Insert optionattrubutevalue
                        ReportOptionAttributeValue newReportOptionAttributeValue = new ReportOptionAttributeValue()
                        {
                            idReport = idReport,
                            idOptionAttribute = idOptionAttribute,
                            idReportOptionValue = optionValue.idReportOptionValue,
                            Value = value,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionAttributeValue to DB : don't save yet
                        optionValue.ReportOptionAttributeValue.Add(newReportOptionAttributeValue);
                        optionAttributeValue2 = newReportOptionAttributeValue;
                    }
                }
                #endregion

                #region RADIO BUTTON : rb
                //2- Save option attribute value (Radio button)
                else if (fieldType == "rb")
                {
                    //Delete old rb
                    IList<ReportOptionValue> optionValues = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                             where rov.idReport == idReport && rov.Option.idParent == option.idParent
                                                             select rov).ToList();

                    //Delete option attribute values attached to option value
                    if (optionValues != null)
                    {
                        foreach (var optionValue in optionValues)
                        {
                            IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = optionValue.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            db.ReportOptionValue.DeleteObject(optionValue);

                            //Delete child option value
                            IList<ReportOptionValue> lstOptionValuesChild = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                                             where rov.idReport == idReport && rov.Option.idParent == optionValue.idOption
                                                                             select rov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValueChild.ReportOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                        db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    db.ReportOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }

                    }

                    if (!string.IsNullOrEmpty(value) && value.ToLower() == "true")
                    {
                        //Insert new rb
                        ReportOptionValue newOptionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(newOptionValue);

                        //Insert parent ??
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }


                    
                    }
                }
                #endregion

                #region CHECKBOX : chk
                //3- Save option attribute value (Checkbox)
                else if (fieldType == "chk")
                {
                    ReportOptionValue optionValue;

                    if (value == "false")
                    {
                        //Delete old chk
                        optionValue = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                       where rov.idReport == idReport && rov.idOption == idOption
                                       select rov).FirstOrDefault();

                        //Delete option attribute values attached to option value
                        if (optionValue != null)
                        {
                            IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = optionValue.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            db.ReportOptionValue.DeleteObject(optionValue);

                            //Delete child option value
                            IList<ReportOptionValue> lstOptionValuesChild = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                                             where rov.idReport == idReport && rov.Option.idParent == optionValue.idOption
                                                                             select rov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValueChild.ReportOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                        db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    db.ReportOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }
                    }
                    else if (value == "true")
                    {
                        //Insert new chk
                        optionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(optionValue);

                        //Insert parent ??
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }
                    }
                }
                #endregion

                #region CUSTOM DATATYPE
                //4- Custom datatype
                else
                {
                    //pour agreg
                    ReportOptionAttributeValue agregOptionAttributeValue = null;
                    //

                    ReportOptionValue optionValue = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                     where rov.idReport == idReport && rov.idOption == idOption
                                                     select rov).FirstOrDefault();

                    IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>();

                    //Option value ?
                    if (optionValue != null)
                    {
                        lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                        lstOptionAttributeValues = lstOptionAttributeValues.Where(oav => oav.idOptionAttribute == idOptionAttribute).ToList();
                    }
                    else if (!string.IsNullOrEmpty(value))
                    {
                        optionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(optionValue);

                        //Insert parent
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }
                    }

                    //Get target option attribute
                    if (lineNumber.HasValue && lineNumber.Value < lstOptionAttributeValues.Count)
                    {
                        //Line already in database
                        ReportOptionAttributeValue reportOptionAttrValue = lstOptionAttributeValues[lineNumber.Value];
                        dynamic customData = reportOptionAttrValue.CustomObjectValue;

                        if (customData != null)
                        {
                            bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                            if (!isTheSameValue)
                            {
                                CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                reportOptionAttrValue.CustomObjectValue = customData;
                                reportOptionAttrValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                reportOptionAttrValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                //pour agreg
                                agregOptionAttributeValue = reportOptionAttrValue;
                                //
                            }
                        }
                        optionAttributeValue2 = reportOptionAttrValue;

                    }
                    else
                    {
                        //Get Custom datatype columns
                        List<string> customAttribute = OptionBL.GetCustomAttributeNames(fieldType);

                        if (customAttribute.Count > 0)
                        {
                            dynamic customData = new Upsilab.Data.Model.CustomObject();
                            dynamic customDataEmpty = new Upsilab.Data.Model.CustomObject();

                            foreach (string itemColumnName in customAttribute)
                            {
                                string _strVal = string.Empty;

                                if (itemColumnName == colomnName)
                                {
                                    _strVal = value;
                                }
                                CustomObject.SetValueByPropertyName(customData, itemColumnName, _strVal);
                                CustomObject.SetValueByPropertyName(customDataEmpty, itemColumnName, string.Empty);
                            }

                            ReportOptionAttributeValue optionAttributeValue = null;
                            bool createOptionAttr = true;
                            if (!lineNumber.HasValue && lstOptionAttributeValues.Count > 0)
                            {
                                createOptionAttr = false;
                                optionAttributeValue = optionValue.ReportOptionAttributeValue.Where(oav => oav.idOptionAttribute == idOptionAttribute).FirstOrDefault();
                                optionAttributeValue2 = optionAttributeValue;
                            }
                            else if (lineNumber.HasValue)
                            {
                                //Create empty lines
                               // while (lstOptionAttributeValues.Count < lineNumber.Value)
                                {
                                    optionAttributeValue = new ReportOptionAttributeValue()
                                    {
                                        idReport = idReport,
                                        idOptionAttribute = idOptionAttribute,
                                        idReportOptionValue = optionValue.idReportOptionValue,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    optionAttributeValue.CustomObjectValue = customDataEmpty;

                                    lstOptionAttributeValues.Add(optionAttributeValue);
                                    optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);
                                }
                            }

                            //if (optionAttributeValue == null)
                            if (createOptionAttr)
                            {
                                //Add new line
                                //Insert optionattrubutevalue
                                optionAttributeValue = new ReportOptionAttributeValue()
                                {
                                    idReport = idReport,
                                    idOptionAttribute = idOptionAttribute,
                                    idReportOptionValue = optionValue.idReportOptionValue,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                optionAttributeValue.CustomObjectValue = customData;

                                //pour agreg
                                agregOptionAttributeValue = optionAttributeValue;
                                optionAttributeValue2 = agregOptionAttributeValue;
                                //
                            }
                            else
                            {
                                customData = optionAttributeValue.CustomObjectValue;

                                if (customData != null)
                                {
                                    bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                                    if (!isTheSameValue)
                                    {
                                        CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                        optionAttributeValue.CustomObjectValue = customData;
                                        optionAttributeValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                        optionAttributeValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                        //pour agreg
                                        agregOptionAttributeValue = optionAttributeValue;
                                        //
                                    }
                                }
                            }

                            //Add ReportOptionAttributeValue to DB : don't save yet
                            optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);
                            optionAttributeValue2 = optionAttributeValue;
                        }
                    }

                    #region Save patrimoine from Recueil/lab to Agregateur
                    //update/add ag_upsideo_compte
                    //if (report.CustomerProspect.User1.idLicenseAgreg.HasValue && report.CustomerProspect.User1.idAgregCGP.HasValue
                    //    && (idOptionAttribute == 204 || idOptionAttribute == 205 || idOptionAttribute == 206)
                    //    && report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet != null)
                    if (report.CustomerProspect.User1.HasAggregatorLicense() && report.CustomerProspect.User1.idAgregCGP.HasValue
                        && (idOptionAttribute == 204 || idOptionAttribute == 205 || idOptionAttribute == 206)
                        && report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet != null)
                    {
                        //Les ids en cours : agregCabinet, agregCGP et agregClient
                        Guid idAgregCGP = report.CustomerProspect.User1.idAgregCGP.Value;
                        Guid idAgregCabinet = report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet;
                        Guid currentAgregClientId = Guid.Empty;

                        if (report.CustomerProspect.idAgregClient.HasValue)
                        {
                            currentAgregClientId = report.CustomerProspect.idAgregClient.Value;
                        }
                        else
                        {
                            ag_upsideo_client clientAgregToAdd = new ag_upsideo_client()
                            {
                                idclient = Guid.NewGuid(),
                                idcgp = idAgregCGP,
                                nomclient = report.CustomerProspect.User.UserName,
                                prenomclient = report.CustomerProspect.User.UserFirstName,
                                adr = report.CustomerProspect.Adress,
                                cp = report.CustomerProspect.ZipCode,
                                ville = report.CustomerProspect.City,
                                titre = report.CustomerProspect.Title,
                                ddn = DateTime.Now,
                                deleted = "n"
                            };

                            db.ag_upsideo_client.AddObject(clientAgregToAdd);

                            report.CustomerProspect.idAgregClient = clientAgregToAdd.idclient;
                            currentAgregClientId = clientAgregToAdd.idclient;
                        }

                        //Fournisseur de l'actif : comme il s'agit de données provenant du "Recueil/LAB", mettre "UPSIDEO" comme fournisseur fictif (pour chaque cabinet / etablissement)
                        //Get fournisseur
                        ag_upsideo_fournisseur agregFournisseur = db.ag_upsideo_fournisseur.Where(f => f.idcrmcabinet == report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet
                                                                                                  && f.nomfournisseur == Business.Agreg.agupsideocompteBL.FournisseurUpsideo).FirstOrDefault();

                        if (agregFournisseur == null)
                        {
                            agregFournisseur = new ag_upsideo_fournisseur()
                            {
                                idcrmcabinet = idAgregCabinet,
                                nomfournisseur = Business.Agreg.agupsideocompteBL.FournisseurUpsideo,
                                cleAgreg = Business.Agreg.agupsideocompteBL.FournisseurUpsideo.ToLower(),
                                deleted = "n",
                            };

                            //TODO : to delete : normalement à faire lors de la souscription mais garder ce code pour test
                            //Insertion fournisseur avec un autre contexte
                            using (UpsilabEntities dbTemp = new UpsilabEntities())
                            {
                                dbTemp.ag_upsideo_fournisseur.AddObject(agregFournisseur);
                                dbTemp.SaveChanges();
                            }
                        }

                        //num compte fictif dans table compte Agreg
                        string numCompteFictif = string.Empty;
                        numCompteFictif = string.Format("{0}_{1}", idOptionAttribute.ToString(), lineNumber.Value.ToString());

                        //teste si existe déjà (maj) si no new
                        ag_upsideo_compte currentCompte = db.ag_upsideo_compte.Where(c => c.idclient == currentAgregClientId && c.numcompte == numCompteFictif).FirstOrDefault();

                        //maj
                        if (currentCompte != null && agregOptionAttributeValue != null)
                        {
                            switch (idOptionAttribute)
                            {
                                case 204:
                                case 205:
                                    {
                                        currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                                        currentCompte.dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null;
                                        currentCompte.valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null;
                                        currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null;
                                        currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                        currentCompte.type = "n"; //pour l'instant : non géré
                                    }
                                    break;
                                case 206:
                                    currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                                    currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null;
                                    currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                    currentCompte.type = "n"; //pour l'instant : non géré
                                    break;
                                default:
                                    break;

                            }
                        }
                        //new
                        else if (currentCompte == null && agregOptionAttributeValue != null)
                        {
                            switch (idOptionAttribute)
                            {
                                case 204:
                                case 205:
                                    {
                                        currentCompte = new ag_upsideo_compte()
                                        {
                                            idclient = currentAgregClientId,
                                            idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                                            idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                            numcompte = numCompteFictif,
                                            typecontrat = "bien immobilier",
                                            deleted = "n",

                                            designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                                            dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null,
                                            valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null,
                                            totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null
                                        };
                                        if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                                        {
                                            db.ag_upsideo_compte.AddObject(currentCompte);
                                        }

                                    }
                                    break;

                                case 206:
                                    {
                                        currentCompte = new ag_upsideo_compte()
                                        {
                                            idclient = currentAgregClientId,
                                            idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                                            idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                            numcompte = numCompteFictif,
                                            typecontrat = "professionels",
                                            deleted = "n",

                                            designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                                            totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null

                                        };
                                        if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                                        {
                                            db.ag_upsideo_compte.AddObject(currentCompte);
                                        }
                                    }
                                    break;
                                default:
                                    break;

                            }
                        }
                    }
                    #endregion


                }
                #endregion

                #region Report
                //5- Update dateupdated report               
                report.DateUpdated = DateTime.Now;
                #endregion

                //6- Commit all changes here
                db.SaveChanges();
                return optionAttributeValue2!=null ? optionAttributeValue2.idReportOptionAttributeValue : 0;
            }
        }
        public static int SaveReportOptionValueWithLineNumber(Guid idReport, Upsilab.Data.Model.Option option,
            int idOptionAttribute, string value, string fieldType, string colomnName, int idReportAttributeValue)
        {
            ReportOptionAttributeValue optionAttributeValue = null;
            int idOption = option.idOption;
            bool updateDateUpdated = false;
            string completedStatus = Report.ReportBL.Status.Completed.ToString();
            string waitingForClientUpdateStatus = Report.ReportBL.Status.WaitingForClientUpdate.ToString();

            using (UpsilabEntities db = new UpsilabEntities())
            {
                ReportOptionAttributeValue reportOptionAttrValueToUpdate =
                    db.ReportOptionAttributeValue.FirstOrDefault(
                        x => x.idReportOptionAttributeValue == idReportAttributeValue);

                /* UPDATE */
                if (reportOptionAttrValueToUpdate != null)
                {
                    dynamic customData = reportOptionAttrValueToUpdate.CustomObjectValue;

                    if (customData != null)
                    {
                        bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                        if (!isTheSameValue)
                        {

                            CustomObject.SetValueByPropertyName(customData, colomnName, value);
                            reportOptionAttrValueToUpdate.CustomObjectValue = customData;
                            reportOptionAttrValueToUpdate.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                            if (reportOptionAttrValueToUpdate.ReportOptionValue!=null)
                            {
                                reportOptionAttrValueToUpdate.ReportOptionValue.DateUpdated = (updateDateUpdated)
                                                        ? DateTime.Now
                                                        : (DateTime?)null; 
                            }

                            
                            //
                        }
                    }
                    optionAttributeValue = reportOptionAttrValueToUpdate;
                }
                /* CREATE */
                else
                {
                    //Get current report
                    Data.Model.Report report = (from rep in db.Report
                                                where rep.idReport == idReport
                                                select rep).FirstOrDefault();

                    //Check if customer has completed report
                    var checkCompletedReport = (from rep in db.Report
                                                where rep.CustomerProspect.idCustomer == report.CustomerProspect.idCustomer
                                                      && rep.Status == completedStatus
                                                select rep).FirstOrDefault();

                    if (checkCompletedReport != null)
                    {
                        updateDateUpdated = true;
                    }

                    //#9262 : Check if customer changes the info after Adviser request
                    if (!updateDateUpdated)
                    {
                        if (report.Status == waitingForClientUpdateStatus && SessionManager.GetUserSession().IsEndUser())
                        {
                            updateDateUpdated = true;
                        }
                    }

                    {
                        //pour agreg
                        ReportOptionAttributeValue agregOptionAttributeValue = null;
                        //

                        ReportOptionValue optionValue = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                         where rov.idReport == idReport && rov.idOption == idOption
                                                         && rov.ReportOptionAttributeValue.FirstOrDefault(x => x.idReportOptionAttributeValue == idReportAttributeValue).idReportOptionAttributeValue == idReportAttributeValue
                                                         select rov).FirstOrDefault();

                        IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>();

                        //Option value ?
                        if (optionValue != null)
                        {
                            lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                            lstOptionAttributeValues = lstOptionAttributeValues.Where(oav => oav.idOptionAttribute == idOptionAttribute).ToList();
                        }
                        else if (!string.IsNullOrEmpty(value))
                        {
                            optionValue = new ReportOptionValue()
                            {
                                idReport = idReport,
                                idOption = idOption,
                                Value = string.Empty,
                                DateCreated = DateTime.Now,
                                DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                            };

                            //Add ReportOptionValue to DB : don't save yet
                            db.ReportOptionValue.AddObject(optionValue);

                            //Insert parent
                            while (option.idParent.HasValue)
                            {
                                ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                       where rov.idReport == idReport && rov.idOption == option.idParent
                                                                       select rov).FirstOrDefault();

                                if (optionParentValue == null && option.idParent != null)
                                {
                                    optionParentValue = new ReportOptionValue()
                                    {
                                        idReport = idReport,
                                        idOption = option.idParent.Value,
                                        Value = string.Empty,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    //Add ReportOptionValue to DB : don't save yet
                                    db.ReportOptionValue.AddObject(optionParentValue);

                                    //Check if this parent option has already parent ?
                                    option = optionParentValue.Option;
                                }
                                else
                                {
                                    optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                    break;
                                }
                            }
                        }

                        

                        //Get target option attribute
                        if (lstOptionAttributeValues.Any())
                        {
                            //Line already in database
                            ReportOptionAttributeValue reportOptionAttrValue = lstOptionAttributeValues.FirstOrDefault();
                            dynamic customData = reportOptionAttrValue.CustomObjectValue;

                            if (customData != null)
                            {
                                bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                                if (!isTheSameValue)
                                {

                                    CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                    reportOptionAttrValue.CustomObjectValue = customData;
                                    reportOptionAttrValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                    reportOptionAttrValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                    //pour agreg
                                    agregOptionAttributeValue = reportOptionAttrValue;
                                    optionAttributeValue = reportOptionAttrValue;
                                    //
                                }
                            }

                        }
                        else
                        {
                            //Get Custom datatype columns
                            List<string> customAttribute = OptionBL.GetCustomAttributeNames(fieldType);

                            if (customAttribute.Count > 0)
                            {
                                dynamic customData = new Upsilab.Data.Model.CustomObject();
                                dynamic customDataEmpty = new Upsilab.Data.Model.CustomObject();

                                foreach (string itemColumnName in customAttribute)
                                {
                                    string _strVal = string.Empty;

                                    if (itemColumnName == colomnName)
                                    {
                                        _strVal = value;
                                        CustomObject.SetValueByPropertyName(customData, itemColumnName, _strVal);
                                        CustomObject.SetValueByPropertyName(customDataEmpty, itemColumnName, string.Empty);
                                    }
                                }


                                bool createOptionAttr = true;
                                //Create empty lines
                                if (lstOptionAttributeValues.Count == 0)
                                {
                                    optionAttributeValue = new ReportOptionAttributeValue()
                                    {
                                        idReport = idReport,
                                        idOptionAttribute = idOptionAttribute,
                                        idReportOptionValue = optionValue.idReportOptionValue,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    optionAttributeValue.CustomObjectValue = customData;

                                    lstOptionAttributeValues.Add(optionAttributeValue);
                                    //optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);
                                }

                                if (optionAttributeValue == null)
                                //if (createOptionAttr)
                                {
                                    //Add new line
                                    //Insert optionattrubutevalue
                                    optionAttributeValue = new ReportOptionAttributeValue()
                                    {
                                        idReport = idReport,
                                        idOptionAttribute = idOptionAttribute,
                                        idReportOptionValue = optionValue.idReportOptionValue,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    optionAttributeValue.CustomObjectValue = customData;

                                    //pour agreg
                                    agregOptionAttributeValue = optionAttributeValue;
                                    //
                                }
                                else
                                {
                                    customData = optionAttributeValue.CustomObjectValue;

                                    if (customData != null)
                                    {
                                        bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                                        if (!isTheSameValue)
                                        {
                                            CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                            optionAttributeValue.CustomObjectValue = customData;
                                            optionAttributeValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                            optionAttributeValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                            //pour agreg
                                            agregOptionAttributeValue = optionAttributeValue;
                                            //
                                        }
                                    }
                                }

                                //Add ReportOptionAttributeValue to DB : don't save yet
                                optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);

                            }
                        }
                        

                        //#region Save patrimoine from Recueil/lab to Agregateur
                        ////update/add ag_upsideo_compte
                        //if (report.CustomerProspect.User1.idLicenseAgreg.HasValue && report.CustomerProspect.User1.idAgregCGP.HasValue
                        //    && (idOptionAttribute == 204 || idOptionAttribute == 205 || idOptionAttribute == 206)
                        //    && report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet != null)
                        //{
                        //    //Les ids en cours : agregCabinet, agregCGP et agregClient
                        //    Guid idAgregCGP = report.CustomerProspect.User1.idAgregCGP.Value;
                        //    Guid idAgregCabinet = report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet;
                        //    Guid currentAgregClientId = Guid.Empty;

                        //    if (report.CustomerProspect.idAgregClient.HasValue)
                        //    {
                        //        currentAgregClientId = report.CustomerProspect.idAgregClient.Value;
                        //    }
                        //    else
                        //    {
                        //        ag_upsideo_client clientAgregToAdd = new ag_upsideo_client()
                        //        {
                        //            idclient = Guid.NewGuid(),
                        //            idcgp = idAgregCGP,
                        //            nomclient = report.CustomerProspect.User.UserName,
                        //            prenomclient = report.CustomerProspect.User.UserFirstName,
                        //            adr = report.CustomerProspect.Adress,
                        //            cp = report.CustomerProspect.ZipCode,
                        //            ville = report.CustomerProspect.City,
                        //            titre = report.CustomerProspect.Title,
                        //            ddn = DateTime.Now,
                        //            deleted = "n"
                        //        };

                        //        db.ag_upsideo_client.AddObject(clientAgregToAdd);

                        //        report.CustomerProspect.idAgregClient = clientAgregToAdd.idclient;
                        //        currentAgregClientId = clientAgregToAdd.idclient;
                        //    }

                        //    //Fournisseur de l'actif : comme il s'agit de données provenant du "Recueil/LAB", mettre "UPSIDEO" comme fournisseur fictif (pour chaque cabinet / etablissement)
                        //    //Get fournisseur
                        //    ag_upsideo_fournisseur agregFournisseur = db.ag_upsideo_fournisseur.Where(f => f.idcrmcabinet == report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet
                        //                                                                              && f.nomfournisseur == Business.Agreg.agupsideocompteBL.FournisseurUpsideo).FirstOrDefault();

                        //    if (agregFournisseur == null)
                        //    {
                        //        agregFournisseur = new ag_upsideo_fournisseur()
                        //        {
                        //            idcrmcabinet = idAgregCabinet,
                        //            nomfournisseur = Business.Agreg.agupsideocompteBL.FournisseurUpsideo,
                        //            cleAgreg = Business.Agreg.agupsideocompteBL.FournisseurUpsideo.ToLower(),
                        //            deleted = "n",
                        //        };

                        //        //TODO : to delete : normalement à faire lors de la souscription mais garder ce code pour test
                        //        //Insertion fournisseur avec un autre contexte
                        //        using (UpsilabEntities dbTemp = new UpsilabEntities())
                        //        {
                        //            dbTemp.ag_upsideo_fournisseur.AddObject(agregFournisseur);
                        //            dbTemp.SaveChanges();
                        //        }
                        //    }

                        //    //num compte fictif dans table compte Agreg
                        //    string numCompteFictif = string.Empty;
                        //    numCompteFictif = string.Format("{0}_{1}", idOptionAttribute.ToString(), lineNumber.Value.ToString());

                        //    //teste si existe déjà (maj) si no new
                        //    ag_upsideo_compte currentCompte = db.ag_upsideo_compte.Where(c => c.idclient == currentAgregClientId && c.numcompte == numCompteFictif).FirstOrDefault();

                        //    //maj
                        //    if (currentCompte != null && agregOptionAttributeValue != null)
                        //    {
                        //        switch (idOptionAttribute)
                        //        {
                        //            case 204:
                        //            case 205:
                        //                {
                        //                    currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                        //                    currentCompte.dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null;
                        //                    currentCompte.valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null;
                        //                    currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null;
                        //                    currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                        //                    currentCompte.type = "n"; //pour l'instant : non géré
                        //                }
                        //                break;
                        //            case 206:
                        //                currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                        //                currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null;
                        //                currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                        //                currentCompte.type = "n"; //pour l'instant : non géré
                        //                break;
                        //            default:
                        //                break;

                        //        }
                        //    }
                        //    //new
                        //    else if (currentCompte == null && agregOptionAttributeValue != null)
                        //    {
                        //        switch (idOptionAttribute)
                        //        {
                        //            case 204:
                        //            case 205:
                        //                {
                        //                    currentCompte = new ag_upsideo_compte()
                        //                    {
                        //                        idclient = currentAgregClientId,
                        //                        idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                        //                        idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                        //                        numcompte = numCompteFictif,
                        //                        typecontrat = "bien immobilier",
                        //                        deleted = "n",

                        //                        designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                        //                        dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null,
                        //                        valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null,
                        //                        totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null
                        //                    };
                        //                    if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                        //                    {
                        //                        db.ag_upsideo_compte.AddObject(currentCompte);
                        //                    }

                        //                }
                        //                break;

                        //            case 206:
                        //                {
                        //                    currentCompte = new ag_upsideo_compte()
                        //                    {
                        //                        idclient = currentAgregClientId,
                        //                        idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                        //                        idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                        //                        numcompte = numCompteFictif,
                        //                        typecontrat = "professionels",
                        //                        deleted = "n",

                        //                        designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                        //                        totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null

                        //                    };
                        //                    if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                        //                    {
                        //                        db.ag_upsideo_compte.AddObject(currentCompte);
                        //                    }
                        //                }
                        //                break;
                        //            default:
                        //                break;

                        //        }
                        //    }
                        //}
                        //#endregion


                    }

                    #region Report
                    //5- Update dateupdated report               
                    report.DateUpdated = DateTime.Now;
                    #endregion 
                }

                //6- Commit all changes here
                db.SaveChanges();

                return optionAttributeValue!=null ? optionAttributeValue.idReportOptionAttributeValue : 0;
            }
        }
        public List<ReportOptionAttributeValue> RetrieveCustomDataTypeValues(OptionAttribute _optionAttribute, Guid _idReport)
        {
            List<ReportOptionAttributeValue> retVal = new List<ReportOptionAttributeValue>();

            //List<string> customAttribute = new List<string>();
            List<string> customAttribute = OptionBL.GetCustomAttributeNames(_optionAttribute.Datatype);

            if (customAttribute.Count > 0)
            {
                string param_Prefix = string.Format("{0}_{1}_{2}", _optionAttribute.Datatype.ToLower(), _optionAttribute.idOption, _optionAttribute.idOptionAttribute);
                var paramList = Request.Params.AllKeys.Where(s => s.StartsWith(param_Prefix));

                //int entryCount = paramList.Count() / customAttribute.Count; TODO : For knowledgelevet, this condition doesn't work                 
                int entryCount = paramList.Count();

                int entryCountFinal = paramList.Where(x => x.Contains(customAttribute[0])).Count();
                if (entryCountFinal > 0)
                {
                    entryCount = entryCountFinal;
                }

                for (int i = 0; i < entryCount; i++)
                {
                    dynamic _customData = new Upsilab.Data.Model.CustomObject();
                    foreach (string _attr in customAttribute)
                    {
                        string _strVal = string.Empty;
                        string param = string.Format("{0}_{1}", param_Prefix, _attr);
                        if (_optionAttribute.SingleOption.HasValue && !_optionAttribute.SingleOption.Value)
                        {
                            param = string.Format("{0}_{1}_{2}", param_Prefix, i, _attr);
                        }
                        if (!string.IsNullOrEmpty(Request.Params[param]))
                        {
                            _strVal = Request.Params[param];
                        }
                        CustomObject.SetValueByPropertyName(_customData, _attr, _strVal);
                    }
                    ReportOptionAttributeValue newVal = new ReportOptionAttributeValue();
                    newVal.idOptionAttribute = _optionAttribute.idOptionAttribute;
                    newVal.idReport = _idReport;
                    newVal.CustomObjectValue = _customData;
                    retVal.Add(newVal);
                }
            }

            return retVal;
        }