// int ConnctionLongMaxQuerryTimeOut = 100;

        public SyncRepository(IHostingEnvironment environment, IConfiguration config) : base(environment, config)
        {
            _config             = config;
            _hostingEnvironment = environment;
            minio             = new MinioServices();
            _masterRepository = new MasterRepository(_hostingEnvironment, _config);
        }
        private async Task <bool> UpdatePathUrlFile(int TdefectId)
        {
            using (IDbConnection conn = WebConnection)
            {
                try
                {
                    string bucketName  = Environment.GetEnvironmentVariable("Minio_DefaultBucket") ?? UtilsProvider.AppSetting.MinioDefaultBucket;
                    var    queryString = String.Format(@"SELECT
	                                callResource.*
                                FROM
	                                dbo.callTDefectDetail
	                                INNER JOIN
	                                dbo.callResource
	                                ON 
		                                callTDefectDetail.TDefectDetailId = callResource.TDefectDetailId
                                WHERE
	                                callTDefectDetail.TDefectId = {0}"    , TdefectId.ToString());

                    var listResource = conn.Query <callResource>(queryString).ToList();

                    minio = new MinioServices();
                    foreach (var element in listResource)
                    {
                        element.FullFilePath = await minio.GetFileUrlAsync(bucketName, element.FilePath);

                        element.ExpirePathDate = DateTime.Now.AddDays(6);
                    }

                    conn.Open();
                    var tran = conn.BeginTransaction(IsolationLevel.ReadUncommitted);

                    var result = conn.Update(listResource, tran);
                    tran.Commit();
                    return(result);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        public async Task GenerateReport(ParamReportModel model)
        {
            try
            {
                var reportName = "";

                // V แนวสูง
                // H แนวราบ
                await UpdatePathUrlFile(model.TDefectId);

                string bucketName = Environment.GetEnvironmentVariable("Minio_DefaultBucket") ?? UtilsProvider.AppSetting.MinioDefaultBucket;
                minio = new MinioServices();
                bool insertPDF = false;
                List <callResource> Signature = _masterRepository.GetSignatureByTdefectID(model.TDefectId);
                string lcSigAf  = Signature.Where(w => w.ResourceTagCode == "SAL-LC-AF").Any() ? Signature.Where(w => w.ResourceTagCode == "SAL-LC-AF").FirstOrDefault().FilePath : null;
                string cusSigBf = Signature.Where(w => w.ResourceTagCode == "CUST-BF").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-BF").FirstOrDefault().FilePath : null;
                string cusSigAf = Signature.Where(w => w.ResourceTagCode == "CUST-AF").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-AF").FirstOrDefault().FilePath : null;
                string conSigBf = Signature.Where(w => w.ResourceTagCode == "CON-MGR-BF").Any() ? Signature.Where(w => w.ResourceTagCode == "CON-MGR-BF").FirstOrDefault().FilePath : null;
                string conSigAf = Signature.Where(w => w.ResourceTagCode == "CON-MGR-AF").Any() ? Signature.Where(w => w.ResourceTagCode == "CON-MGR-AF").FirstOrDefault().FilePath : null;
                string cusSigRe = Signature.Where(w => w.ResourceTagCode == "CUST-RECE").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-RECE").FirstOrDefault().FilePath : null;

                var listCus = new List <string>()
                {
                    "CUST-BF", "CUST-AF", "CUST-RECE"
                };
                var orderCusSignature = Signature.Where(w => listCus.Contains(w.ResourceTagCode)).OrderBy(o => o.CreateDate).ToList();

                var dateCusSigBf = Signature.Where(w => w.ResourceTagCode == "CUST-BF").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-BF").FirstOrDefault().CreateDate : null;
                var dateCusSigAf = Signature.Where(w => w.ResourceTagCode == "CUST-AF").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-AF").FirstOrDefault().CreateDate : null;
                var dateCusSigRe = Signature.Where(w => w.ResourceTagCode == "CUST-RECE").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-RECE").FirstOrDefault().CreateDate : null;

                string cusBfDatetime = "";
                string cusAfDatetime = "";
                string cusReDatetime = "";

                if (dateCusSigBf != null)
                {
                    cusBfDatetime = dateCusSigBf.Value.ToString("dd/MM/yyyy");
                }

                if (dateCusSigAf != null)
                {
                    cusAfDatetime = dateCusSigAf.Value.ToString("dd/MM/yyyy");
                }

                if (dateCusSigRe != null)
                {
                    cusReDatetime = string.Format("ลูกค้าเช็นต์รับบ้านแล้ว {0}", dateCusSigRe.Value.ToString("dd/MM/yyyy"));
                }


                string alternativeDate = "";
                var    indexCusRe      = orderCusSignature.FindIndex(w => w.ResourceTagCode == "CUST-RECE");
                if (indexCusRe != 0 && indexCusRe != -1)
                {
                    if (orderCusSignature[indexCusRe - 1].ResourceTagCode == "CUST-BF")
                    {
                        alternativeDate = string.Format("ลูกค้าเช็นต์ก่อนซ่อมแล้ว {0}", cusBfDatetime);
                    }

                    if (orderCusSignature[indexCusRe - 1].ResourceTagCode == "CUST-AF")
                    {
                        alternativeDate = string.Format("ลูกค้าเช็นต์หลังซ่อมแล้ว {0}", cusAfDatetime);
                    }
                }

                if (model.ProjectType.Equals("V"))
                {
                    if (model.SignatureType == "CUST-BF")
                    {
                        reportName = "RPT_ReceiveUnit_Vertical_CUST_BF";
                    }
                    else if (model.SignatureType == "CUST-AF")
                    {
                        reportName = "RPT_ReceiveUnit_Vertical_CUST_AF";
                    }
                    else
                    {
                        reportName = "RPT_ReceiveUnit_Vertical_CUST_RECE";
                    }
                }
                else
                {
                    if (model.SignatureType == "CUST-BF")
                    {
                        reportName = "RPT_ReceiveUnit_Horizontal_CUST_BF";
                    }
                    else if (model.SignatureType == "CUST-AF")
                    {
                        reportName = "RPT_ReceiveUnit_Horizontal_CUST_AF";
                    }
                    else
                    {
                        reportName = "RPT_ReceiveUnit_Horizontal_CUST_RECE";
                    }
                }

                string lcSigAffilePath = String.IsNullOrEmpty(lcSigAf) ? null : await minio.GetFileUrlAsync(bucketName, lcSigAf);

                string cusSigBfFilePath = String.IsNullOrEmpty(cusSigBf) ? null : await minio.GetFileUrlAsync(bucketName, cusSigBf);

                string cusSigAfFilePath = String.IsNullOrEmpty(cusSigAf) ? null : await minio.GetFileUrlAsync(bucketName, cusSigAf);

                string conSigBfFilePath = String.IsNullOrEmpty(conSigBf) ? null : await minio.GetFileUrlAsync(bucketName, conSigBf);

                string conSigAfFilePath = String.IsNullOrEmpty(conSigAf) ? null : await minio.GetFileUrlAsync(bucketName, conSigAf);

                string cusSigReFilePath = String.IsNullOrEmpty(cusSigRe) ? null : await minio.GetFileUrlAsync(bucketName, cusSigRe);

                var requestMode = new RequestReportModel()
                {
                    Folder       = "defect",
                    FileName     = reportName,
                    Server       = Environment.GetEnvironmentVariable("ReportServer") ?? UtilsProvider.AppSetting.ReportServer,
                    DatabaseName = Environment.GetEnvironmentVariable("ReportDataBase") ?? UtilsProvider.AppSetting.ReportDataBase,
                    UserName     = Environment.GetEnvironmentVariable("ReportUserName") ?? UtilsProvider.AppSetting.ReportUserName,
                    Password     = Environment.GetEnvironmentVariable("ReportPassword") ?? UtilsProvider.AppSetting.ReportPassword,
                    Parameters   = new List <ParameterReport>()
                    {
                        new ParameterReport()
                        {
                            Name = "@TDefectId", Value = model.TDefectId.ToString()
                        },
                        new ParameterReport()
                        {
                            Name = "@CustRoundAuditNo", Value = "1"
                        },
                        new ParameterReport()
                        {
                            Name = "@CON_MGR_AF_URL", Value = conSigAfFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@CON_MGR_BF_URL", Value = conSigBfFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@CUST_AF_URL", Value = cusSigAfFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@CUST_BF_URL", Value = cusSigBfFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@CUST_RECE", Value = cusSigReFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@SAL_LC_AF", Value = lcSigAffilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@ALTERNATIVE_DATE", Value = alternativeDate
                        },
                        new ParameterReport()
                        {
                            Name = "@CUS_RECE_SIGN_DATE", Value = cusReDatetime
                        }
                    }
                };
                ResponsetReportModel resultObject = new ResponsetReportModel();
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = new TimeSpan(0, 0, 1000);
                    var urlReport = Environment.GetEnvironmentVariable("ReportURL") ?? UtilsProvider.AppSetting.ReportURL;
                    var reportKey = Environment.GetEnvironmentVariable("ReportKey") ?? UtilsProvider.AppSetting.ReportKey;
                    var Content   = new StringContent(JsonConvert.SerializeObject(requestMode));
                    Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    Content.Headers.Add("api_accesskey", reportKey);
                    var response = await client.PostAsync(urlReport, Content);

                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        var result = await response.Content.ReadAsStringAsync();

                        resultObject = JsonConvert.DeserializeObject <ResponsetReportModel>(result);
                    }
                    client.Dispose();
                }
                await Task.Delay(3000);

                long sizeFile = 0;
                var  fullUrl  = "";
                var  path     = $"{model.ProjectCode}/{model.UnitNo}/DefectDocument";
                if (resultObject.Success)
                {
                    using (HttpClient client = new HttpClient())
                    {
                        HttpResponseMessage resDownload = await client.GetAsync(resultObject.URL.ToString()).ConfigureAwait(false);

                        HttpContent content = resDownload.Content;

                        // ... Read the string.
                        var result = await content.ReadAsByteArrayAsync().ConfigureAwait(false);

                        Stream stream = new MemoryStream(result);
                        var    file   = new FormFile(stream, 0, stream.Length, null, resultObject.FileName)
                        {
                            Headers     = new HeaderDictionary(),
                            ContentType = "application/pdf"
                        };
                        sizeFile = file.Length;
                        var resultMinio = await minio.UploadFile(file, path, resultObject.FileName);

                        fullUrl = resultMinio.Url;

                        client.Dispose();
                    }

                    callResource callResourcePDF = new callResource();
                    callResourcePDF.FilePath           = $"{path}/{resultObject.FileName}";
                    callResourcePDF.FileLength         = sizeFile;
                    callResourcePDF.CreateDate         = DateTime.Now;
                    callResourcePDF.RowState           = "Original";
                    callResourcePDF.ResourceType       = 8;
                    callResourcePDF.ResourceTagCode    = "1";
                    callResourcePDF.ResourceTagSubCode = "1";
                    callResourcePDF.ResourceGroupSet   = null;
                    callResourcePDF.StorageServerId    = 1400;
                    callResourcePDF.ResourceGroupOrder = 0;
                    callResourcePDF.TDefectDetailId    = 0;
                    callResourcePDF.TDefectId          = (int)model.TDefectId;
                    callResourcePDF.ProjectNo          = model.ProjectCode;
                    callResourcePDF.SerialNo           = model.UnitNo;
                    callResourcePDF.Active             = true;
                    callResourcePDF.FullFilePath       = fullUrl;
                    callResourcePDF.UserId             = model.EmpCode;
                    callResourcePDF.ExpirePathDate     = DateTime.Now.AddDays(6);;
                    insertPDF = InsertCallResource(callResourcePDF);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }