using BPMService.Models;
using Dapper;
using MassTransit;
using MassTransit.Contracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Controllers.Common.Uploader;
using WK_KLI_LAPS_Service.Controllers.Configuration.Job;
using WK_KLI_LAPS_Service.Controllers.Master.Lot;
using WK_KLI_LAPS_Service.Controllers.WorkArea;
using WK_KLI_LAPS_Service.Models;
using WK_KLI_LAPS_Service.Models.Configuration;
using WK_KLI_LAPS_Service.Models.Master;

namespace WK_KLI_LAPS_Service.Controllers.Dashboard
{
    [Route("api/[controller]")]
    [ApiController]
    public class DashboardApiController : ControllerBase
    {
        DashboardService oDashboardService = new DashboardService();
        CommonRepository oCommonRepository = new CommonRepository();
        WorkAreaService oWorkAreaService = new WorkAreaService();
        UploaderService oUploaderService = new UploaderService();
        LotService oLotService = new LotService();
        private readonly IConfiguration _config;
        JobConfigurationService oJobConfigurationService = new JobConfigurationService();
        private object list;
        string baseurl = Startup.Configuration.GetValue<string>("AppSettings:serverroot");
        string downloader = Startup.Configuration.GetValue<string>("AppSettings:Downloader");
        string uploader = Startup.Configuration.GetValue<string>("AppSettings:Uploader");
        static string Vendor_Allocation_mailtemplate_id = Startup.Configuration.GetValue<string>("AppSettings:Vendor_Allocation_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:Vendor_mail_header");
        static string Vendor_to_From_Address = Startup.Configuration.GetValue<string>("AppSettings:Vendor_to_From_Address");  
        static string Inhouseuserid = Startup.Configuration.GetValue<string>("AppSettings:Inhouseuserid");
        private readonly IRequestClient<ISimpleRequest, ISimpleResponse> _requestClient;


        public DashboardApiController(IRequestClient<ISimpleRequest, ISimpleResponse> requestClient, IConfiguration config)
        {
            _requestClient = requestClient;
            _config=config;
        }

        [HttpGet]
        public IActionResult tetx()
        {
            return Ok("1");

        }
        //code to get User Project Status Details
        [Authorize]
        [HttpPost("getUserProjectStatusDetails")]
        public IActionResult getUserProjectStatusDetails([FromBody] dashboardModel data)
        {
            string inputstr = JsonConvert.SerializeObject(data);
            var _list = oDashboardService.getUserProjectStatusDetails(inputstr);
            return Ok(_list);

        }

        [Authorize]
        [HttpPost("getJobNo")]
        public IActionResult getJobNo([FromBody] dashboardModel data)
        {
            string inputstr = JsonConvert.SerializeObject(data);
            var _list = oDashboardService.getJobNo(inputstr);
            return Ok(_list);

        }
        [Authorize]
        [HttpPost("loadStageDetails")]
        public IActionResult loadStageDetails([FromBody] dashboardModel data)
        {
            string inputstr = JsonConvert.SerializeObject(data);
            var _list = oDashboardService.loadStageDetails(inputstr);
            return Ok(_list);

        }
        [Authorize]
        [HttpPost("getMailBoxDetails")]
        public IActionResult getMailBoxDetails([FromBody] dashboardModel data)
        {
            string inputstr = JsonConvert.SerializeObject(data);
            var _list = oDashboardService.getMailBoxDetails(inputstr);
            return Ok(_list);

        }

        [Authorize]
        [HttpPost("getLoadType")]
        public IActionResult getLoadType([FromBody] dashboardModel data)
        {
            string inputstr = JsonConvert.SerializeObject(data);
            var _list = oDashboardService.getLoadType(inputstr);
            return Ok(_list);
        }

        [Authorize]
        [HttpPost("getProjectJobDetails")]

        public IActionResult GetProjectJobDetails([FromBody] dashboardModel data)
        {
            
            try
            {
                oCommonRepository.WriteLog("GetProjectJobDetails", data.p_jobid.ToString());
                oCommonRepository.WriteLog("GetProjectJobDetails", data.p_projectdefinitionid.ToString());
                oCommonRepository.WriteLog("GetProjectJobDetails", data.p_userid.ToString());
                string inputstr = JsonConvert.SerializeObject(data);
                oCommonRepository.WriteLog("GetProjectJobDetailsiactionresult", inputstr);
                var _list = oDashboardService.getProjectJobDetails(inputstr);
                return Ok(_list);
            }
            catch (Exception ex)
            {
                // Log the exception properly (e.g., using a logging framework)
                Console.WriteLine($"Error: {ex.Message}");

                return StatusCode(500, "An unexpected error occurred while processing the request.");
            }
        }


        public class LotCommentModel
        {
            public long jobid { get; set; }
            public string comment_text { get; set; }
            public DateTime createdon { get; set; }
            public long projectdefinitionid { get; set; }
            public string jobtitle { get; set; }

            public string querytype { set; get; }

            public string status { set; get; }
        }
        [HttpPost("getLotCommentsByProject")]
        public IActionResult getLotCommentsByProject([FromBody] LotCommentModel data)
        {
            try
            {
                string inputstr = JsonConvert.SerializeObject(data);
                var _list = oDashboardService.getLotCommentsByProject(inputstr);
                return Ok(_list);
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }

        public class LotCommentUpdateRequest
        {
            public string Mode { get; set; }
            public long tranid { get; set; }
            public long jobid { get; set; }
            public string querytype { get; set; }
            public string status { get; set; }
            public long cid { get; set; }
            public long startpage { get; set; }
            public long endpage { get; set; }
        }
        [HttpPost("updateLotComment")]
        public IActionResult UpdateLotComment([FromBody] LotCommentUpdateRequest data)
        {
            try
            {
                using (var conn = new NpgsqlConnection(_config["DBInfo:ConnectionString"]))
                {
                    conn.Open();

                    string query = string.Empty;
                    if (data.Mode == "updatepage")
                    {
                        query = @"UPDATE tbllotcomments
                        SET startpage = @startpage,
                        endpage = @endpage where cid = @queryid";

                        using (var cmd = new NpgsqlCommand(query, conn))
                        {
                            cmd.Parameters.AddWithValue("@startpage", data.startpage);
                            cmd.Parameters.AddWithValue("@endpage", data.endpage);
                            cmd.Parameters.AddWithValue("@queryid", data.cid);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    else if (data.Mode == "updateQueryType")
                    {
                        query = @"
                   UPDATE tbllotcomments 
                   SET querytype = @querytype
                   WHERE jobid = @jobid
                   AND createon = (
                       SELECT MAX(createon)
                       FROM tbllotcomments 
                       WHERE jobid = @jobid
                   )";

                        using (var cmd = new NpgsqlCommand(query, conn))
                        {
                            cmd.Parameters.AddWithValue("@querytype", (object)data.querytype ?? DBNull.Value);
                            cmd.Parameters.AddWithValue("@jobid", data.jobid);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    else if (data.Mode == "updateStatus")
                    {

                        query = @"
                   UPDATE tbllotcomments 
                   SET status = @status
                   WHERE jobid = @jobid
                   AND createon = (
                       SELECT MAX(createon)
                       FROM tbllotcomments 
                       WHERE jobid = @jobid
                   )";

                        using (var cmd = new NpgsqlCommand(query, conn))
                        {
                            cmd.Parameters.AddWithValue("@status", (object)data.status ?? DBNull.Value);
                            cmd.Parameters.AddWithValue("@jobid", data.jobid);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    else
                    {
                        return BadRequest(new { message = "Invalid mode specified" });
                    }
                }

                return Ok(new { message = "Updated successfully" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = "Error updating record", error = ex.Message });
            }
        }


        //public IActionResult getProjectJobDetails([FromBody] dashboardModel data)
        //{
        //    try
        //    {
        //        string inputstr = JsonConvert.SerializeObject(data);
        //        var _list = oDashboardService.getProjectJobDetails(inputstr);
        //        return Ok(_list);
        //    }
        //    catch (Exception ex)
        //    {

        //        Console.WriteLine(ex.Message.ToString());

        //    }
        //}
        [Authorize]
        [HttpGet]
        [Route("getStageList/{data:int}")]
        public IActionResult getStageList(int data)
        {
            var projdef = new { projectdefinitionid = data };
            string inputstr = JsonConvert.SerializeObject(projdef);
            var _list = oDashboardService.getStageList(inputstr);
            return Ok(_list);
        }

        [Authorize]
        [HttpGet]
        [Route("getUserAssignedJob/{prdefid:int}/{wfdefid:int}")]
        public IActionResult getUserAssignedJob(int prdefid, int wfdefid)
        {
            var projdef = new { projectdefinitionid = prdefid, wfdid = wfdefid };

            string inputstr = JsonConvert.SerializeObject(projdef);
            var _list = oDashboardService.getUserAssignedJob(inputstr);
            return Ok(_list);
        }
        [Authorize]
        [HttpGet]
        [Route("getUserAssignedUser/{prdefid:int}/{wfdefid:int}")]
        public IActionResult getUserAssignedUser(int prdefid, int wfdefid)
        {
            var projdef = new { projectdefinitionid = prdefid, wfdid = wfdefid };

            string inputstr = JsonConvert.SerializeObject(projdef);
            var _list = oDashboardService.getUserAssignedUser(inputstr);
            return Ok(_list);
        }


        [Authorize]
        [HttpPost("jobBackForward")]
        public IActionResult jobBackForward([FromBody] dashboardModel data)
        {
            // string inputstr = JsonConvert.SerializeObject(data);
            var _list = oDashboardService.jobBackForward(data);
            return Ok(_list);
        }
        [Authorize]
        [HttpPost("GetUserWiseAssignLot")]
        public IActionResult GetUserWiseAssignLot([FromBody] lotassignmentdetails data)
        {
            var _list = oDashboardService.GetUserWiseAssignLot(data);
            return Ok(_list);
        }
        [Authorize]
        [HttpGet]
        [Route("getUserAssignedLot/{prdefid:int}/{wfdefid:int}/{jobid:int}/{userid:int}/{start}/{end}/{type:int}")]
        public IActionResult getUserAssignedLot(int prdefid, int wfdefid, int jobid, int userid)
        {
            var projdef = new { projectdefinitionid = prdefid, wfdid = wfdefid, jobid = jobid, userid = userid };

            string inputstr = JsonConvert.SerializeObject(projdef);
            var _list = oDashboardService.getUserAssignedLot(inputstr);
            return Ok(_list);
        }
        [Authorize]
        [HttpGet]
        [Route("getassignjob_userlst/{prdefid:int}/{wfdefid:int}/{jobid:int}/{userid:int}/{start}/{end}/{type:int}")]
        public IActionResult getassignjob_userlst(int prdefid, int wfdefid, int jobid, int userid, string start, string end, int type)
        {
            try
            {
                var projdef = new { projectdefinitionid = prdefid, wfdid = wfdefid, jobid = jobid, userid = userid, p_startdate = start, p_enddate = end, p_type = type };
                string inputstr = JsonConvert.SerializeObject(projdef);
                var userlst = oDashboardService.getUserAssignedUser(inputstr);
                var joblst = oDashboardService.getUserAssignedJob(inputstr);
                //var filterlst = oDashboardService.getUserAssignedLot(inputstr);
                return Ok(new
                {
                    joblst = joblst,
                    userlst = userlst,
                    //filterlst = filterlst
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpPost]
        [Route("setLotAssignDetails/{jobworkflowid:int}/{lotid:int}/{userid:int}/{sflag:int}/{stype}")]
        public IActionResult setLotAssignDetails(long jobworkflowid, long lotid, long userid, long sflag, string stype)
        {

            var lotdet = new { jobworkflowid = jobworkflowid, lotid = lotid, userid = userid, sflag = sflag, stype = stype };

            string inputstr = JsonConvert.SerializeObject(lotdet);

            var _list = oDashboardService.setLotAssignDetails(inputstr);
            Postmail_SignOff(0, jobworkflowid, "1", lotid, userid);
            return Ok(_list);
        }

        [Authorize]
        [HttpGet]
        [Route("getUserJobs/{prdefid:int}/{userid:int}")]
        public IActionResult getUserJobs(long prdefid, long userid)
        {
            var projdef = new { projectdefinitionid = prdefid, userid = userid };

            string inputstr = JsonConvert.SerializeObject(projdef);

            var _list = oDashboardService.getUserJobs(inputstr);
            return Ok(_list);
        }

        [Authorize]
        [HttpGet]
        [Route("getlot_userlst/{prdefid:int}/{wfdefid:int}/{jobid:int}/{userid:int}")]
        public IActionResult getlot_userlst(int prdefid, int wfdefid, int jobid, int userid)
        {
            try
            {
                var projdef = new { projectdefinitionid = prdefid, wfdid = wfdefid, jobid = jobid, userid = userid };
                string inputstr = JsonConvert.SerializeObject(projdef);
                var userlst = oDashboardService.getVendorUser(inputstr);
                var lotlst = oDashboardService.getavailablelot(inputstr);
                var lotassignlst = oDashboardService.getassignedvendorlot(inputstr);
                return Ok(new
                {
                   lotlst = lotlst,
                    userlst = userlst,
                    lotassignlst= lotassignlst
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpPost("usrstagemove")]
        public IActionResult usrstagemove([FromBody] dashboardModel data)
        {
            try
            {
                // lottraninfo obj = JsonConvert.DeserializeObject<lottraninfo>(data.ToString());

                var lst = oWorkAreaService.getCheckout(data.p_tranid.ToString(), data.p_userid.ToString(), "P", "checkin", "0", "");
                var _list = oDashboardService.usrstagemove(data);
                return Ok(_list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }
        [Authorize]
        [HttpPost("geterror")]
        public IActionResult geterror([FromBody] lotcomment data)
        {
            // string inputstr = JsonConvert.SerializeObject(data);
            var _list = oLotService.GetCommentsByTranId(data);
            return Ok(_list);
        }

        [Authorize]
        [HttpPost("getReadyYTS")]
        public IActionResult getReadyYTS([FromBody] jobworkflowdefinitionModel data)
        {
            var _list = oJobConfigurationService.getReadyYTS(data);
            if (_list == null)
            {
                Guid id = Guid.NewGuid();
                var _listlt = oWorkAreaService.usrLotTransactionInsert(data.createdby, data.lotid, data.jobworkflowid, id.ToString(), "insertlottransactiondetailonly");
            }
            return Ok(_list);
        }
        [Authorize]
        [HttpPost("venodorallocation")]
        public object venodorallocation()
        {
            oCommonRepository.WriteLog("venodorallocation Started:", "venodorallocation");
            if (Request.Form != null)
            {
                string model = Request.Form["model"].ToString();
                var jsonArray = JArray.Parse(model);
                string trankey = string.Empty;
                string jobworkflowid = string.Empty;
                string userid = string.Empty;
                string tranid = string.Empty;               
                string filename = string.Empty;               
                string lottitle = string.Empty;               
                string lotid = string.Empty;
                string mode = string.Empty;
                string jobtitle = string.Empty;
                bool res = false;
                long withvendor = 0;
                long next_tranid = 0; string next_trankey = string.Empty;
                List<Int64> lotIds = new List<Int64>();
                string uniqueKey = Guid.NewGuid().ToString();
                string type = "nextstage";
                string pdfanalysispath = Startup.Configuration.GetValue<string>("AppSettings:pdfanalysispath");
                string redacationpath = Startup.Configuration.GetValue<string>("AppSettings:redactedpath");
                List<string> inhouseUserIdList = new List<string>(Inhouseuserid.Split(','));
                foreach (var i in jsonArray)
                {
                    trankey = i["trankey"].ToString();
                    jobworkflowid = i["jobworkflowid"].ToString();
                    userid = i["userid"].ToString();
                    tranid = i["tranid"].ToString();
                    filename = i["filename"].ToString();
                    lottitle = i["lottitle"].ToString();
                    //jobtitle = i["jobtitle"].ToString();
                    lotid = i["lotid"].ToString();
                    lotIds.Add(Convert.ToInt64(i["lotid"]));
                    if (!filename.Contains("."))
                    {
                        filename += ".pdf";
                    }
                    //if (Inhouseuserid == userid)
                    //{
                    //    mode = "checkexisttranbynextwflotid";
                    //    type = "next_nextstage";
                    //}
                    if (inhouseUserIdList.Contains(userid))
                    {
                        mode = "checkexisttranbynextwflotid";
                           type = "next_nextstage";
                    }
                    else
                    {
                        mode = "checkexisttranbywflotid";

                    }
                    
                    OkObjectResult checkexistence = (OkObjectResult)checkexisttranbywflotid(jobworkflowid, Convert.ToInt64(lotid), mode);
                    if (checkexistence != null && checkexistence.Value != null)
                    {
                        var list_ = JsonConvert.DeserializeObject<List<Dictionary<string, Dictionary<string, object>>>>(checkexistence.Value.ToString());
                        next_tranid = Convert.ToInt64(list_[0]["json_build_object"]["p_tranid"]);
                        next_trankey = list_[0]["json_build_object"]["trankkey"].ToString();
                    }
                    else { 
                    OkObjectResult nextres = (OkObjectResult)nextstagecreate(trankey, userid, lotid, type);
                  
                    if (nextres != null && nextres.Value != null)
                    {
                        var list_ = JsonConvert.DeserializeObject<List<Dictionary<string, Dictionary<string, object>>>>(nextres.Value.ToString());
                     next_tranid = Convert.ToInt64(list_[0]["json_build_object"]["p_tranid"]);
                     next_trankey= list_[0]["json_build_object"]["trankkey"].ToString();
                    }
                    }
                    long previous_tranid = 0;
                    using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", lotid))
                    {
                        WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

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

                            using (IDbConnection dbConnection = ConnectionBase.Connection)
                            {
                                dbConnection.Open();
                                DynamicParameters param = new DynamicParameters();
                                
                                param.Add("jobworkflowid_p", Convert.ToInt64(jobworkflowid)); 
                                param.Add("lotid_p", Convert.ToInt64(lotid));
                                 previous_tranid = dbConnection.Query<int>("public.spgetpreviousstagetranidbylotid", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                            }
                            string filePath_cur_IN = string.Empty;
                            //file movement
                            if (previous_tranid !=0)
                            {
                                string filePath_curr = oCommonRepository.getfilesavelocation(Convert.ToInt32(previous_tranid));
                                filePath_curr = oCommonRepository.FormatPath(filePath_curr);
                                string filePath_server_curr = oCommonRepository.GetServerPath(previous_tranid.ToString(), "serverinfo", false);
                                filePath_server_curr = filePath_server_curr.Replace("/", "\\");
                                filePath_cur_IN = Path.Combine(filePath_server_curr, "OUT");

                            }
                            else
                            {
                                string filePath_curr = oCommonRepository.getfilesavelocation(Convert.ToInt32(tranid));
                                filePath_curr = oCommonRepository.FormatPath(filePath_curr);
                                string filePath_server_curr = oCommonRepository.GetServerPath(tranid, "serverinfo", false);
                                filePath_server_curr = filePath_server_curr.Replace("/", "\\");
                                filePath_cur_IN = Path.Combine(filePath_server_curr, "IN");
                            }
                            string filePath_next = oCommonRepository.getfilesavelocation(Convert.ToInt32(next_tranid));
                            filePath_next = oCommonRepository.FormatPath(filePath_next);
                            string filePath_server_next = oCommonRepository.GetServerPath(next_tranid.ToString(), "serverinfo", false);
                            filePath_server_next = filePath_server_next.Replace("/", "\\");
                            var filePath_next_IN = Path.Combine(filePath_server_next, "IN");
                            var filePath_next_OUT = Path.Combine(filePath_server_next, "OUT");

                            //var pdfanalysis = Path.Combine(filePath_next,  "Parent");
                            var pdfanalysis = filePath_next.Replace(lotid, "Parent");
                            var redactedpath = Path.Combine(filePath_next, redacationpath, "OUT");
                            string visftitle = String.Concat(jobtitle, ".visf");
                            var visfpath = Path.Combine(filePath_next_IN, visftitle);
                            string pdftitle = String.Concat(jobtitle, ".pdf");
                            var pdfpath = Path.Combine(filePath_next_IN, pdftitle);
                            if (!Directory.Exists(filePath_next_OUT))
                            {
                                Directory.CreateDirectory(filePath_next_OUT);
                            }
                            if (!Directory.Exists(visfpath))
                            {
                                Directory.CreateDirectory(visfpath);
                            }

                            if (!Directory.Exists(Path.Combine(filePath_next_IN, "Input")))
                            {
                                Directory.CreateDirectory(Path.Combine(filePath_next_IN, "Input"));
                                //string[] pdfanalysisinputfiles = Directory.GetFiles(pdfanalysis, "*.pdf*", SearchOption.AllDirectories).ToArray();
                                string[] pdfanalysisinputfiles = Directory.GetFiles(pdfanalysis, "*.pdf", SearchOption.AllDirectories)
    .Where(file => Path.GetFileName(file).Contains(filename))
    .ToArray();

                                foreach (var pdfanlysisfile in pdfanalysisinputfiles)
                                {
                                    string psfname = Path.GetFileName(pdfanlysisfile);
                                    System.IO.File.Copy(pdfanlysisfile, Path.Combine(filePath_next_IN, "Input", psfname));
                                }
                            }
                            if (!Directory.Exists(Path.Combine(filePath_next_IN, pdftitle)))
                            {
                                Directory.CreateDirectory(Path.Combine(filePath_next_IN, pdftitle));

                                string[] redactioninputfiles = Directory.GetFiles(redactedpath, "*_Redacted.pdf", SearchOption.AllDirectories).ToArray();
                                foreach (var redactedfile in redactioninputfiles)
                                {
                                    string redname = Path.GetFileName(redactedfile);
                                    System.IO.File.Copy(redactedfile, Path.Combine(filePath_next_IN, pdftitle, redname));
                                }
                            }
                            oCommonRepository.CopyDirectory(filePath_cur_IN, filePath_next_IN);
                            string[] docxFiles = Directory.GetFiles(filePath_next_IN, "*.docx");
                            foreach (string file in docxFiles)
                            {
                                string fileName = Path.GetFileName(file);
                                System.IO.File.Move(file,Path.Combine(visfpath, fileName));
                            }
                        });
                    }  
                }//loop end
                if (Inhouseuserid != userid)
                {
                    //email send
                    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(Vendor_Allocation_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 = string.Empty;
                                if (!string.IsNullOrEmpty(Vendor_to_From_Address))
                                {
                                    createduser_mail = Vendor_to_From_Address;
                                }
                                else
                                {
                                    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(Vendor_Allocation_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("$$firstname", username);
                        }
                        else
                        {
                            MailContent = MailContent.Replace("$$firstname", "All");
                        }
                        MailContent = MailContent.Replace("$$chapter", lottitle);
                        //baseurl 
                       
                        string downloadpath = baseurl + downloader + "?L=" + next_trankey + "&U=" + userid + "&F=" + filename + "&T=" + next_tranid + "&K=" + uniqueKey;
                        string uploadpath = baseurl + uploader + "?L=" + next_trankey + "&U=" + userid + "&T=" + next_tranid + "&K=" + uniqueKey;
                        MailContent = MailContent.Replace("$$downloadpath", "<a href='" + downloadpath + "'> here </a>");
                        MailContent = MailContent.Replace("$$uploadpath", "<a href='" + uploadpath + "'> here </a>");
                         res = sendmail(Mailsubject, MailContent, To_list, CC_list);

                            if (res) withvendor = 1;
                        }
                }

                }
                else
                {
                    res = true;
                    withvendor = 2;
                }            
                if (res)
                {
                    //withvendor = 1;
                    mode = "updatevendoremail";

                }
                else
                {
                    //withvendor = 0;
                    mode = "updatevendoremail_fail";
                }
                foreach (var lotId in lotIds)
                {
                    var item = new { lotid = lotId, userid = userid, withvendor = withvendor, vendorkey = uniqueKey };
                    using (IDbConnection dbConnection = ConnectionBase.Connection)
                    {
                        dbConnection.Open();
                        DynamicParameters param = new DynamicParameters();
                        var jsonstr = JsonConvert.SerializeObject(item);
                        param.Add("inputjsonstr", jsonstr);
                        param.Add("mode_p", mode);
                        int result = dbConnection.Query<int>("public.splotmaster", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                    }
                }
                return Ok(new { result = "done" });
            }
            else
            {
                return null;
            }
           
        }


        [Authorize]
        [HttpGet("validatevendorcomplelte/{jobid}")]

        public object validatevendorcomplelte(int jobid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                string query = @"
      SELECT lotid 
      FROM tbllotmaster 
      WHERE jobid = @jobid 
      AND (assignedvendor IS NULL OR assignedvendor = 0)";
                var lotIds = dbConnection.Query<int>(query, new { jobid = jobid }).ToList();

                if (!lotIds.Any())
                {
                    return true;
                }

                // Loop through each lotid and check if its lotstatus is 'F'
                foreach (var lotId in lotIds)
                {
                    // Query to get the lotstatus for the current lotid
                    string lotStatusQuery = @"
          SELECT lotstatus 
          FROM tbllottransaction
          WHERE lotid = @lotid ORDER BY transactionid DESC LIMIT 1";

                    var lotStatus = dbConnection.QueryFirstOrDefault<string>(lotStatusQuery, new { lotid = lotId });

                    // If any lotstatus is 'F', return false (found incomplete)
                    if (lotStatus == "F")
                    {
                        return true; // Found at least one lot with status 'F'
                    }
                    else
                    {
                        return false;
                    }
                }

                // If no lotstatus was 'F', return true (all are valid)
                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;
            }
        }
        [AllowAnonymous]
        [HttpPost("Nextstagecreate/{tranid}/{userid}/{lotid}")]
        public IActionResult nextstagecreate(string tranid, string userid, string lotid,string type="")
        {
            var dt = oUploaderService.getlotstatusbytrankey(tranid);

            var i1_dt = JsonConvert.DeserializeObject<object>(dt.ToString());
            JArray a1_dt = JArray.Parse(i1_dt.ToString());
            JObject obj1_dt = JObject.Parse(a1_dt[0].ToString());

            long batchid = Convert.ToInt64(obj1_dt["batchid"]);
            string transactionid = obj1_dt["transactionid"].ToString();
            string next_jobworkflowid = string.Empty;
            //if (type == "next_nextstage")
            //{
            //    next_jobworkflowid = obj1_dt["next_next_jobworkflowid"].ToString();
            //}
            //else
            //{
            //    next_jobworkflowid = obj1_dt["next_jobworkflowid"].ToString();
            //}
            next_jobworkflowid = obj1_dt["next_jobworkflowid"].ToString();

            var data1 = new { batchid = batchid };
            var jsonstr1 = JsonConvert.SerializeObject(data1);
            var next_ordernores1 = CommonRepository.ExecuteSP_ReturnList2("splotbatchdetailsselect", jsonstr1, "getbybatchid");
            var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
            JArray BatchLotDetails = JArray.Parse(next_ordernodata1.ToString());

            if (BatchLotDetails.Count > 0)
            {
                for (var item = 0; item < BatchLotDetails.Count; item++)
                {
                    if (BatchLotDetails[item]["lotid"].ToString() == lotid)
                    {
                        var data2 = new { n_lotid = BatchLotDetails[item]["lotid"].ToString(), p_option = "getlottransactioncount" };
                        var jsonstr = JsonConvert.SerializeObject(data2);

                        var Checkinapp = oCommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);
                        var i_appType = JsonConvert.DeserializeObject<object>(Checkinapp.ToString());
                        JArray BatchLotDetails2 = JArray.Parse(i_appType.ToString());
                        if (Convert.ToInt32(BatchLotDetails2[0]["count"].ToString()) == 0)
                        {
                            list = oWorkAreaService.getCheckout(transactionid, userid, "R", "checkout_next_unmerged", next_jobworkflowid, "", BatchLotDetails[item]["lotid"].ToString());

                            
                        }
                    }
                }
            }
            return Ok(list);
        }
        [AllowAnonymous]
        [HttpPost("getcurstagecheckoutony/{tranid}/{userid}")]
        public IActionResult getcurstagecheckoutony(string tranid,string userid)
        {
            list = oWorkAreaService.getCheckout(tranid, userid, "C", "checkout_only", "0", "");
            return Ok(list);
        }
        public IActionResult checkexisttranbywflotid(string jobworkflowid, long lotid,string mode)
        {
            var projdef = new { jobworkflowid = jobworkflowid, lotid = lotid };
            string inputstr = JsonConvert.SerializeObject(projdef);

            list = oDashboardService.getcheckexisttranbywflotid(inputstr,mode);
            return Ok(list);
        }
        [Authorize]
        [HttpPost]
        [Route("manualcheckout")]
        public IActionResult manualcheckout(lottraninfo data)
        {
            var res = new { p_tranid = data.p_tranid, p_userid = data.p_userid, p_status = data.p_lotstatus, p_option = data.p_option, p_comments = "" };

            var jsonstr = JsonConvert.SerializeObject(res);
            oCommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);

            return Ok(jsonstr);
        }


        [HttpPost]
        [Route("forwardstage")]
        public IActionResult forwardstage(lottraninfofor data)
        {

            

            Guid id = Guid.NewGuid();

            //int next_tranid = InsertLotTransaction(Convert.ToInt32(data1.Rows[0]["lotid"].ToString()), AIstage.ToString(), Path.GetFileNameWithoutExtension(inpath), tranid);

            //   var _listlt = oWorkAreaService.usrLotTransactionInsert(data.p_userid, data.p_lotid, data.p_jobworkflowid, id.ToString(), "insertlottransactiondetailonly");
            long tranid = 0;
           int userid = Convert.ToInt32(data.p_userid);
           long lotid = Convert.ToInt32(data.p_lotid);
            // long jobworkflowid = Convert.ToInt32(data.p_jobworkflowid) + 1;
           
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();

                string querys = @"
      SELECT jobworkflowid 
      FROM tbljobworkflowdefinition 
      WHERE jobid = @jobid 
      AND stagename_alias='HTML Generation'";
                var jobworkflow = dbConnection.Query<int>(querys, new { jobid =  data.p_jobid }).ToList();

                string sQry = "insert_lot_transaction_details_only";
                using (var cmd = new NpgsqlCommand(sQry, (NpgsqlConnection)dbConnection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    //cmd.Parameters.Add(new NpgsqlParameter("p_jobworkflowid", NpgsqlTypes.NpgsqlDbType.Bigint) { Value = Convert.ToInt64(jobworkflow) });
                    if (jobworkflow != null && jobworkflow.Any())
                    {
                        cmd.Parameters.Add(new NpgsqlParameter("p_jobworkflowid", NpgsqlTypes.NpgsqlDbType.Bigint)
                        {
                            Value = Convert.ToInt64(jobworkflow.First())
                        });
                    }
                    cmd.Parameters.Add(new NpgsqlParameter("p_lotid", NpgsqlTypes.NpgsqlDbType.Bigint) { Value = lotid });
                    cmd.Parameters.Add(new NpgsqlParameter("p_lotkey", NpgsqlTypes.NpgsqlDbType.Uuid) { Value = Guid.Parse(id.ToString()) });

                    object result = cmd.ExecuteScalar();

                    // Replace modcommon.nz with your own null check or conversion
                    if (result == null || result == DBNull.Value)
                    {
                        tranid = 0;  // or default value you want
                    }
                    else
                    {
                        tranid = Convert.ToInt64(result);
                    }
                }
                long transactionId = Convert.ToInt64(data.p_tranid);
                string query = @"Update tbllottransaction set lotstatus='F' where transactionid=@transactionid"
            ;
                var lotIds = dbConnection.Query<int>(query, new { transactionid = transactionId }).ToList();


            }

            // var _listlt = oWorkAreaService.usrLotTransactionInsert(userid, lotid, jobworkflowid, id.ToString(), "insertlottransactiondetailonly");

            //string nextstage_serverpath = oCommonRepository.GetServerPath(data.p_tranid.ToString(), "serverinfo",true);


            RabbitMq sendmsg = new RabbitMq(_requestClient);
            
            sendmsg.SendMq_StageComplete(tranid.ToString(), "0", "checkin_apps", "server", "", "A", "");
            return Ok("Success");
        }


        [HttpPost]
        public object Postmail_SignOff(long tranid, long jobworkflowid, string sflag, long curtranid, long userId)
        {
            try
            {
                oCommonRepository.WriteLog("Postmail_SignOff:", "Postmail_SignOff");
                //long userId_t = Convert.ToInt64(userId);
                long userId_t = userId;
                RabbitMq sendmsg = new RabbitMq(_requestClient);
                oCommonRepository.WriteLog("_requestClient:" + _requestClient, "Postmail_SignOff");
                sendmsg.SendMqMail(tranid.ToString(), jobworkflowid.ToString(), sflag, curtranid.ToString(), userId_t.ToString());
                return Ok();
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return Ok();
            }



        }
        [Authorize]
        [HttpPost("activeordeactive")]
        public IActionResult Delete([FromBody] mailboxModel omenuModel)
        {
            int retval = 0;
            try
            {
                retval = oDashboardService.Delete(omenuModel);
                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("UpdateMailbox")]
        public IActionResult UpdateMailbox([FromBody] dashboardModel ounitModel)
        {
            int retval = 0;
            try
            {
                retval = oDashboardService.UpdateMailbox(ounitModel);
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }
        [Authorize]
        [HttpGet("GetJobStatusreport/{jobid}")]
        public IActionResult GetJobStatusreport(long jobid)
        {
            try
            {
                // using (DBContext db = new DBContext())
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {

                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    param.Add("p_jobid", dbType: DbType.Int64, value: Convert.ToInt64(jobid), direction: ParameterDirection.Input);

                    var getReportJobDetails = dbConnection.Query<string>("public.spgetjobstatusreport", param, commandType: CommandType.StoredProcedure).ToList();
                    if (getReportJobDetails[0] != null)
                    {
                        var next_ordernodata2 = JsonConvert.DeserializeObject<object>(getReportJobDetails[0].ToString());
                        JArray dt_order = JArray.Parse(next_ordernodata2.ToString());

                        List<jobstatusdetails> json = new List<jobstatusdetails>();

                        foreach (var item in dt_order)
                        {
                            json.Add(JsonConvert.DeserializeObject<jobstatusdetails>(item.ToString()));
                        }

                        if (json.Count > 0)
                        {
                            json.Where(x => x.merged_lot.Equals(1) && x.batchid != null).Select(x => new { x.lotid, x.batchid, x.lottitle }).Distinct().ToList().ForEach(x =>
                            {
                                json.Where(y => y.lotid == x.lotid).ToList().ForEach(o => { o.batchid = x.batchid; o.batchname = x.lottitle; });
                            });

                            //json.Where(x => x.merged_lot.Equals(1) && x.batchid != null).Select(x => new { x.lotid, x.batchid, x.lottitle }).Distinct().ToList().ForEach(x =>
                            //{
                            //    //DynamicParameters param1 = new DynamicParameters();
                            //    //var lotdata = new
                            //    //{
                            //    //    jobid = Convert.ToInt32(jobid),
                            //    //    batchid = Convert.ToInt32(x.batchid)
                            //    //};
                            //    //string lotinput = JsonConvert.SerializeObject(lotdata);
                            //    //param1.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                            //    //param1.Add("mode_p", dbType: DbType.String, value: "getbyjobbatchsupplement", direction: ParameterDirection.Input);
                            //    //var batchDetails = dbConnection.Query<string>("public.splotbatchselect", param1, commandType: CommandType.StoredProcedure).ToList();
                            //    //if (batchDetails[0] != null)
                            //    //{
                            //    //    var next_ordernodata3 = JsonConvert.DeserializeObject<object>(batchDetails[0].ToString());
                            //    //    JArray dt_order3 = JArray.Parse(next_ordernodata3.ToString());
                            //    //    List<batchdet> json1 = new List<batchdet>();
                            //    //    foreach (var item in dt_order3)
                            //    //    {
                            //    //        json1.Add(JsonConvert.DeserializeObject<batchdet>(item.ToString()));
                            //    //    }
                            //    //    foreach (batchdet bd in json1)
                            //    //    {
                            //    //        json.Where(y => y.lotid == bd.lotid).ToList().ForEach(o =>
                            //    //        {
                            //    //            o.batchid = bd.batchid;
                            //    //            o.batchname = bd.batchname;
                            //    //        });
                            //    //    }
                            //    //}
                            //});

                            json.ForEach(x =>
                            {
                                if (x.transactionid != null)
                                {
                                    long? m = json.Where(y => y.lotid.Equals(x.lotid) && y.stagename_alias.Equals(x.stagename_alias)).Max(y => y.transactionid);
                                    json.Where(y => y.lotid.Equals(x.lotid) && y.stagename_alias.Equals(x.stagename_alias)).ToList().ForEach(o =>
                                    {
                                        if (o.transactionid == m)
                                            o.locked = 1;
                                        else
                                            o.locked = 0;
                                    });
                                }
                                else
                                    x.locked = 1;

                            });

                            List<chapterdetails> cpdet = new List<chapterdetails>();
                            var stages = json.Select(x => x.stagename_alias).Distinct();
                            json.Select(x => x.lotid).Distinct().ToList().ForEach(x =>
                            {
                                List<jobstatusdetails> temp = json.Where(y => y.lotid == x && y.locked == 1).ToList<jobstatusdetails>();
                                cpdet.Add(new chapterdetails() { rows = temp.Max(o => o.slotcnt), batchid = temp[0].batchid, chaptername = temp[0].lottitle, statusdetails = temp });

                            });
                            //var Supplementdet = json.Where(x => x.batchid != null && x.issupplement == 1).Select(x => new { x.batchid, x.batchname }).Distinct();
                            //var volumedetails = json.Where(x => x.volumeid != null).Select(x => new { x.volumeid, x.volumename }).Distinct();
                            var lotdata = new
                            {
                                Stagedet = stages,
                                Chapdet = cpdet.OrderBy(x => x.batchid).ThenByDescending(x => x.rows),
                                //volumedet = volumedetails,
                                //Supplementdet = Supplementdet
                            };

                            return Ok(lotdata);
                        }
                        else
                            return Ok(json);
                    }
                    else
                    {
                        var lotdata = new
                        {
                            Stagedet = 0,
                            Chapdet = 0,
                            //volumedet = 0,
                            //Supplementdet = 0
                        };
                        return Ok(lotdata);
                    }
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpGet("GetSupplementlotdetails/{batchid}")]
        public IActionResult GetSupplementlotdetails(long batchid)
        {
            try
            {
                // using (DBContext db = new DBContext())
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    // db.CheckLogin();
                    // string qry = string.Format(@"select distinct lotid from lot_batch_details where batchid={0} and active=true", batchid);
                    // List<long> SuppLot = db.Database.SqlQuery<long>(qry).ToList();
                    DynamicParameters param1 = new DynamicParameters();
                    var lotdata = new
                    {
                        batchid = Convert.ToInt32(batchid)
                    };
                    string lotinput = JsonConvert.SerializeObject(lotdata);
                    param1.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                    param1.Add("mode_p", dbType: DbType.String, value: "GetSupplementlotdetails", direction: ParameterDirection.Input);
                    var batchDetails = dbConnection.Query<string>("public.splotbatchdetailsselect", param1, commandType: CommandType.StoredProcedure).ToList();
                    return Ok(batchDetails);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [Authorize]
        [HttpGet("getuserbyprodefid/{prodefid}")]
        public IActionResult getuserbyprodefid(long prodefid)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    DynamicParameters param1 = new DynamicParameters();
                    param1.Add("p_projectdefinitionid", dbType: DbType.Int64, value: prodefid, direction: ParameterDirection.Input);
                    var userlist = dbConnection.Query<string>("public.getuserbyprodefid", param1, commandType: CommandType.StoredProcedure).ToList();
                    return Ok(userlist);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [Authorize]
        [HttpPost("getjoblotexcel")]
        public IActionResult getjoblotexcel([FromBody] object data)
        {
            string inputstr = JsonConvert.SerializeObject(data);
            var _list = oDashboardService.getjoblotexcel(inputstr, "getall");
            return Ok(_list);
        }

        //Code to add new record
        [Authorize]
        [HttpPost("Addjoblotinfo")]
        public IActionResult Addjoblotinfo([FromBody] joblotinfoexcellist olotmaster)
        {
            try
            {
                string inputstr = JsonConvert.SerializeObject(olotmaster);
                var retval = oDashboardService.Add(inputstr, "insert");
                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 update specific record
        [Authorize]
        [HttpPost("Update")]
        public IActionResult Update([FromBody] joblotinfoexcellist olotmaster)
        {
            try
            {
                string inputstr = JsonConvert.SerializeObject(olotmaster);
                var retval = oDashboardService.Add(inputstr, "updateprojectid_url");
                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]
        [Route("setLotAssignDetails_multiple")]
        public IActionResult setLotAssignDetails_multiple()
        {
            try
            {
                if (Request.Form != null)
                {

                    string model = Request.Form["model"].ToString();
                    var jsonArray = JArray.Parse(model);
                    foreach (var j in jsonArray)
                    {
                        string assgineduser = j["assigned_user"].ToString();
                        string jobworkflowid = j["jobworkflowid"].ToString();
                        string lotid = j["lotid"].ToString();
                        string userid = j["selectUser"].ToString();
                        string stype = j["sType"].ToString();
						var fromorder = j["fromorder"];
                        var toorder = j["toorder"]; 
						
						if (Convert.ToInt64(assgineduser) == 0)
                        {
                            var lotdet = new { jobworkflowid = Convert.ToInt64(jobworkflowid), lotid = Convert.ToInt64(lotid), userid = Convert.ToInt64(userid), sflag = 1, stype = stype };
                            string inputstr = JsonConvert.SerializeObject(lotdet);
                            var _list = oDashboardService.setLotAssignDetails(inputstr);
                            //Postmail_SignOff(0, Convert.ToInt64(jobworkflowid), "1", Convert.ToInt64(lotid), Convert.ToInt64(userid));
                        }
                        else if (Convert.ToInt64(assgineduser) == Convert.ToInt64(userid))
                        {
                            var lotdet = new { jobworkflowid = Convert.ToInt64(jobworkflowid), lotid = Convert.ToInt64(lotid), userid = Convert.ToInt64(userid), sflag = 3, stype = stype };
                            string inputstr = JsonConvert.SerializeObject(lotdet);
                            var _list = oDashboardService.setLotAssignDetails(inputstr);
                           // Postmail_SignOff(0, Convert.ToInt64(jobworkflowid), "3", Convert.ToInt64(lotid), Convert.ToInt64(userid));

                        }
                        else if (Convert.ToInt64(assgineduser) != Convert.ToInt64(userid))
                        {
                            var lotdet = new { jobworkflowid = Convert.ToInt64(jobworkflowid), lotid = Convert.ToInt64(lotid), userid = Convert.ToInt64(userid), sflag = 1, stype = stype };
                            string inputstr = JsonConvert.SerializeObject(lotdet);
                            var _list = oDashboardService.setLotAssignDetails(inputstr);
                          //  Postmail_SignOff(0, Convert.ToInt64(jobworkflowid), "1", Convert.ToInt64(lotid), Convert.ToInt64(userid));
                        }
                        if (fromorder != null && toorder != null)
                        {
                            //vendor bypass -------
                            string p_option = j["p_option"].ToString();
                            string mode_p = j["mode_p"].ToString();
                            string p_vendor = j["p_vendor"].ToString();
                            long tranid = Convert.ToInt64(j["tranid"]);

                            var inputstr = new
                            {
                                fromorder = Convert.ToInt64(fromorder.ToString()),
                                option = p_option,
                                toorder = Convert.ToInt64(toorder.ToString()),
                                tranid = tranid,
                                userid = Convert.ToInt64(userid),
                                vendor = p_vendor,
                            };
                            var result = oCommonRepository.ExecuteSP_ReturnInt("spjobbackforward", inputstr, mode_p, null);

                            using (IDbConnection dbConnection = ConnectionBase.Connection)
                            {
                                DynamicParameters param1 = new DynamicParameters();
                                var inputstr1 = new
                                {
                                    lotid = Convert.ToInt64(lotid),

                                };
                                string lotinput = JsonConvert.SerializeObject(inputstr1);
                                param1.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                                param1.Add("mode_p", dbType: DbType.String, value: "", direction: ParameterDirection.Input);
                                var getlots = dbConnection.Query<string>("public.spgetlotsbylotid", param1, commandType: CommandType.StoredProcedure).ToList();
                                var temp = JsonConvert.DeserializeObject<object>(getlots[0].ToString());

                                JArray dt_lots = JArray.Parse(temp.ToString());

                                List<lots_details> lots = new List<lots_details>();

                                foreach (var items in dt_lots)
                                {
                                    lots.Add(JsonConvert.DeserializeObject<lots_details>(items.ToString()));
                                }

                                foreach(var item in lots)
                                {
                                    if (item.userid ==0)
                                    {
                                        var vendor_assign = new { jobworkflowid = Convert.ToInt64(item.jobworkflowid), lotid = Convert.ToInt64(item.lotid), userid = Convert.ToInt64(userid), sflag = 1, stype = stype };
                                        string inputstr2 = JsonConvert.SerializeObject(vendor_assign);
                                        var vendor_return = oDashboardService.setLotAssignDetails(inputstr2);
                                        Postmail_SignOff(0, Convert.ToInt64(item.jobworkflowid), "1", Convert.ToInt64(lotid), Convert.ToInt64(userid));
                                    }
                                }

                            }
                        }
                    }
                }

                return Ok(
                    new
                    {
                        msg = "success"
                    });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = ex.Message });
            }

        }
        public class lots_details
        {
            public Int64 lotid { get; set; }
            public Int64 transactionid { get; set; }
            public string lotstatus { get; set; }
            public Int64 pickedby { get; set; }
            public string stagename_alias { get; set; }
            public int stageorder { get; set; }
            public Int64 jobworkflowid { get; set; }
            public Int64? userid { get; set; }
            public Int64 projectdefinitionid { get; set; }
        }
        public class Transaction
        {
            public int TransactionId { get; set; }
            public string TransactionKey { get; set; }
        }
        public class InnerObject
        {
            [JsonProperty("p_tranid")]
            public int TranId { get; set; }

            [JsonProperty("trankkey")]
            public string TranKey { get; set; }
        }

        public class OuterObject
        {
            [JsonProperty("json_build_object")]
            public InnerObject JsonBuildObject { get; set; }
        }
    }


}