using BPMService.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;					   
using System.Threading.Tasks;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Controllers.Master.Lot;
using WK_KLI_LAPS_Service.Models.Configuration;
using WK_KLI_LAPS_Service.Models.Master;

namespace WK_KLI_LAPS_Service.Controllers.Configuration.Job
{
    [EnableCors("CorsPolicy")]
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class JobConfigurationApiController : ControllerBase
    {
        CommonRepository oCommonRepository = new CommonRepository();
        MasterRepository oMasterRepository = new MasterRepository();

        private IJobConfigurationService _JobConfigurationservices;
        public JobConfigurationApiController(IJobConfigurationService JobConfigurationServices)
        {
            _JobConfigurationservices = JobConfigurationServices;
        }
        static string Job_Creation_mailtemplate_id = Startup.Configuration.GetValue<string>("AppSettings:Job_Creation_mailtemplate");
        static string from_mail = Startup.Configuration.GetValue<string>("AppSettings:emailusername");
        static string from_mail_pwd = Startup.Configuration.GetValue<string>("AppSettings:emailpassword");
        static string mail_host = Startup.Configuration.GetValue<string>("AppSettings:emailhost");
        static string from_port = Startup.Configuration.GetValue<string>("AppSettings:emailportid");
        static string mail_header = Startup.Configuration.GetValue<string>("AppSettings:from_mail_header");
        static string OLUA_Workflow = Startup.Configuration.GetValue<string>("AppSettings:OLUA_Workflow");
        [Authorize]
        [HttpGet]
        //Code to retrieve all data
        public IActionResult GetAll()
        {
            var _list = _JobConfigurationservices.GetAll();
            return Ok(_list);
        }

        [Authorize]
        [HttpGet("getProjectCode")]
        //Code to retrieve active data
        public IActionResult GetProjectCode()
        {
            var _list = _JobConfigurationservices.GetProjectCode();
            return Ok(_list);
        }


        [Authorize]
        [HttpGet("GetProductType")]
        //Code to retrieve active data
        public IActionResult GetProductType(string projectid)
        {
            var _list = _JobConfigurationservices.GetProductType(projectid);
            return Ok(_list);
        }


        [Authorize]
        [HttpGet("GetJobNo")]
        //Code to retrieve active data
        public IActionResult GetJobNo(string projectid, string projectdefinitionid)
        {
            var _list = _JobConfigurationservices.GetJobNo(projectid, projectdefinitionid);
            return Ok(_list);
        }


        //Code to add new record
        [Authorize]
        [HttpPost("add")]
        public IActionResult Add([FromBody] jobModel ojobModel)
        {

            int retval = 0;
            try
            {
                retval = _JobConfigurationservices.Add(ojobModel);
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }
        [Authorize]
        [HttpPost("GetExcelTemplate")]
        public async Task<IActionResult> GetExcelTemplate(string projectid, string projecdefid)
        {
            string error = string.Empty;
            byte[] file = null;
            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission(projecdefid))
            {
                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                {
                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                    System.Console.WriteLine(useri.Name);
                    var data = new
                    {
                        transactionid = projecdefid,
                        lotid = 0,
                        option = "serverinfo_projid"
                    };
                    string inputstr = JsonConvert.SerializeObject(data);
                    var ds = oCommonRepository.ExecuteSP_ReturnListForLot("spusrserverpathinfo", inputstr, "serverinfo_projid");
                    string serverpath = FormatPath(ds.serverpath);
                    string foldername = string.Concat("ExcelTemplate");
                    string serverpath1 = Path.Combine(serverpath, foldername);
                    if (!Directory.Exists(serverpath1)) error = "Directory does not exists";
                    //return BadRequest(new { message = "Directory does not exists" });
                    if (string.IsNullOrEmpty(error))
                    {
                        string spath = Path.Combine(serverpath1, "exceltemplate.xlsx");
                        if (!System.IO.File.Exists(spath)) error = "File does not exists";
                        //return BadRequest(new { message = "File does not exists" });
                        if (string.IsNullOrEmpty(error)) file = System.IO.File.ReadAllBytes(spath);
                    }
                });
                if (!string.IsNullOrEmpty(error))
                {
                    return BadRequest(new { message = error });
                }
                return Ok(new
                {
                    file_ = file
                });

            }
        }
        /**UAT in  OLUA**/
        [Authorize]
        [HttpPost("Addexceljob")]
        public IActionResult Addexceljob()
        {
            string sFilePath = string.Empty;
            var retval = new List<int>();
            try
            {
                string fileName = string.Empty;
                jobModel ojobModel = new jobModel();
                List<jobinfoexcellist> joblist = new List<jobinfoexcellist>();
                string jobid_mul = string.Empty;
                var httpRequest = HttpContext.Request.Form;
                ojobModel.jobstatus = Request.Form["jobstatus"].ToString();
                ojobModel.isreadyforpurge = Convert.ToInt32(Request.Form["isreadyforpurge"].ToString());
                ojobModel.totallots = Convert.ToInt32(Request.Form["totallots"].ToString());
                ojobModel.jobkey = Request.Form["jobkey"].ToString();
                ojobModel.projectdefinitionid = Convert.ToInt64(Request.Form["projectdefinitionid"].ToString());
                ojobModel.projectid = Convert.ToInt32(Request.Form["projectid"].ToString());
                ojobModel.createdby = Convert.ToInt32(Request.Form["createdby"].ToString());
                int jobno = Convert.ToInt32(Request.Form["jobno"].ToString());
                jobmetaModel lst = new jobmetaModel();
                lst.projectdefinitionid = Convert.ToInt32(ojobModel.projectdefinitionid);
                string inputjobmeta = JsonConvert.SerializeObject(lst);
                string metafieldlst = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spjobmetamasterselect", inputjobmeta, "getprojectmappedexcelmeta"));
                metafieldlst = metafieldlst.Replace("\\\"", "\"");
                if (string.IsNullOrEmpty(metafieldlst) || metafieldlst == "null")
                {
                    return BadRequest(new { message = "Kindly add the Meta data" });
                }
                DataTable dtmetafieldlst = oCommonRepository.JsonStringToDataTable(metafieldlst);
                if (dtmetafieldlst.Rows.Count == 0)
                {
                    return BadRequest(new { message = "Kindly check the Meta data master" });
                }
                if (HttpContext.Request.Form.Files.Count > 0)
                {
                    for (int file = 0; file < HttpContext.Request.Form.Files.Count; file++)
                    {
                        var FileDataContent = HttpContext.Request.Form.Files[file];
                        if (FileDataContent != null && FileDataContent.Length > 0)
                        {
                            //take the input stream, and save it to a temp folder using the original file.part name posted
                            var stream = FileDataContent;
                            string[] col = Path.GetFileName(FileDataContent.FileName).Split('~');
                            fileName = col[0];
                            //getting state and frequency list
                            string s = JsonConvert.SerializeObject(oMasterRepository.GetActive("statecode"));
                            s = s.Replace("\\\"", "\"");
                            DataTable dts = oCommonRepository.JsonStringToDataTable(s);
                            string f = JsonConvert.SerializeObject(oMasterRepository.GetActive("frequency"));
                            f = f.Replace("\\\"", "\"");
                            DataTable dtf = oCommonRepository.JsonStringToDataTable(f);

                            string msg = string.Empty;
                            //file copy into server
                            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission(Request.Form["projectdefinitionid"].ToString()))
                            {
                                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                                {
                                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                                    System.Console.WriteLine(useri.Name);

                                    var data = new
                                    {
                                        transactionid = Request.Form["projectdefinitionid"].ToString(),
                                        lotid = 0,
                                        option = "serverinfo_projid"
                                    };
                                    string inputstr = JsonConvert.SerializeObject(data);
                                    var ds = oCommonRepository.ExecuteSP_ReturnListForLot("spusrserverpathinfo", inputstr, "serverinfo_projid");
                                    string serverpath = FormatPath(ds.serverpath);
                                    string foldername = string.Concat("LotInfoExcel-", DateTime.Now.ToString("ddMMyy"));
                                    string serverpath1 = Path.Combine(serverpath, foldername);
                                    if (!Directory.Exists(serverpath1))
                                        Directory.CreateDirectory(serverpath1);

                                    sFilePath = Path.Combine(serverpath1, fileName.ToString());
                                    if (System.IO.File.Exists(sFilePath))
                                    {
                                        System.IO.File.Delete(sFilePath);
                                    }
                                    try
                                    {
                                        using (var fileStream = System.IO.File.Create(sFilePath))
                                        {
                                            stream.CopyTo(fileStream);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message.ToString());
                                        throw;
                                    }

                                    string stcode = string.Empty;
                                    string frcode = string.Empty;
                                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                                    //getting excel content
                                    using (ExcelPackage package = new ExcelPackage(new FileInfo(sFilePath)))
                                    {
                                        ExcelWorksheet worksheet = null;
                                        worksheet = package.Workbook.Worksheets["sheet1"];
                                        int colCount = worksheet.Dimension.End.Column;  //get Column Count
                                        int rowCount = worksheet.Dimension.End.Row;     //get row count
                                        if (colCount != 0 && colCount != null && rowCount != 0 && rowCount != null)
                                        {
                                            //Response.Headers.Add("Content-Type", "text/event-stream");		  
                                            for (int row = 2; row <= rowCount; row++)
                                            {
                                                jobinfoexcellist jobitem = new jobinfoexcellist();
                                                if (joblist.Count > 0)
                                                {
                                                    for (int i = 0; i < joblist.Count; i++)
                                                    {
                                                        if (worksheet.Cells[row, 5].Value != null && worksheet.Cells[row, 7].Value != null)
                                                        {
                                                            var itemlist_ = joblist.Find(x => x.Frequency.ToLower().Equals(worksheet.Cells[row, 5].Value?.ToString().Trim().ToLower()) && x.State.ToLower().Equals(worksheet.Cells[row, 7].Value?.ToString().Trim().ToLower()));
                                                            if (itemlist_ == null)
                                                            {
                                                                jobitem.Frequency = worksheet.Cells[row, 5].Value?.ToString().Trim();
                                                                jobitem.State = worksheet.Cells[row, 7].Value?.ToString().Trim();
                                                                if (dts.Rows.Count > 0 && dtf.Rows.Count > 0)
                                                                {
                                                                    for (int k = 0; k < dts.Rows.Count; k++)
                                                                    {
                                                                        if (jobitem.State.ToLower() == dts.Rows[k]["statename"].ToString().ToLower())
                                                                        {
                                                                            stcode = dts.Rows[k]["statecodeid"].ToString();
                                                                            break;
                                                                        }
                                                                    }
                                                                    for (int l = 0; l < dtf.Rows.Count; l++)
                                                                    {
                                                                        if (jobitem.Frequency.ToLower() == dtf.Rows[l]["frequencytype"].ToString().ToLower())
                                                                        {
                                                                            frcode = dtf.Rows[l]["frequencyid"].ToString();
                                                                            break;
                                                                        }
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
                                                                }
                                                                if (!string.IsNullOrEmpty(frcode) && !string.IsNullOrEmpty(stcode))
                                                                {
                                                                    joblist.Add(jobitem);
                                                                }
                                                                else
                                                                {
                                                                    msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            msg = "Job creation failed due to invalid input Excel format.";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    jobitem.Frequency = worksheet.Cells[row, 5].Value?.ToString().Trim();
                                                    jobitem.State = worksheet.Cells[row, 7].Value?.ToString().Trim();
                                                    if (dts.Rows.Count > 0 && dtf.Rows.Count > 0)
                                                    {

                                                        if (!string.IsNullOrEmpty(jobitem.State) && !string.IsNullOrEmpty(jobitem.Frequency))
                                                        {
                                                            for (int k = 0; k < dts.Rows.Count; k++)
                                                            {
                                                                if (jobitem.State.ToLower() == dts.Rows[k]["statename"].ToString().ToLower())
                                                                {
                                                                    stcode = dts.Rows[k]["statecodeid"].ToString();
                                                                    break;
                                                                }
                                                            }
                                                            for (int l = 0; l < dtf.Rows.Count; l++)
                                                            {
                                                                if (jobitem.Frequency.ToLower() == dtf.Rows[l]["frequencytype"].ToString().ToLower())
                                                                {
                                                                    frcode = dtf.Rows[l]["frequencyid"].ToString();
                                                                    break;
                                                                }
                                                            }
                                                            if (!string.IsNullOrEmpty(frcode) && !string.IsNullOrEmpty(stcode))
                                                            {
                                                                joblist.Add(jobitem);
                                                            }
                                                            else
                                                            {
                                                                msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
                                                            }
                                                        }
                                                        else
                                                        {
                                                            msg = "Kindly Fill Mandatory Field.";
                                                        }

                                                    }
                                                    else
                                                    {
                                                        msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
                                                    }

                                                }
                                            }
                                        }
                                        else
                                        {
                                            msg = "Job creation failed due to invalid input Excel format.";
                                        }

                                        //tas
                                        //Response.Headers.Add("Content-Type", "text/event-stream");
                                        for (int j = 0; j < joblist.Count; j++)
                                        {
                                            //job insertion
                                            ojobModel.statename = joblist[j].State;
                                            ojobModel.frequencytype = joblist[j].Frequency;
                                            if (!string.IsNullOrEmpty(stcode) && !string.IsNullOrEmpty(frcode))
                                            {
                                                //jobid_mul = "1579,1580";
                                                //tas
                                                int retval1 = _JobConfigurationservices.Addjobandjobcofig(ojobModel);
                                                // int retval1 = 1580;
                                                if (string.IsNullOrEmpty(jobid_mul))
                                                {
                                                    jobid_mul = retval1.ToString();
                                                }
                                                else
                                                {
                                                    jobid_mul = jobid_mul + "," + retval1.ToString();
                                                }
                                                //adding lot
                                                for (int row = 2; row <= rowCount; row++)
                                                {
                                                    bool st = false;
                                                    bool ft = false;
                                                    if (worksheet.Cells[row, 5].Value?.ToString().Trim().ToLower() == joblist[j].Frequency.ToLower())
                                                        ft = true;

                                                    if (worksheet.Cells[row, 7].Value?.ToString().Trim().ToLower() == joblist[j].State.ToLower())
                                                        st = true;
                                                    if (ft && st)
                                                    {
                                                        List<lotmetafields> metafieldslst = new List<lotmetafields>();
                                                        //For lot metafields
                                                        for (int coln = 2; coln <= colCount; coln++)
                                                        {
                                                            lotmetafields metafields = new lotmetafields();
                                                            for (int i = 0; i < dtmetafieldlst.Rows.Count; i++)
                                                            {
                                                                if ((dtmetafieldlst.Rows[i]["jobmeta"].ToString().ToLower() == worksheet.Cells[1, coln].Value?.ToString().Trim().ToLower()) || (dtmetafieldlst.Rows[i]["jobmeta"].ToString().ToLower() + "*" == worksheet.Cells[1, coln].Value?.ToString().Trim().ToLower()))
                                                                {
                                                                    metafields.FieldName = dtmetafieldlst.Rows[i]["jobmeta"].ToString();
                                                                    metafields.FieldValue = worksheet.Cells[row, coln].Value?.ToString().Trim();
                                                                    metafields.isexcelmeta = true;
                                                                    metafieldslst.Add(metafields);
                                                                }
                                                            }
                                                        }
                                                        //add lot
                                                        lotmasterModel olotmaster = new lotmasterModel();
                                                        olotmaster.lotmastermetafields = JsonConvert.SerializeObject(metafieldslst);
                                                        olotmaster.jobid = retval1;
                                                        olotmaster.createdby = ojobModel.createdby;
                                                        foreach (var item in metafieldslst)
                                                        {
                                                            if (item.FieldName == "Company Name")
                                                            {
                                                                olotmaster.companyname = item.FieldValue;
                                                            }
                                                            else if (item.FieldName == "Type")
                                                            {
                                                                olotmaster.type = item.FieldValue;
                                                            }
                                                            else if (item.FieldName == "Ranking")
                                                            {
                                                                olotmaster.ranking = item.FieldValue;
                                                            }
                                                            else if (item.FieldName == "State")
                                                            {
                                                                olotmaster.state = item.FieldValue;
                                                            }
                                                            else if (item.FieldName == "Follow Up Date")
                                                            {
                                                                olotmaster.followupdate = item.FieldValue;
                                                            }
                                                            else if (item.FieldName == "Frequency")
                                                            {
                                                                olotmaster.frequency = item.FieldValue;
                                                            }
                                                            else if (item.FieldName == "City")
                                                            {
                                                                olotmaster.city = item.FieldValue;
                                                            }
                                                        }
                                                        olotmaster.option = "insertlot";
                                                        string inputstr1 = JsonConvert.SerializeObject(olotmaster);
                                                        //tas
                                                        //  var retval_ = "1345";
                                                        var retval_ = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr1, olotmaster.option);
                                                    }
                                                }
                                                retval.Add(retval1);
                                                //added by monicaa
                                                //var eventMessage = $",{retval.Count}/{joblist.Count}\n\n";
                                                //                                     var bytes = Encoding.UTF8.GetBytes(eventMessage);

                                                //                                      Response.Body.WriteAsync(bytes, 0, bytes.Length);
                                                //                                      Response.Body.FlushAsync();
                                                //                                      Thread.Sleep(1000);
                                            }
                                            else
                                            {
                                                msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
                                            }
                                        }
                                        //send email
                                        createmail(jobid_mul, Convert.ToInt64(Request.Form["createdby"].ToString()));
                                    }
                                });

                                if (msg != string.Empty)
                                    return BadRequest(new { message = msg });
                            }
                        }
                    }
                }
                else
                {
                    ojobModel.oluaworkflow = Convert.ToBoolean(Request.Form["oluaworkflow"]);
                    //job insertion
                    ojobModel.statename = OLUA_Workflow;
                    int retval1 = _JobConfigurationservices.Addjobandjobcofig(ojobModel);
                    jobid_mul = retval1.ToString();
                    int nooflot = Convert.ToInt32(Request.Form["totallots"].ToString());
                    if (nooflot > 0)
                    {
                        for (int k = 0; k < nooflot; k++)
                        {
                            //add lot
                            lotmasterModel olotmaster = new lotmasterModel();
                            olotmaster.jobid = retval1;
                            olotmaster.createdby = ojobModel.createdby;
                            olotmaster.option = "updateandisertlot";
                            string inputstr1 = JsonConvert.SerializeObject(olotmaster);
                            var retval_ = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr1, olotmaster.option);
                        }
                        retval.Add(retval1);
                    }
                }
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                //return BadRequest(new { message = "Job Creation Failed" });
                return BadRequest(new { message = ex.Message.ToString() });
            }

        }
        /**Live in  OLUA**/
        //[Authorize]
        //[HttpPost("Addexceljob")]
        //public IActionResult Addexceljob()
        //{
        //    string sFilePath = string.Empty;
        //    var retval = new List<int>();
        //    try
        //    {
        //        string fileName = string.Empty;
        //        jobModel ojobModel = new jobModel();
        //        List<jobinfoexcellist> joblist = new List<jobinfoexcellist>();
        //        var httpRequest = HttpContext.Request.Form;
        //        for (int file = 0; file < HttpContext.Request.Form.Files.Count; file++)
        //        {
        //            var FileDataContent = HttpContext.Request.Form.Files[file];
        //            if (FileDataContent != null && FileDataContent.Length > 0)
        //            {
        //                // take the input stream, and save it to a temp folder using the original file.part name posted
        //                var stream = FileDataContent;
        //                string[] col = Path.GetFileName(FileDataContent.FileName).Split('~');
        //                fileName = col[0];
        //                ojobModel.jobstatus = Request.Form["jobstatus"].ToString();
        //                ojobModel.isreadyforpurge = Convert.ToInt32(Request.Form["isreadyforpurge"].ToString());
        //                ojobModel.totallots = Convert.ToInt32(Request.Form["totallots"].ToString());
        //                ojobModel.jobkey = Request.Form["jobkey"].ToString();
        //                ojobModel.projectdefinitionid = Convert.ToInt64(Request.Form["projectdefinitionid"].ToString());
        //                ojobModel.projectid = Convert.ToInt32(Request.Form["projectid"].ToString());
        //                ojobModel.createdby = Convert.ToInt32(Request.Form["createdby"].ToString());
        //                int jobno = Convert.ToInt32(Request.Form["jobno"].ToString());

        //                //getting state and frequency list
        //                string s = JsonConvert.SerializeObject(oMasterRepository.GetActive("statecode"));
        //                s = s.Replace("\\\"", "\"");
        //                DataTable dts = oCommonRepository.JsonStringToDataTable(s);
        //                string f = JsonConvert.SerializeObject(oMasterRepository.GetActive("frequency"));
        //                f = f.Replace("\\\"", "\"");
        //                DataTable dtf = oCommonRepository.JsonStringToDataTable(f);
        //                jobmetaModel lst = new jobmetaModel();
        //                lst.projectdefinitionid = Convert.ToInt32(ojobModel.projectdefinitionid);
        //                string inputjobmeta = JsonConvert.SerializeObject(lst);
        //                string metafieldlst = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spjobmetamasterselect", inputjobmeta, "getprojectmappedexcelmeta"));
        //                metafieldlst = metafieldlst.Replace("\\\"", "\"");
        //                if (string.IsNullOrEmpty(metafieldlst) || metafieldlst == "null")
        //                {
        //                    return BadRequest(new { message = "Kindly add the Meta data" });
        //                }
        //                DataTable dtmetafieldlst = oCommonRepository.JsonStringToDataTable(metafieldlst);
        //                if (dtmetafieldlst.Rows.Count == 0)
        //                {
        //                    return BadRequest(new { message = "Kindly check the Meta data master" });
        //                }
        //                string msg = string.Empty;
        //                //file copy into server
        //                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission(Request.Form["projectdefinitionid"].ToString()))
        //                {
        //                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

        //                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
        //                    {
        //                        WindowsIdentity useri = WindowsIdentity.GetCurrent();
        //                        System.Console.WriteLine(useri.Name);

        //                        var data = new
        //                        {
        //                            transactionid = Request.Form["projectdefinitionid"].ToString(),
        //                            lotid = 0,
        //                            option = "serverinfo_projid"
        //                        };
        //                        string inputstr = JsonConvert.SerializeObject(data);
        //                        var ds = oCommonRepository.ExecuteSP_ReturnListForLot("spusrserverpathinfo", inputstr, "serverinfo_projid");
        //                        string serverpath = FormatPath(ds.serverpath);
        //                        string foldername = string.Concat("LotInfoExcel-", DateTime.Now.ToString("ddMMyy"));
        //                        string serverpath1 = Path.Combine(serverpath, foldername);
        //                        if (!Directory.Exists(serverpath1))
        //                            Directory.CreateDirectory(serverpath1);

        //                        sFilePath = Path.Combine(serverpath1, fileName.ToString());
        //                        if (System.IO.File.Exists(sFilePath))
        //                        {
        //                            System.IO.File.Delete(sFilePath);
        //                        }
        //                        try
        //                        {
        //                            using (var fileStream = System.IO.File.Create(sFilePath))
        //                            {
        //                                stream.CopyTo(fileStream);
        //                            }
        //                        }
        //                        catch (Exception ex)
        //                        {
        //                            Console.WriteLine(ex.Message.ToString());
        //                            throw;
        //                        }

        //                        string stcode = string.Empty;
        //                        string frcode = string.Empty;
        //                        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
        //                        //getting excel content
        //                        using (ExcelPackage package = new ExcelPackage(new FileInfo(sFilePath)))
        //                        {
        //                            ExcelWorksheet worksheet = null;
        //                            worksheet = package.Workbook.Worksheets["sheet1"];
        //                            int colCount = worksheet.Dimension.End.Column;  //get Column Count
        //                            int rowCount = worksheet.Dimension.End.Row;     //get row count
        //                            if (colCount != 0 && colCount != null && rowCount != 0 && rowCount != null)
        //                            {
        //                                for (int row = 2; row <= rowCount; row++)
        //                                {
        //                                    jobinfoexcellist jobitem = new jobinfoexcellist();
        //                                    if (joblist.Count > 0)
        //                                    {
        //                                        for (int i = 0; i < joblist.Count; i++)
        //                                        {
        //                                            if (worksheet.Cells[row, 5].Value != null && worksheet.Cells[row, 7].Value != null)
        //                                            {
        //                                                var itemlist_ = joblist.Find(x => x.Frequency.ToLower().Equals(worksheet.Cells[row, 5].Value?.ToString().Trim().ToLower()) && x.State.ToLower().Equals(worksheet.Cells[row, 7].Value?.ToString().Trim().ToLower()));
        //                                                if (itemlist_ == null)
        //                                                {
        //                                                    jobitem.Frequency = worksheet.Cells[row, 5].Value?.ToString().Trim();
        //                                                    jobitem.State = worksheet.Cells[row, 7].Value?.ToString().Trim();
        //                                                    if (dts.Rows.Count > 0 && dtf.Rows.Count > 0)
        //                                                    {
        //                                                        for (int k = 0; k < dts.Rows.Count; k++)
        //                                                        {
        //                                                            if (jobitem.State.ToLower() == dts.Rows[k]["statename"].ToString().ToLower())
        //                                                            {
        //                                                                stcode = dts.Rows[k]["statecodeid"].ToString();
        //                                                                break;
        //                                                            }
        //                                                        }
        //                                                        for (int l = 0; l < dtf.Rows.Count; l++)
        //                                                        {
        //                                                            if (jobitem.Frequency.ToLower() == dtf.Rows[l]["frequencytype"].ToString().ToLower())
        //                                                            {
        //                                                                frcode = dtf.Rows[l]["frequencyid"].ToString();
        //                                                                break;
        //                                                            }
        //                                                        }
        //                                                    }
        //                                                    else
        //                                                    {
        //                                                        msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
        //                                                    }
        //                                                    if (!string.IsNullOrEmpty(frcode) && !string.IsNullOrEmpty(stcode))
        //                                                    {
        //                                                        joblist.Add(jobitem);
        //                                                    }
        //                                                    else
        //                                                    {
        //                                                        msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
        //                                                    }
        //                                                }
        //                                            }
        //                                            else
        //                                            {
        //                                                msg = "Job creation failed due to invalid input Excel format.";
        //                                            }
        //                                        }
        //                                    }
        //                                    else
        //                                    {
        //                                        jobitem.Frequency = worksheet.Cells[row, 5].Value?.ToString().Trim();
        //                                        jobitem.State = worksheet.Cells[row, 7].Value?.ToString().Trim();
        //                                        if (dts.Rows.Count > 0 && dtf.Rows.Count > 0)
        //                                        {

        //                                            if (!string.IsNullOrEmpty(jobitem.State) && !string.IsNullOrEmpty(jobitem.Frequency))
        //                                            {
        //                                                for (int k = 0; k < dts.Rows.Count; k++)
        //                                                {
        //                                                    if (jobitem.State.ToLower() == dts.Rows[k]["statename"].ToString().ToLower())
        //                                                    {
        //                                                        stcode = dts.Rows[k]["statecodeid"].ToString();
        //                                                        break;
        //                                                    }
        //                                                }
        //                                                for (int l = 0; l < dtf.Rows.Count; l++)
        //                                                {
        //                                                    if (jobitem.Frequency.ToLower() == dtf.Rows[l]["frequencytype"].ToString().ToLower())
        //                                                    {
        //                                                        frcode = dtf.Rows[l]["frequencyid"].ToString();
        //                                                        break;
        //                                                    }
        //                                                }
        //                                                if (!string.IsNullOrEmpty(frcode) && !string.IsNullOrEmpty(stcode))
        //                                                {
        //                                                    joblist.Add(jobitem);
        //                                                }
        //                                                else
        //                                                {
        //                                                    msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
        //                                                }
        //                                            }
        //                                            else
        //                                            {
        //                                                msg = "Kindly Fill Mandatory Field.";
        //                                            }

        //                                        }
        //                                        else
        //                                        {
        //                                            msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
        //                                        }

        //                                    }
        //                                }
        //                            }
        //                            else
        //                            {
        //                                msg = "Job creation failed due to invalid input Excel format.";
        //                            }
        //                            string jobid_mul = string.Empty;
        //                            //tas
        //                            //Response.Headers.Add("Content-Type", "text/event-stream");
        //                            for (int j = 0; j < joblist.Count; j++)
        //                            {
        //                                //job insertion
        //                                ojobModel.statename = joblist[j].State;
        //                                ojobModel.frequencytype = joblist[j].Frequency;
        //                                if (!string.IsNullOrEmpty(stcode) && !string.IsNullOrEmpty(frcode))
        //                                {
        //                                    //jobid_mul = "1579,1580";
        //                                    //tas
        //                                    int retval1 = _JobConfigurationservices.Addjobandjobcofig(ojobModel);
        //                                    //int retval1 = 1580;
        //                                    if (string.IsNullOrEmpty(jobid_mul))
        //                                    {
        //                                        jobid_mul = retval1.ToString();
        //                                    }
        //                                    else
        //                                    {
        //                                        jobid_mul = jobid_mul + "," + retval1.ToString();
        //                                    }
        //                                    //adding lot
        //                                    for (int row = 2; row <= rowCount; row++)
        //                                    {
        //                                        bool st = false;
        //                                        bool ft = false;
        //                                        if (worksheet.Cells[row, 5].Value?.ToString().Trim().ToLower() == joblist[j].Frequency.ToLower())
        //                                            ft = true;

        //                                        if (worksheet.Cells[row, 7].Value?.ToString().Trim().ToLower() == joblist[j].State.ToLower())
        //                                            st = true;
        //                                        if (ft && st)
        //                                        {
        //                                            List<lotmetafields> metafieldslst = new List<lotmetafields>();
        //                                            //For lot metafields
        //                                            for (int coln = 2; coln <= colCount; coln++)
        //                                            {
        //                                                lotmetafields metafields = new lotmetafields();
        //                                                for (int i = 0; i < dtmetafieldlst.Rows.Count; i++)
        //                                                {
        //                                                    if ((dtmetafieldlst.Rows[i]["jobmeta"].ToString().ToLower() == worksheet.Cells[1, coln].Value?.ToString().Trim().ToLower()) || (dtmetafieldlst.Rows[i]["jobmeta"].ToString().ToLower() + "*" == worksheet.Cells[1, coln].Value?.ToString().Trim().ToLower()))
        //                                                    {
        //                                                        metafields.FieldName = dtmetafieldlst.Rows[i]["jobmeta"].ToString();
        //                                                        metafields.FieldValue = worksheet.Cells[row, coln].Value?.ToString().Trim();
        //                                                        metafields.isexcelmeta = true;
        //                                                        metafieldslst.Add(metafields);
        //                                                    }
        //                                                }
        //                                            }
        //                                            //add lot
        //                                            lotmasterModel olotmaster = new lotmasterModel();
        //                                            olotmaster.lotmastermetafields = JsonConvert.SerializeObject(metafieldslst);
        //                                            olotmaster.jobid = retval1;
        //                                            olotmaster.createdby = ojobModel.createdby;
        //                                            foreach (var item in metafieldslst)
        //                                            {
        //                                                if (item.FieldName == "Company Name")
        //                                                {
        //                                                    olotmaster.companyname = item.FieldValue;
        //                                                }
        //                                                else if (item.FieldName == "Type")
        //                                                {
        //                                                    olotmaster.type = item.FieldValue;
        //                                                }
        //                                                else if (item.FieldName == "Ranking")
        //                                                {
        //                                                    olotmaster.ranking = item.FieldValue;
        //                                                }
        //                                                else if (item.FieldName == "State")
        //                                                {
        //                                                    olotmaster.state = item.FieldValue;
        //                                                }
        //                                                else if (item.FieldName == "Follow Up Date")
        //                                                {
        //                                                    olotmaster.followupdate = item.FieldValue;
        //                                                }
        //                                                else if (item.FieldName == "Frequency")
        //                                                {
        //                                                    olotmaster.frequency = item.FieldValue;
        //                                                }
        //                                                else if (item.FieldName == "City")
        //                                                {
        //                                                    olotmaster.city = item.FieldValue;
        //                                                }
        //                                            }
        //                                            olotmaster.option = "insertlot";
        //                                            string inputstr1 = JsonConvert.SerializeObject(olotmaster);
        //                                            //tas
        //                                            //var retval_ = "1345";
        //                                            var retval_ = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr1, olotmaster.option);
        //                                        }
        //                                    }
        //                                    retval.Add(retval1);
        //                                    //added by monicaa
        //                                    // Send a message containing the current progress
        //                                    // Response.WriteAsync($"data: {retval.Count}\n\n");
        //                                    //Response.Body.Flush();
        //                                }
        //                                else
        //                                {
        //                                    msg = "State/Frequency code missing. Kindly add into master(s) list and then create job.";
        //                                }
        //                            }
        //                            //send email
        //                            createmail(jobid_mul, Convert.ToInt64(Request.Form["createdby"].ToString()));
        //                        }
        //                    });

        //                    if (msg != string.Empty)
        //                        return BadRequest(new { message = msg });
        //                }
        //            }
        //        }
        //        return Ok(retval);
        //    }
        //    catch (Exception ex)
        //    {
        //        oCommonRepository.ErrorLog(ex);
        //        // return error message if there was an exception
        //        //return BadRequest(new { message = "Job Creation Failed" });
        //        return BadRequest(new { message = ex.Message.ToString() });
        //    }

        //}

        [Authorize]
        [HttpGet]
        public IActionResult GetSSEProgress()
        {
            Response.Headers.Add("Content-Type", "text/event-stream");

            // Simulate a progress update
            for (int i = 1; i <= 10; i++)
            {
                string eventData = $"data: {{\"progress\": {i * 10}}}\n\n";
                Response.Body.Write(Encoding.UTF8.GetBytes(eventData));
                Response.Body.Flush();
                Thread.Sleep(1000); // Simulate progress updates every 1 second
            }

            return Ok();
        }
        public static bool createmail(string jobid, long userid)
        {
            CommonRepository oCommonRepository = new CommonRepository();
            StringBuilder tableStr = new StringBuilder();
            var jsonData = new { mul_jobid = jobid };
            var jsonstr = JsonConvert.SerializeObject(jsonData);
            long totalLotsCount = 0;
            string jobdetails = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spjobmasterselect", jsonstr, "getJobdatabymuljobid"));
            jobdetails = jobdetails.Replace("\\\"", "\"");
            if (!string.IsNullOrEmpty(jobdetails) || jobdetails != "null")
            {
                DataTable dtjoblst = oCommonRepository.JsonStringToDataTable(jobdetails);
                if (dtjoblst.Rows.Count > 0)
                {
                    tableStr.Append("<TABLE style=\"border-collapse:collapse; border: solid black 1.0pt;width:50%\">");
                    tableStr.Append("<TR style=\"border: solid black 1.0pt; background:#2B4C81;color:white\">");
                    for (int k = 0; k < dtjoblst.Columns.Count; k++)
                    {
                        string colname =
                                System.Text.Json.JsonNamingPolicy.CamelCase.ConvertName(dtjoblst.Columns[k].ColumnName.ToString());
                        TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
                        colname = textInfo.ToTitleCase(colname);
                        tableStr.Append("<TH  style=\"border: solid black 1.0pt;text-transform:capitalize\">" + colname + "</TH>");
                    }
                    tableStr.Append("</TR>");
                    for (int r = 0; r < dtjoblst.Rows.Count; r++)
                    {
                        int remainder;
                        int quotient = Math.DivRem(r, 2, out remainder);
                        if (remainder == 0)
                        {
                            tableStr.Append("<TR style = \"border: solid black 1.0pt; border - top:none; background:#DBEDF2\">");
                        }
                        else
                        {
                            tableStr.Append("<TR style=\"border: solid black 1.0pt; border-top:none; \">");
                        }

                        for (int k = 0; k < dtjoblst.Columns.Count; k++)
                        {
                            string s = dtjoblst.Rows[r][k].ToString().Trim();
                            int u = -1;
                            if (dtjoblst.Columns[k].ColumnName.ToString() == "Number of Lots")
                            {
                                totalLotsCount = totalLotsCount + Convert.ToInt64(dtjoblst.Rows[r][k]);
                            }

                            if (int.TryParse(s, out u) || s == "null")
                            {
                                tableStr.Append("<TD  style=\"border: solid black 1.0pt;text-align:center \">");
                            }
                            else
                            {
                                tableStr.Append("<TD  style=\"border: solid black 1.0pt;text-align:left \">");
                            }
                            // tableStr.Append("<TD  style=\"border: solid black 1.0pt;text-align:center \">");
                            if (string.IsNullOrEmpty(s) || s == "null")
                            {
                                tableStr.Append(0);
                            }
                            else
                            {
                                tableStr.Append(s);
                            }

                            tableStr.Append("</TD>");
                        }
                        tableStr.Append("</TR>");
                    }

                    tableStr.Append("</TABLE>");
                    //tableStr.Append("<p> <b>Total Lots count = </b>" + totalLotsCount + "</p>");

                    List<string> CC_list = new List<string>();
                    List<string> To_list = new List<string>();
                    List<string> BCC_list = new List<string>();
                    string MailContent = string.Empty;
                    string Mailsubject = string.Empty;
                    string username = string.Empty;
                    //get email template
                    var jsonmailData = new { mailtemplateid = Convert.ToInt64(Job_Creation_mailtemplate_id) };
                    var jsonmailstr = JsonConvert.SerializeObject(jsonmailData);
                    string mailtemplatedetails = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spmailtemplatemasterselect", jsonmailstr, "getbyid"));
                    mailtemplatedetails = mailtemplatedetails.Replace("\\\"", "\"");
                    if (!string.IsNullOrEmpty(mailtemplatedetails) && mailtemplatedetails != "null")
                    {
                        DataTable dtmaillst = oCommonRepository.JsonStringToDataTable(mailtemplatedetails);
                        if (dtmaillst.Rows.Count > 0)
                        {
                            MailContent = dtmaillst.Rows[0]["body"].ToString();
                            Mailsubject = dtmaillst.Rows[0]["subject"].ToString();
                            //to user creadedby
                            var jsoncreateduserData = new { userid_p = userid };
                            var jsoncreateduserstr = JsonConvert.SerializeObject(jsoncreateduserData);
                            string createduserdetails = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spusermasterselect", jsoncreateduserstr, "getbyid"));
                            createduserdetails = createduserdetails.Replace("\\\"", "\"");
                            if (!string.IsNullOrEmpty(createduserdetails) && createduserdetails != "null")
                            {
                                DataTable dtcreateduserlst = oCommonRepository.JsonStringToDataTable(createduserdetails);
                                if (dtcreateduserlst.Rows.Count > 0)
                                {
                                    string createduser_mail = dtcreateduserlst.Rows[0]["emailid"].ToString();
                                    username = dtcreateduserlst.Rows[0]["username"].ToString();
                                    List<string> tolistcont = To_list.Where(x => x.Equals(createduser_mail)).ToList();
                                    if (tolistcont.Count == 0) To_list.Add(createduser_mail);
                                }
                            }
                            //cc mailtemplate mapping user
                            var jsonmailtempuserData = new { mailtemplateid = Convert.ToInt64(Job_Creation_mailtemplate_id) };
                            var jsonmailtempuserstr = JsonConvert.SerializeObject(jsonmailtempuserData);
                            string mailtempuser = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spusermasterselect", jsonmailtempuserstr, "getbymailtemplateid"));
                            mailtempuser = mailtempuser.Replace("\\\"", "\"");
                            if (!string.IsNullOrEmpty(mailtempuser) && mailtempuser != "null")
                            {
                                DataTable dtmailtempuserlst = oCommonRepository.JsonStringToDataTable(mailtempuser);
                                if (dtmailtempuserlst.Rows.Count > 0)
                                {
                                    for (int l = 0; l < dtmailtempuserlst.Rows.Count; l++)
                                    {
                                        string createduser_mail = dtmailtempuserlst.Rows[l]["emailid"].ToString();

                                        if (!string.IsNullOrEmpty(createduser_mail) && createduser_mail != "null")
                                        {
                                            List<string> tolistcont = To_list.Where(x => x.Equals(createduser_mail)).ToList();
                                            List<string> cclistcont = CC_list.Where(x => x.Equals(createduser_mail)).ToList();
                                            if (tolistcont.Count == 0 && cclistcont.Count == 0) CC_list.Add(createduser_mail);
                                        }
                                    }

                                }
                            }
                            if (To_list.Count == 1)
                            {
                                MailContent = MailContent.Replace("$$username", username);
                            }
                            else
                            {
                                MailContent = MailContent.Replace("$$username", "All");
                            }
                            MailContent = MailContent.Replace("$$total", totalLotsCount.ToString());
                            MailContent = MailContent.Replace("$$table", tableStr.ToString());
                            sendmail(Mailsubject, MailContent, To_list, CC_list);

                        }
                    }
                }
            }
            return true;
        }
        public static bool sendmail(string Subject, string BodyText, List<string> TOMailIDs, List<string> CCMailIDs = null, List<string> BCCMailIDs = null)
        {
            try
            {
                SmtpClient smtpClient = new SmtpClient();
                MailMessage message = new MailMessage();
                StringBuilder mailbody = new StringBuilder();
                MailAddress fromAddress = new MailAddress(from_mail, mail_header);
                System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential(from_mail, from_mail_pwd);
                smtpClient.Host = mail_host;
                smtpClient.EnableSsl = true;
                smtpClient.Port = Convert.ToInt32(from_port);
                smtpClient.Credentials = myCredential;
                message.From = fromAddress;
                message.Subject = Subject;
                TOMailIDs.ForEach(x => message.To.Add(x));
                if (CCMailIDs != null)
                    CCMailIDs.ForEach(x => message.CC.Add(x));
                if (BCCMailIDs != null)
                    BCCMailIDs.ForEach(x => message.Bcc.Add(x));
                message.IsBodyHtml = true;
                message.Body = BodyText;
                smtpClient.Send(message);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        [Authorize]
        [HttpGet("DeleteJob")]
        public IActionResult DeleteJob(Int64 jobid)
        {
            try
            {
                var res = _JobConfigurationservices.DeleteJob(jobid);
                if (res == 0)
                {
                    return Ok(new
                    {
                        message = "success"
                    });
                }
                else
                {
                    return BadRequest(new { message = "Job does not exist." });
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }


        }
        //Code to update specific record
        [Authorize]
        [HttpPost("Update")]
        public IActionResult Update([FromBody] jobModel ojobModel)
        {
            int retval = 0;
            try
            {
                retval = _JobConfigurationservices.Edit(ojobModel);
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }
        //code to get current flow by workflowid
        [Authorize]
        [HttpPost("GetByJobId")]
        public IActionResult GetByJobId([FromBody] jobModel data)
        {
            try
            {
                var list = _JobConfigurationservices.GetByJobId(data);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpPost("GetFlowChart")]
        ///code to get flowchart for the given job id
        public IActionResult GetFlowChart([FromBody] jobModel oJobModel)
        {
            var _mappedFlowChart = _JobConfigurationservices.GetFlowChart(oJobModel);
            return Ok(_mappedFlowChart);
        }

        //code to add the project workflow definition 
        [Authorize]
        [HttpPost("AddJobWorkflow")]
        public IActionResult AddJobWorkflow([FromBody] List<jobworkflowdefinitionModel> oJobworkflowdefinitionModel)
        {

            try
            {
                var list = _JobConfigurationservices.AddJobWorkflow(oJobworkflowdefinitionModel);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        //code to add the project workflow definition 
        [Authorize]
        [HttpPost("UpdateJobWorkflow")]
        public IActionResult UpdateJobWorkflow([FromBody] List<jobworkflowdefinitionModel> oJobworkflowdefinitionModel)
        {

            try
            {
                var list = _JobConfigurationservices.UpdateJobWorkflow(oJobworkflowdefinitionModel);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpPost("GetAllByUserId")]
        public IActionResult GetAllByUserId([FromBody] userModel data)
        {
            try
            {               
                if (data.isarchive == 1)
                {
                    var list = _JobConfigurationservices.getAllByUserId_witharchive(data);
                    return Ok(list);
                }
                else
                {
                    var list = _JobConfigurationservices.GetAllByUserId(data);
                    return Ok(list);
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpPost("GetJobWorkFlowDefCount")]
        public IActionResult GetJobWorkFlowDefCount([FromBody] jobworkflowdefinitionModel data)
        {
            try
            {
                var list = _JobConfigurationservices.GetJobWorkFlowDefCount(data);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpPost("GetLotMastersByJobId")]
        public IActionResult GetLotMastersByJobId([FromBody] lotmasterModel data)
        {
            try
            {
                var list = _JobConfigurationservices.GetLotMastersByJobId(data);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpGet("GetJobProductType")]
        public IActionResult GetJobProductType(string userid)
        {
            try
            {
                var list = _JobConfigurationservices.GetJobProductType(userid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpGet("GetTatFlowByProjectId")]
        //Code to retrieve active data
        public IActionResult GetTatFlowByProjectId(Int64 projectdefinitionid)
        {
            var _list = _JobConfigurationservices.GetTatFlowByProjectId(projectdefinitionid);
            return Ok(_list);
        }

        [Authorize]
        [HttpGet("GetTatFlowByJobId")]
        //Code to retrieve active data
        public IActionResult GetTatFlowByJobId(Int64 jobId)
        {
            var _list = _JobConfigurationservices.GetTatFlowByJobId(jobId);
            return Ok(_list);
        }
        [Authorize]
        [HttpGet("getJobByProjectDefinitionid")]
        public IActionResult getJobByProjectDefinitionid(Int64 projectdefinitionid)
        {
            try
            {
                var list = _JobConfigurationservices.getJobByProjectDefinitionid(projectdefinitionid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        //code to get current flow by workflowid
        [Authorize]
        [HttpPost("GetByJobIdFromJobMaster")]
        public IActionResult GetByJobIdFromJobMaster([FromBody] jobModel data)
        {
            try
            {
                var list = _JobConfigurationservices.GetByJobIdFromJobMaster(data);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        //ccwms
        [Authorize]
        [HttpGet("GetCCJobByUserId/{userid}/{projecdefid}")]
        //Code to retrieve active data
        public IActionResult GetCCJobByUserId(Int64 userid, Int64 projecdefid)
        {
            var _list = _JobConfigurationservices.GetCCJobByUserId(userid, projecdefid);
            return Ok(_list);
        }
        [Authorize]
        [HttpPost("PostCCJobMaster/{userid}/{projecdefid}")]
        public IActionResult PostCCJobMaster(Int64 userid, Int64 projecdefid)
        {
            var _list = _JobConfigurationservices.PostCCJobMaster(userid, projecdefid);
            return Ok(_list);
        }

        private string FormatPath(string inputpath)
        {
            try
            {
                inputpath = inputpath.Replace("/", "\\");
                inputpath = inputpath.Replace("\\\\", "");
                inputpath = System.Text.RegularExpressions.Regex.Replace(inputpath, @"\\\\", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            return string.Concat("\\\\", inputpath);
        }
        public class jobinfoexcellist
        {
            public string Frequency { get; set; }
            public string State { get; set; }
        }
        public class lotmetafields
        {
            public string FieldName { get; set; }
            public string FieldValue { get; set; }
            public bool isexcelmeta { get; set; }
        }
    }
}