public static FirmInstitutionViewModel ToViewModel(this FirmInstitution entity)
 {
     var vm = new FirmInstitutionViewModel();
     if (entity == null) return vm;
     vm.IdFirmInstitution = entity.idFirmInstitution;
     vm.FirmInstitutionName = entity.FirmInstitutionName;
     vm.Email = entity.E_mail;
     return vm;
 }
        public static int ConvertHtmlSringBdsProductToPdf(string name, Guid idDocumentModel, string destinationPath, Guid idUser, FirmInstitutionViewModel firmCGP, Guid? idDocument, bool forceDownload, string logoUrl = "")
        {
            int pageCount = 0;
            Byte[] documentBytes = null;
            try
            {

                DocumentModel documentModel = GetDocumentModelFromId(idDocumentModel);
                if (documentModel != null && idDocument.HasValue)
                {
                    string strHtmlMapped = null;
                    string strFooter = null;

                    var model = EntityToModel(documentModel);
                    strHtmlMapped = AppendIntoBodyHtml(model.HtmlTemplate);
                    //strHtmlMapped = AppendIntoBodyHtml(documentModel.HtmlTemplate);

                    ExpertPDFHelper expertPdfEngine = new ExpertPDFHelper();
                    documentBytes = expertPdfEngine.GeneratePdfBytesUsingComponent(ParserHtmlMethod(documentModel, idDocument.Value, strHtmlMapped, logoUrl, true, firmCGP), name, strFooter, false);

                    FoxitPDFGenerator pdfGen = new FoxitPDFGenerator();

                    string docTitle = string.Empty; //TODO : multilingue
                    string ownerName = name;

                    pdfGen.GenerateMergeByteDocument(documentModel.IdDocumentModel, documentBytes, destinationPath, "", forceDownload, out pageCount, Upsilab.Business.Document.ElectronicSafeDocumentBL.DocumentType.SF.ToString(), "center", docTitle, ownerName,false,false);
                     
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Erreur lors de la génération du template HTML en PDF : {0}", ex.Message));
            }

            return pageCount;
        }
        public static string ParserHtmlMethod(DocumentModel documentModel, Guid idDocument, string strHtml, string logoUrl, bool isproduct, FirmInstitutionViewModel firmCGP)
        {
            var userConnecte = SessionManager.GetUserSession();
            //var firmCGP = FirmInstitutionBL.GetFirmInstitutionCgpByIdDocument(idDocument); //FirmInstitutionBL.GetFirmInstitutionByUser(userConnecte);  //GetFirmCGP();
            var firmSDG = GetFirmSDG();
                        
            
            strHtml = strHtml.Replace("[" + FieldsEditorBL.DATE_FAIT_A + "]",DateTime.Now.ToString("d"));
            strHtml = strHtml.Replace("[sdg_lieu_fait_a]", firmSDG.FirmCity);

            if (!isproduct)
            {
                strHtml = strHtml.Replace("[" + FieldsEditorBL.NOM_ETABLISSEMENT_CGP + "]",
                    firmCGP != null ? firmCGP.FirmInstitutionName : string.Empty);
                strHtml = strHtml.Replace("[" + FieldsEditorBL.PRENOM_CGP_CONNECTE + "]",
                    userConnecte != null ? userConnecte.UserFirstName : string.Empty);
                strHtml = strHtml.Replace("[" + FieldsEditorBL.NOM_CGP_CONNECTE + "]",
                    userConnecte != null ? userConnecte.UserName : string.Empty);
            }
            else
            {
                strHtml = strHtml.Replace("[" + FieldsEditorBL.NOM_ETABLISSEMENT_CGP + "]",string.Empty);
                strHtml = strHtml.Replace("[" + FieldsEditorBL.PRENOM_CGP_CONNECTE + "]",string.Empty);
                strHtml = strHtml.Replace("[" + FieldsEditorBL.NOM_CGP_CONNECTE + "]",string.Empty);
            }


            var valDico = new Dictionary<string, string>();
            var fieldDico = new Dictionary<string, FieldValueModel>();


            var listNameKey = FieldValuesBL.GetAllNameKeyForMapping(documentModel.IdDocumentModel);
            listNameKey.ToList().ForEach(u => valDico.Add(u.NameKey, string.Empty));
            listNameKey.ToList().ForEach(u => fieldDico.Add(u.NameKey, u));
            var dico = FieldValuesBL.GetForMapping(idDocument);

            foreach (var item in dico)
            {
                valDico[item.Key] = item.Value;
            }

            foreach (var fv in valDico)
            {
                var value = fv.Value;
                var nk = fieldDico[fv.Key] ?? new FieldValueModel() { Value = string.Empty };
                var type = (nk != null && !string.IsNullOrEmpty(nk.Value)) ? nk.Value : "";

                switch (type)
                {
                    case "radio":
                    case "radiogroup":
                    case "civilite":
                        var rad_pattern = string.Format("ckvalue=\"{0}_{1}\"", fv.Key, value);
                        var rad_replace = "checked";
                        strHtml = strHtml.Replace(rad_pattern, rad_replace);
                        break;
                    case "checkbox":
                        var cbx_pattern = string.Format("value=\"[{0}]\"", fv.Key);
                        var cbx_replace = (value == "True") ? "checked" : "";
                        strHtml = strHtml.Replace(cbx_pattern, cbx_replace);
                        break;
                    case "ibanfield":
                        string[] ibanwords = value.Split(' ');
                        for (int i = 0; i < ibanwords.Length; i++)
                        {
                            var iban_pattern = string.Format("ibanvalue=\"{0}_{1}\"", fv.Key, i);
                            var iban_replace = string.Format("value=\"{0}\"", ibanwords[i]);  //ibanwords[i];
                            strHtml = strHtml.Replace(iban_pattern, iban_replace);
                        }
                        break;

                    case "numeric":
                        if(!String.IsNullOrEmpty(value)) 
                        {
                            decimal d = 0;
                            Decimal.TryParse(value.Replace('.',','), out d);
                            if (d > 0)
                            {
                                var f = new NumberFormatInfo { NumberGroupSeparator = " ", CurrencyDecimalDigits = 2 }; //TODO cultureInfo
                                value = d.ToString("n", f);
                            }
                        }
                        strHtml = strHtml.Replace("[" + fv.Key + "]", !string.IsNullOrEmpty(value) ? value : string.Empty);
                        break;

                    case "datetime":                        
                        if (!string.IsNullOrEmpty(value))
                        {
                            var dt = DateTime.MinValue;
                            DateTime.TryParse(value, CultureInfo.CreateSpecificCulture("Fr"), DateTimeStyles.None, out dt);
                            if (dt == DateTime.MinValue) 
                            {
                                DateTime.TryParse(value, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out dt);
                            }                            
                            if (dt != DateTime.MinValue)
                            {
                                value = dt.ToString("dd/MM/yyyy");
                            }
                        }
                        strHtml = strHtml.Replace("[" + fv.Key + "]", !string.IsNullOrEmpty(value) ? value : string.Empty);
                        break;
                    default:
                        strHtml = strHtml.Replace("[" + fv.Key + "]", !string.IsNullOrEmpty(value) ? value : string.Empty);
                        break;
                }

            }
            strHtml = strHtml.Replace("[logo]", logoUrl + "NextStatge.jpg");
            return strHtml;
        }
        public static IEnumerable<SubscriptionFileViewModel> GetInformationSubscriptionFilesCgp(Guid idUser, string letter = "tous", string search = "")
        {
            using (var ctx = new UpsilabEntities())
            {
                letter = letter.ToLower();
                search = search.ToLower();

                var SFCrit = Upsilab.Business.Document.ElectronicSafeDocumentBL.DocumentType.SF.ToString();
                var entity = (from sf in ctx.SubscriptionFile
                    from p in ctx.Product.Where(x => sf.IdProduct == x.IdProduct)
                    from fr in ctx.FirmInstitution.Where(x => x.idFirmInstitution == p.IdFirmInstitution)
                    from sg in ctx.SignatureTransaction.Where(x => sf.IdSignatureTransaction == x.idSignatureTransaction)
                    from ci in ctx.CustomerProspect.Where(x => x.idCustomer == sf.IdCustomerProspect1).DefaultIfEmpty()
                    from dc in ctx.Document.Where(x => x.idSignatureTransaction == sg.idSignatureTransaction)
                    from fv in ctx.FieldValue.Where(x => x.IdDocument == dc.idDocument).DefaultIfEmpty()
                    from fd in ctx.Fields.Where(x => x.IdField == fv.IdField).DefaultIfEmpty()
                    where (sf.IdUserCreated == idUser && dc.DocumentType == SFCrit && !sf.IsDeleted)
                    select new { sf,p,sg,fr,ci,dc,fv,fd} 
                ).ToList();

                List<SubscriptionFileModel> list = new List<SubscriptionFileModel>();
                if (entity != null)
                {
                    List<SubscriptionFileModel> sfLst = new List<SubscriptionFileModel>();
                    entity.ForEach(itm =>
                    {
                        if (!sfLst.Any(x => x.IdSubscriptionFile == itm.sf.IdSubscriptionFile))
                        {
                            var model = new SubscriptionFileModel();
                            model.Role = FrsRole.CGP;
                            model.IdSubscriptionFile = itm.sf.IdSubscriptionFile;
                            model.DateCreated = itm.sf.DateCreated;
                            model.SubmissionMode = itm.sf.SubmissionMode;
                            model.DatesReportsLab = itm.sf.DatesReportLab;
                            var st = new SignatureTransactionEntity();
                            st.IdSignatureTransaction = itm.sg.idSignatureTransaction;
                            st.Status = itm.sg.Status;
                            st.DateSignaturesObjet = itm.sg.DateSignaturesObjet;
                            model.SignatureTransaction = st;
                            var pt = new ProductModel();
                            pt.IdProduct = itm.p.IdProduct;
                            pt.Name = itm.p.Name;
                            var frm = new FirmInstitutionViewModel();
                            frm.IdFirmInstitution = itm.fr.idFirmInstitution;
                            frm.Email = itm.fr.E_mail;
                            frm.FirmInstitutionName = itm.fr.FirmInstitutionName;
                            pt.FirmInstitution = frm;
                            model.Product = pt;

                            var ui = new UserModel();
                            if (itm.fv != null && itm.fv.Fields != null)
                            {
                                ui.UserName = itm.fv.Fields.NameKey == NOM_SSC ? itm.fv.Value : string.Empty;
                                ui.UserFirstName = itm.fv.Fields.NameKey == PRENOM_SSC ? itm.fv.Value : string.Empty;
                                ui.UserMobilePhone = itm.fv.Fields.NameKey == MOBILE_SSC ? itm.fv.Value : string.Empty;
                                ui.IdDocument = itm.fv.IdDocument;
                            }
                            model.User = ui;
                            
                            sfLst.Add(model);
                        }
                        else
                        {
                            var item = sfLst.FirstOrDefault(x => x.IdSubscriptionFile == itm.sf.IdSubscriptionFile);
                            if (item != null)
                            {
                                if (item.User != null && itm.dc != null && item.User.IdDocument == itm.dc.idDocument)
                                {
                                    if (string.IsNullOrEmpty(item.User.UserName) && itm.fv.Fields.NameKey == NOM_SSC)
                                        item.User.UserName = itm.fv.Value;
                                    if (string.IsNullOrEmpty(item.User.UserFirstName) && itm.fv.Fields.NameKey == PRENOM_SSC)
                                        item.User.UserFirstName = itm.fv.Value;
                                    if (string.IsNullOrEmpty(item.User.UserMobilePhone) && itm.fv.Fields.NameKey == MOBILE_SSC)
                                        item.User.UserMobilePhone = itm.fv.Value;
                                }
                            }
                        }

                    });

                    #region "FILTER"

                    list = sfLst.ToList();

                    list.ForEach(delegate(SubscriptionFileModel sf)
                    {
                        sf.UserCgp = GetUserModelBySubscriptionFile(sf.IdSubscriptionFile);
                    });

                    if (!string.IsNullOrEmpty(letter) && letter.ToUpper() != "TOUS")
                    {
                        list =
                            list.Where(
                                x =>
                                    (x.User != null && x.User.UserName != null && x.User.UserFirstName != null &&
                                     (x.User.UserName.ToLower().StartsWith(letter) || x.User.UserFirstName.ToLower().StartsWith(letter))) ||
                                    (x.FirmInstitution != null && x.FirmInstitution.FirmInstitutionName.ToLower().StartsWith(letter))).ToList();
                    }
                    else if (!string.IsNullOrEmpty(search))
                    {
                        list = list.Where(x =>
                 (x.User != null && x.User.UserName != null && x.User.UserFirstName != null &&
                  (x.User.UserName.ToLower().Contains(search) || x.User.UserFirstName.ToLower().Contains(search))) ||
                 (x.FirmInstitution != null && x.FirmInstitution.FirmInstitutionName.ToLower().Contains(search))).ToList();
                    }
                    #endregion
                }
                

                return list.ToList().ToViewModel();
            }
        }
 public static FirmInstitutionViewModel GetFournisseurFirmInstitutionBySubscription(int idSubscriptionFile)
 {
     using (var ctx = new UpsilabEntities())
     {
         var firm = new FirmInstitutionViewModel();
         var entity = (from sf in ctx.SubscriptionFile
             from p in ctx.Product.Where(x => x.IdProduct == sf.IdProduct)
             from fm in ctx.FirmInstitution.Where(x => x.idFirmInstitution == p.IdFirmInstitution)
             where sf.IdSubscriptionFile == idSubscriptionFile
             select fm).ToList();
         if (entity != null && entity.Any())
         {
             var ent0 = entity.FirstOrDefault();
             firm.IdFirmInstitution = ent0.idFirmInstitution;
             firm.FirmInstitutionName = ent0.FirmInstitutionName;
             firm.Email = ent0.E_mail;
         }
         return firm;
     }
 }
        public static IEnumerable<SubscriptionFileViewModel> GetInformationSubscriptionFilesFrs(Guid idFirmInstitution, string letter = "tous", string search = "")
        {
            using (var ctx = new UpsilabEntities())
            {
                letter = letter.ToLower();
                search = search.ToLower();

                var SFCrit = Upsilab.Business.Document.ElectronicSafeDocumentBL.DocumentType.SF.ToString();
                var entity = (from sf in ctx.SubscriptionFile
                              from p in ctx.Product.Where(x => sf.IdProduct == x.IdProduct)
                              from cgp in ctx.User.Where(x => x.idUser == sf.IdUserCreated)
                              from sg in ctx.SignatureTransaction.Where(x => sf.IdSignatureTransaction == x.idSignatureTransaction)
                              from firm in ctx.FirmInstitution.Where(x => x.idFirmInstitution == p.IdFirmInstitution)
                              from ci in ctx.CustomerProspect.Where(x => x.idCustomer == sf.IdCustomerProspect1).DefaultIfEmpty()
                              from dc in ctx.Document.Where(x => x.idSignatureTransaction == sg.idSignatureTransaction)
                              from fv in ctx.FieldValue.Where(x => x.IdDocument == dc.idDocument).DefaultIfEmpty()
                              from fd in ctx.Fields.Where(x => x.IdField == fv.IdField).DefaultIfEmpty()
                              where (firm.idFirmInstitution == idFirmInstitution && dc.DocumentType == SFCrit && !sf.IsDeleted)
                              select new { sf,p,cgp,sg,firm,ci,dc,fv,fd}
            ).ToList();

                List<SubscriptionFileModel> list = new List<SubscriptionFileModel>();
                if (entity != null)
                {
                    List<SubscriptionFileModel> sfLst = new List<SubscriptionFileModel>();
                    var lst = new List<SubscriptionFileModel>();
                    entity.ForEach(x => {
                        var model = new SubscriptionFileModel();
                        model.Role = FrsRole.FRS;
                        model.IdSubscriptionFile = x.sf.IdSubscriptionFile;
                        model.DateCreated = x.sf.DateCreated;
                        model.SubmissionMode = x.sf.SubmissionMode;
                        model.DatesReportsLab = x.sf.DatesReportLab;
                        model.EmailUserCreator = x.cgp.UserEmail;

                        var signature = new SignatureTransactionEntity();
                        signature.IdSignatureTransaction = x.sg.idSignatureTransaction;
                        signature.Status = x.sg.Status;
                        signature.DateSignaturesObjet = x.sg.DateSignaturesObjet;
                        model.SignatureTransaction = signature;

                        var product = new ProductModel();
                        product.IdProduct = x.p.IdProduct;
                        product.Name = x.p.Name;
                        model.Product = product;

                        var user = new UserModel();
                        user.UserName = x.fv != null && x.fv.Fields != null && !string.IsNullOrEmpty(x.fv.Fields.NameKey) && x.fv.Fields.NameKey == NOM_SSC ? x.fv.Value : string.Empty;
                        user.UserFirstName = x.fv != null && x.fv.Fields != null && !string.IsNullOrEmpty(x.fv.Fields.NameKey) && x.fv.Fields.NameKey == PRENOM_SSC ? x.fv.Value : string.Empty;
                        user.UserMobilePhone = x.fv != null && x.fv.Fields != null && !string.IsNullOrEmpty(x.fv.Fields.NameKey) && x.fv.Fields.NameKey == MOBILE_SSC ? x.fv.Value : string.Empty;
                        user.IdDocument = x.fv != null ? x.fv.IdDocument : Guid.Empty;
                        model.User = user;

                        var firmInstitution = new FirmInstitutionViewModel();
                        firmInstitution.IdFirmInstitution = x.firm.idFirmInstitution;
                        firmInstitution.Email = x.firm.E_mail;
                        firmInstitution.FirmInstitutionName = x.firm.FirmInstitutionName;
                        model.FirmInstitution = firmInstitution;

                        if (x.ci != null)
                        {
                            var customerProspect = new CustomerProspectViewModel();
                            customerProspect.DateUpdatedLast = x.ci.DateUpdatedLast;
                            customerProspect.DateUpdatedNext = x.ci.DateUpdatedNext;
                            customerProspect.DateShiftLABLast = x.ci.DateShiftLABLast;
                            customerProspect.DateShiftLABNext = x.ci.DateShiftLABNext;
                            model.CustomerProspectTitulaire1 = customerProspect;
                        }

                        model.IdUserCgp = x.cgp.idUser;

                        lst.Add(model);
                    });

                    lst.ToList().ForEach(delegate(SubscriptionFileModel itm)
                    {
                        if (!sfLst.Any(x => x.IdSubscriptionFile == itm.IdSubscriptionFile))
                        {
                            sfLst.Add(itm);
                        }
                        else
                        {
                            var item = itm != null ? sfLst.FirstOrDefault(x => x.IdSubscriptionFile == itm.IdSubscriptionFile) : null;
                            if (item != null)
                            {
                                if (item.User != null && itm.User != null && item.User.IdDocument.HasValue && item.User.IdDocument != Guid.Empty && item.User.IdDocument == itm.User.IdDocument)
                                {
                                    if (string.IsNullOrEmpty(item.User.UserName))
                                        item.User.UserName = itm.User.UserName;
                                    if (string.IsNullOrEmpty(item.User.UserFirstName))
                                        item.User.UserFirstName = itm.User.UserFirstName;
                                    if (string.IsNullOrEmpty(item.User.UserMobilePhone))
                                        item.User.UserMobilePhone = itm.User.UserMobilePhone;
                                }
                            }
                        }

                    });

                    #region "FILTER"

                    list = sfLst.ToList();

                    list.ForEach(delegate(SubscriptionFileModel sf)
                    {
                        sf.UserCgp = GetUserModelBySubscriptionFile(sf.IdSubscriptionFile);
                    });

                    if (!string.IsNullOrEmpty(letter) && letter.ToUpper() != "TOUS")
                    {
                        list =
                            list.Where(
                                x =>
                                    (x.User != null && x.User.UserName != null && x.User.UserFirstName != null &&
                                     (x.User.UserName.ToLower().StartsWith(letter) || x.User.UserFirstName.ToLower().StartsWith(letter))) ||
                                    (x.FirmInstitution != null && x.FirmInstitution.FirmInstitutionName.ToLower().StartsWith(letter))).ToList();
                    }
                    else if (!string.IsNullOrEmpty(search))
                    {
                        list = list.Where(x =>
                 (x.User != null && x.User.UserName != null && x.User.UserFirstName != null &&
                  (x.User.UserName.ToLower().Contains(search) || x.User.UserFirstName.ToLower().Contains(search))) ||
                 (x.FirmInstitution != null && x.FirmInstitution.FirmInstitutionName.ToLower().Contains(search))).ToList();
                    }
                    #endregion
                }
                // lst = lst;

                
                
                return list.OrderBy(x => x.IdSubscriptionFile).ToViewModel();

            }
        }