using Dapper;
using MassTransit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text.RegularExpressions;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Controllers.Common.Uploader;
using WK_KLI_LAPS_Service.Controllers.Master.LotBatch;
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.WorkArea
{
    [Route("api/[controller]")]
    [ApiController]
    public class WorkAreaApiController : ControllerBase
    {

        private readonly IRequestClient<ISimpleRequest, ISimpleResponse> _requestClient;
        private readonly IConfiguration _config;
        private ILotBatchService _LotBatchService;
        public WorkAreaApiController(IRequestClient<ISimpleRequest, ISimpleResponse> requestClient, IConfiguration config,ILotBatchService LotBatchService)
        {
            _requestClient = requestClient;
            _config = config;
            _LotBatchService = LotBatchService;
        }
        WorkAreaService oWorkAreaService = new WorkAreaService();
        UploaderService oUploaderService = new UploaderService();
        string baseurl = Startup.Configuration.GetValue<string>("AppSettings:serverroot");
        CommonRepository oCommonRepository = new CommonRepository();
        private object list;
        [HttpPost]

        public object EnableIgnore(string sequence, string movebackstage, string lotid, string p_tranid, string userid, string correction)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                DynamicParameters param = new DynamicParameters();
                param.Add("p_tranid", dbType: DbType.Int32, value: p_tranid, direction: ParameterDirection.Input);

                var dt = dbConnection.Query<object>("select  a.jobworkflowid,a.lotstatus,a.lotid,a.transactionid,c.lotkey from lot_transaction a left outer join lot_master c on a.lotid = c.lotid where a.transactionid = " + p_tranid + "", param, commandType: CommandType.Text).ToList();
                if (dt != null)
                {
                    var i_appType = JsonConvert.DeserializeObject<object>(dt.ToString());
                    JArray a_appType = JArray.Parse(i_appType.ToString());
                    JObject obj_appType = JObject.Parse(a_appType[0].ToString());

                    param = new DynamicParameters();
                    param.Add("@p_jobworkflowid", value: obj_appType["jobworkflowid"].ToString());
                    param.Add("@p_lotid", value: obj_appType["lotid"].ToString());
                    param.Add("@p_lotkey", value: obj_appType["lotkey"].ToString());

                    var emaildetails = dbConnection.Query<int>("select * from  insert_lot_transaction_details_only(@p_jobworkflowid, @p_lotid,@p_lotkey) as json", param, commandType: CommandType.Text).ToList();

                    //  var emaildetails = db1.Database.SqlQuery<int>("select * from  insert_lot_transaction_details_only(@p_jobworkflowid, @p_lotid,@p_lotkey) as json",
                    //new Npgsql.NpgsqlParameter { ParameterName = "@p_jobworkflowid", Value = dt.Rows[0]["jobworkflowid"].ToString() },
                    //new Npgsql.NpgsqlParameter { ParameterName = "@p_lotid", Value = dt.Rows[0]["lotid"].ToString() },
                    //new Npgsql.NpgsqlParameter { ParameterName = "@p_lotkey", Value = dt.Rows[0]["lotkey"].ToString() }).ToList();

                    param = new DynamicParameters();
                    param.Add("@p_lotid", value: obj_appType["lotid"].ToString());
                    dbConnection.Query<int>("update lot_batch_details set merged=false ,active=true,ignored=false where lotid = {0}", param, commandType: CommandType.Text).ToList();

                    //db.InsertQuery(db1, string.Format("update lot_batch_details set merged=false ,active=true,ignored=false where lotid = {0}", dt.Rows[0]["lotid"].ToString()), null);


                    RabbitMq sendmsg = new RabbitMq(_requestClient);
                    sendmsg.SendMqMail(p_tranid.ToString(), obj_appType["jobworkflowid"].ToString().ToString(), "2", emaildetails[0].ToString(), userid.ToString());
                }


            }
            return Ok();
        }

        [HttpPost]
        public object GetLotDetails(string jobid)
        {
            //DBContext db1 = new DBContext();
            //var qry = "select jsonb_build_object('lotid',lotid,'title',title,'ticked',ticked) as json from (select lotid,title,case  when rownum = 1 then true else false end as ticked from (select lotid,title,row_number() over (order by sequence) as rownum from lot_master a where a.jobid = '" + jobid + "' order by sequence) as T) as T1";
            //var checkoutAppDetails = db1.Database.SqlQuery<jsonvalue>(qry).ToList();
            var Globaljson = new List<object>();
            //var json = new List<object>();
            //foreach (var item in checkoutAppDetails)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            //Globaljson.Add(json);

            //qry = "select jsonb_build_object('stagename_alias',stagename_alias,'jobworkflowid',jobworkflowid,'stageorder',stageorder) as json from(select stagename_alias,jobworkflowid,stageorder from job_workflow_master where jobid = '" + jobid + "' and stage_type != 3 order by stageorder) as T";
            //checkoutAppDetails = db1.Database.SqlQuery<jsonvalue>(qry).ToList();
            //json = new List<object>();
            //foreach (var item in checkoutAppDetails)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            //Globaljson.Add(json);

            //qry = "select * from get_lot_comments(" + jobid + ") as json";
            //checkoutAppDetails = db1.Database.SqlQuery<jsonvalue>(qry).ToList();
            //json = new List<object>();
            //foreach (var item in checkoutAppDetails)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            //Globaljson.Add(json);
            return Globaljson;
        }
        [HttpPost]
        public object GetLotDetails_Lot(string jobid, string lotid)
        {

            //DBContext db1 = new DBContext();
            //var qry = "select jsonb_build_object('lotid',lotid,'title',title,'ticked',ticked) as json from (select lotid,title,case  when rownum = 1 then true else false end as ticked from (select lotid,title,row_number() over (order by sequence) as rownum from lot_master a where a.jobid = '" + jobid + "' order by sequence) as T) as T1";
            //var checkoutAppDetails = db1.Database.SqlQuery<jsonvalue>(qry).ToList();
            var Globaljson = new List<object>();
            //var json = new List<object>();
            //foreach (var item in checkoutAppDetails)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            //Globaljson.Add(json);

            //qry = "select jsonb_build_object('stagename_alias',stagename_alias,'jobworkflowid',jobworkflowid,'stageorder',stageorder) as json from(select stagename_alias,jobworkflowid,stageorder from job_workflow_master where jobid = '" + jobid + "' and stage_type != 3 order by stageorder) as T";
            //checkoutAppDetails = db1.Database.SqlQuery<jsonvalue>(qry).ToList();
            //json = new List<object>();
            //foreach (var item in checkoutAppDetails)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            //Globaljson.Add(json);


            //qry = "select * from get_lot_comments_lot(" + jobid + ",'" + lotid + "') as json";
            //checkoutAppDetails = db1.Database.SqlQuery<jsonvalue>(qry).ToList();
            //json = new List<object>();
            //foreach (var item in checkoutAppDetails)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            //Globaljson.Add(json);


            return Globaljson;
        }
        [HttpPost]
        public object GetLotDetails_Comments(string jobid, string lotid)
        {
            //DBContext db1 = new DBContext();
            //var qry = "select * from get_lot_comments_lot(" + jobid + ",'" + lotid.TrimEnd(',') + "') as json";
            //var checkoutAppDetails = db1.Database.SqlQuery<jsonvalue>(qry).ToList();
            var Globaljson = new List<object>();
            //var json = new List<object>();
            //foreach (var item in checkoutAppDetails)
            //{
            //    json.Add(JObject.Parse(item.json));
            //}
            //Globaljson.Add(json);
            return Globaljson;
        }
        [HttpPost]
        public object GetFileDetails(string transid)
        {
            //WorkAreaController spath = new WorkAreaController();
            //string serverpath_tranid = spath.GetServerPath(transid, true, "serverinfo");
            //var server_inpath = System.IO.Path.Combine(serverpath_tranid, "IN");
            //var server_outpath = System.IO.Path.Combine(serverpath_tranid, "OUT");
            //var server_inpath_List = System.IO.Directory.GetFiles(server_inpath).ToList();
            //var server_out_List = System.IO.Directory.GetFiles(server_outpath).ToList();
            //var input_xml = server_out_List.Where(x => (Path.GetExtension(x.ToLower()).Contains(".xml") && (!Path.GetFileName(x.ToLower()).Contains("_articleinfo")))).ToList();
            //if (input_xml.Count == 0)
            //    input_xml = server_inpath_List.Where(x => (Path.GetExtension(x.ToLower()).Contains(".xml") && (!Path.GetFileName(x.ToLower()).Contains("_articleinfo")))).ToList();
            List<string> s = new List<string>();
            //foreach (var item in input_xml)
            //{
            //    s.Add(Path.GetFileNameWithoutExtension(item));
            //}
            return s;
        }

        [Authorize]
        [HttpPost("PostUpdatelot_transaction_V1")]

        public object PostUpdatelot_transaction_V1()
        {
            oCommonRepository.WriteLog("PostUpdatelot_transaction_V1 Started:", "PostUpdatelot_transaction_V1");
            var httpRequest = HttpContext.Request.Form;
            Fields oFieldsmodal = new Fields();
            if (Request.Form != null)
            {
                string model = Request.Form["model"].ToString();
                var tostage = Request.Form["tostage"];
                var jobid = Request.Form["jobid"];
                var comment = Request.Form["comment"];
                comment = Regex.Replace(comment, "<(.|\n)*?>", "");
                comment = Regex.Replace(comment, @"\t|\n|\r", "");
                var lotid = Request.Form["lotid"];
                var batchid = Request.Form["batchid"];
                var extravalues = Request.Form["extravalues"];
                var isnochange = Request.Form["isnochange"];
                var Status = Request.Form["Status"];
                var querytype = Request.Form["querytype"];



                oFieldsmodal = JsonConvert.DeserializeObject<Fields>(model); //JsonConvert.DeserializeObject<object>(model.ToString()).ToObject<Fields>().FirstOrDefault();

                var list = oWorkAreaService.checkLotTransactionStatus(oFieldsmodal.transid.ToString());
                if (isnochange == "true")
                {
                    var updatelotchange = oWorkAreaService.updatenochange(oFieldsmodal.transid.ToString());
                }

                if (list != null)
                {
                    var i1 = JsonConvert.DeserializeObject<object>(list.ToString());
                    JArray a1 = JArray.Parse(i1.ToString());
                    JObject obj1 = JObject.Parse(a1[0].ToString());
                    string lotstatus = obj1["lotstatus"].ToString();
                    if (lotstatus == "C" || lotstatus == "G")
                    {
                        return Ok("C");
                    }
                }

                //S for Comments, H for Hold Comments, C for Currection Comments.
                var doption = "S";
                if (oFieldsmodal.option == "hold")
                    doption = "H";
                if (oFieldsmodal.cflag == "B")
                    doption = "C";
                if (oFieldsmodal.cflag == "G")
                    doption = "G";

                if (httpRequest.Files.Count > 0)
                {
                    var sFileName = httpRequest.Files[0];

                    //DBContext db1 = new DBContext();
                    if (batchid != "" && doption != "H")
                    {
                        var lotbatch = oWorkAreaService.getBatchStatus(batchid);
                        if (lotbatch != null)
                        {
                            var i_lotbatch = JsonConvert.DeserializeObject<object>(lotbatch.ToString());
                            JArray a_lotbatch = JArray.Parse(i_lotbatch.ToString());
                            JObject obj_lotbatch = JObject.Parse(a_lotbatch[0].ToString());
                            var lotid_lotbatch = obj_lotbatch["lotid"].ToString();
                            //need to check batch process
                            var insertComments_lotbatch = oWorkAreaService.insertLotComments(comment, sFileName.FileName, oFieldsmodal.transid.ToString(), doption, tostage, jobid, lotid, Status, querytype);
                            var i2_lotbatch = JsonConvert.DeserializeObject<object>(insertComments_lotbatch.ToString());
                            JArray a2_lotbatch = JArray.Parse(i2_lotbatch.ToString());
                            JObject obj2_lotbatch = JObject.Parse(a2_lotbatch[0].ToString());
                            string cid_lotbatch = obj2_lotbatch["cid"].ToString();
                            string sPath_lotbatch = oWorkAreaService.getFileSaveLcation(Convert.ToInt32(oFieldsmodal.transid.ToString()));
                            sPath_lotbatch = sPath_lotbatch.Replace("/", "\\");
                            sPath_lotbatch = @"\\" + sPath_lotbatch;
                            if (sPath_lotbatch != string.Empty)
                            {
                                var serverPath_lotbatch = Path.Combine(sPath_lotbatch, "Comments");
                                if (!Directory.Exists(serverPath_lotbatch))
                                    Directory.CreateDirectory(serverPath_lotbatch);
                                var serverPath1_lotbatch = Path.Combine(serverPath_lotbatch, cid_lotbatch);
                                if (!Directory.Exists(serverPath1_lotbatch))
                                    Directory.CreateDirectory(serverPath1_lotbatch);
                                var filePath_lotbatch = serverPath1_lotbatch + "/" + sFileName.FileName;
                                using (var stream = new FileStream(filePath_lotbatch, FileMode.Create))
                                {
                                    sFileName.CopyTo(stream);
                                }
                            }
                        }

                    }
                    else
                    {
                        var insertComments = oWorkAreaService.insertLotComments(comment, sFileName.FileName, oFieldsmodal.transid.ToString(), doption, tostage, jobid, lotid, Status, querytype);
                        var i2 = JsonConvert.DeserializeObject<object>(insertComments.ToString());
                        JArray a2 = JArray.Parse(i2.ToString());
                        JObject obj2 = JObject.Parse(a2[0].ToString());
                        string cid = obj2["cid"].ToString();
                        string sPath = oWorkAreaService.getFileSaveLcation(Convert.ToInt32(oFieldsmodal.transid.ToString()));
                        sPath = sPath.Replace("/", "\\");
                        sPath = @"\\" + sPath;
                        if (sPath != string.Empty)
                        {
                            var serverPath = Path.Combine(sPath, "Comments");
                            if (!Directory.Exists(serverPath))
                                Directory.CreateDirectory(serverPath);
                            var serverPath1 = Path.Combine(serverPath, cid);
                            if (!Directory.Exists(serverPath1))
                                Directory.CreateDirectory(serverPath1);
                            var filePath = serverPath1 + "/" + sFileName.FileName;
                            using (var stream = new FileStream(filePath, FileMode.Create))
                            {
                                sFileName.CopyTo(stream);
                            }
                        }
                    }
                }
                else
                {
                    if (batchid != "" && doption != "H")
                    {
                        var lotbatch = oWorkAreaService.getBatchStatus(batchid);
                        if (lotbatch != null)
                        {
                            var i_lotbatch = JsonConvert.DeserializeObject<object>(lotbatch.ToString());
                            JArray a_lotbatch = JArray.Parse(i_lotbatch.ToString());
                            JObject obj_lotbatch = JObject.Parse(a_lotbatch[0].ToString());
                            var lotid_lotbatch = obj_lotbatch["lotid"].ToString();
                            //need to check batch process
                            var insertComments_lotbatch = oWorkAreaService.insertLotComments(comment, null, oFieldsmodal.transid.ToString(), doption, tostage, jobid, lotid, Status, querytype);
                        }
                        //var lotbatch = db_.GetDataTable(db, "select lotid from lot_batch_details where batchid = " + batchid + " and ignored = false", null);
                        //if (lotbatch.Rows.Count > 0)
                        //{
                        //    for (int i = 0; i <= lotbatch.Rows.Count - 1; i++)
                        //    {
                        //        lotid = lotbatch.Rows[i][0].ToString();
                        //        var cid = insert_lot_comments(comment, null, fields.transid.ToString(), doption, tostage, jobid, lotid);
                        //    }
                        //}
                    }
                    else
                    {
                        var insertComments = oWorkAreaService.insertLotComments(comment, null, oFieldsmodal.transid.ToString(), doption, tostage, jobid, lotid, Status, querytype);
                    }
                }



                long transactionid = oFieldsmodal.transid;
                string option = oFieldsmodal.option;
                string cfalg = oFieldsmodal.cflag;
                string userid = oFieldsmodal.userid;
                if (oFieldsmodal.fields != "null")
                {
                    var metaFieldsUpdate = oWorkAreaService.metaFieldsUpdate(oFieldsmodal.transid.ToString(), oFieldsmodal.fields);
                }

                // var updateLotStatus = oWorkAreaService.updateLotStatus(oFieldsmodal.transid.ToString(), "Q"); if (lotid.ToString() != "")
                {
                    var updateLotStatus = oWorkAreaService.updateLotStatus(oFieldsmodal.transid.ToString(), "Q");
                }

                lottraninfo lotinfo = new lottraninfo();
                lotinfo.p_tranid = transactionid.ToString();
                lotinfo.p_userid = userid;
                lotinfo.p_option = option;
                lotinfo.p_holdreason = "";

                if (option == "hold")
                {
                    var usrLotTransactionUpdate = oWorkAreaService.getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "I", "hold", "0", lotinfo.p_holdreason);
                    return Ok(usrLotTransactionUpdate);

                }
                else if (option == "checkout")
                {
                    oCommonRepository.WriteLog("PostUpdatelot_transaction_V1:", "PostUpdatelot_transaction_V1-Checkout");
                    if (cfalg == "G")
                    {
                        oCommonRepository.WriteLog("PostUpdatelot_transaction_V1:", "Flag:G");
                        RabbitMq sendmsg = new RabbitMq(_requestClient);
                        sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
                    }
                    else
                    {
                        oCommonRepository.WriteLog("PostUpdatelot_transaction_V1:", "Flag:else part");
                        appdetails appdetails = new appdetails();
                        appdetails = oWorkAreaService.CheckAppType(lotinfo.p_tranid, lotinfo.p_userid);

                        if (appdetails != null)
                        {
                            if (appdetails.checkin_app != null && appdetails.checkout_app != "" && appdetails.stagetype == "server")
                            {
                                RabbitMq sendmsg = new RabbitMq(_requestClient);
                                sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkin_apps", "", "", cfalg, extravalues, "", "", comment);
                            }
                            else if (appdetails.checkout_app != null && appdetails.checkout_app != "")
                            {
                                var PublicationID = "";
                                if (lotid.ToString() != "")
                                {
                                    var lotlist = _LotBatchService.GetSupplementDetailsBylotid(Int32.Parse(lotid));
                                    if (lotlist != null)
                                    {
                                        var dt = JArray.Parse(lotlist.ToString());
                                        var obj1_jobid = JObject.Parse(dt[0].ToString());
                                        var Batch = obj1_jobid["batchname"].ToString();
                                        var PublicationType = obj1_jobid["supplementtype"].ToString();

                                        if (obj1_jobid["jobmetadata"].ToString() != "")
                                        {
                                            var PublicationIDs = JArray.Parse(obj1_jobid["jobmetadata"].ToString());
                                            var publicationmetadataId = Startup.Configuration.GetValue<string>("AppSettings:publicationmetadataId");
                                            var metadatalists = PublicationIDs.Where(c =>
                                            c["jobmetaid"].ToString() == publicationmetadataId);
                                            foreach (var metadatalist in metadatalists)
                                            {
                                                PublicationID = metadatalist["FieldValue"].ToString();
                                            }
                                        }
                                        oCommonRepository.WriteLog("PostUpdatelot_transaction_V1:", "appdetails.checkout_app != null && appdetails.checkout_app != ''");
                                        RabbitMq sendmsg = new RabbitMq(_requestClient);
                                        if (appdetails.coaisservice == 1)
                                        {
                                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps_service_withfile", "", "", cfalg, extravalues, Batch, PublicationType, comment, PublicationID);
                                        }
                                        else
                                        {
                                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps", "", "", cfalg, extravalues, Batch, PublicationType, comment, PublicationID);
                                        }
                                    }
                                    else
                                    {
                                        if (appdetails.coaisservice == 1)
                                        {
                                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps_service_withfile", "", "", cfalg, extravalues, "", "", comment, PublicationID);
                                        }
                                        else
                                        {
                                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps", "", "", cfalg, extravalues, "", "", comment, PublicationID);
                                        }
                                    }
                                }
                                else
                                {
                                    RabbitMq sendmsg = new RabbitMq(_requestClient);
                                    sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps_forcmapprove", "", "", cfalg, extravalues, "", "", comment, PublicationID);
                                }

                            }
                            else if (appdetails.process_without_file == 1)
                            {
                                oWorkAreaService.Checkout_transaction(lotinfo);
                            }
                            else if (appdetails.process_without_file == 0)
                            {
                                oCommonRepository.WriteLog("PostUpdatelot_transaction_V1 Started :", "PostUpdatelot_transaction_V1-process_without_file");
                                RabbitMq sendmsg = new RabbitMq(_requestClient);
                                sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withfile", "", "", cfalg, extravalues);
                                oCommonRepository.WriteLog("PostUpdatelot_transaction_V1 after calling watcher :", "PostUpdatelot_transaction_V1-process_without_file");
                            }
                            else
                            {
                                RabbitMq sendmsg = new RabbitMq(_requestClient);
                                sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
                            }
                        }
                        else
                        {
                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                            sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
                        }

                    }

                }
                else if (option == "save")
                {
                    appdetails appdetails = new appdetails();
                    appdetails = oWorkAreaService.CheckAppType(lotinfo.p_tranid, lotinfo.p_userid);
                    if (appdetails != null)
                    {
                        if (appdetails.inprocessapp != null)
                        {
                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "inprocess_apps", "", "", cfalg, extravalues, "", "", comment);
                        }
                    }
                }

                return Ok(list);
            }
            else
            {
                return null;
            }
            //  return "Done";
        }

        //public object PostUpdatelot_transaction_V1()
        //{
        //    oCommonRepository.WriteLog("PostUpdatelot_transaction_V1 Started:", "PostUpdatelot_transaction_V1");
        //    var httpRequest = HttpContext.Request.Form;
        //    Fields oFieldsmodal = new Fields();
        //    if (Request.Form != null)
        //    {
        //        string model = Request.Form["model"].ToString();
        //        var tostage = Request.Form["tostage"];
        //        var jobid = Request.Form["jobid"];
        //        string comment = Request.Form["comment"];
        //        comment = Regex.Replace(comment, "<(.|\n)*?>", "");
        //        comment = Regex.Replace(comment, @"\t|\n|\r", "");
        //        var lotid = Request.Form["lotid"];
        //        var batchid = Request.Form["batchid"];
        //        var extravalues = Request.Form["extravalues"];
        //        var isnochange = Request.Form["isnochange"];

        //        oFieldsmodal = JsonConvert.DeserializeObject<Fields>(model); //JsonConvert.DeserializeObject<object>(model.ToString()).ToObject<Fields>().FirstOrDefault();

        //        var list = oWorkAreaService.checkLotTransactionStatus(oFieldsmodal.transid.ToString());
        //        if (isnochange == "true")
        //        {
        //            var updatelotchange = oWorkAreaService.updatenochange(oFieldsmodal.transid.ToString());
        //        }

        //        if (list != null)
        //        {
        //            var i1 = JsonConvert.DeserializeObject<object>(list.ToString());
        //            JArray a1 = JArray.Parse(i1.ToString());
        //            JObject obj1 = JObject.Parse(a1[0].ToString());
        //            string lotstatus = obj1["lotstatus"].ToString();
        //            if (lotstatus == "C" || lotstatus == "G")
        //            {
        //                return Ok("C");
        //            }
        //        }

        //        //S for Comments, H for Hold Comments, C for Currection Comments.
        //        var doption = "S";
        //        if (oFieldsmodal.option == "hold")
        //            doption = "H";
        //        if (oFieldsmodal.cflag == "B")
        //            doption = "C";
        //        if (oFieldsmodal.cflag == "G")
        //            doption = "G";

        //        if (httpRequest.Files.Count > 0)
        //        {
        //            var sFileName = httpRequest.Files[0];

        //            //DBContext db1 = new DBContext();
        //            if (batchid != "" && doption != "H")
        //            {
        //                var lotbatch = oWorkAreaService.getBatchStatus(batchid);
        //                if (lotbatch != null)
        //                {
        //                    var i_lotbatch = JsonConvert.DeserializeObject<object>(lotbatch.ToString());
        //                    JArray a_lotbatch = JArray.Parse(i_lotbatch.ToString());
        //                    JObject obj_lotbatch = JObject.Parse(a_lotbatch[0].ToString());
        //                    var lotid_lotbatch = obj_lotbatch["lotid"].ToString();
        //                    //need to check batch process
        //                    var insertComments_lotbatch = oWorkAreaService.insertLotComments(comment, sFileName.FileName, oFieldsmodal.transid.ToString(), doption, tostage, jobid, lotid);
        //                    var i2_lotbatch = JsonConvert.DeserializeObject<object>(insertComments_lotbatch.ToString());
        //                    JArray a2_lotbatch = JArray.Parse(i2_lotbatch.ToString());
        //                    JObject obj2_lotbatch = JObject.Parse(a2_lotbatch[0].ToString());
        //                    string cid_lotbatch = obj2_lotbatch["cid"].ToString();
        //                    string sPath_lotbatch = oWorkAreaService.getFileSaveLcation(Convert.ToInt32(oFieldsmodal.transid.ToString()));
        //                    sPath_lotbatch = sPath_lotbatch.Replace("/", "\\");
        //                    sPath_lotbatch = @"\\" + sPath_lotbatch;
        //                    if (sPath_lotbatch != string.Empty)
        //                    {
        //                        var serverPath_lotbatch = Path.Combine(sPath_lotbatch, "Comments");
        //                        if (!Directory.Exists(serverPath_lotbatch))
        //                            Directory.CreateDirectory(serverPath_lotbatch);
        //                        var serverPath1_lotbatch = Path.Combine(serverPath_lotbatch, cid_lotbatch);
        //                        if (!Directory.Exists(serverPath1_lotbatch))
        //                            Directory.CreateDirectory(serverPath1_lotbatch);
        //                        var filePath_lotbatch = serverPath1_lotbatch + "/" + sFileName.FileName;
        //                        using (var stream = new FileStream(filePath_lotbatch, FileMode.Create))
        //                        {
        //                            sFileName.CopyTo(stream);
        //                        }
        //                    }
        //                }

        //            }
        //            else
        //            {
        //                var insertComments = oWorkAreaService.insertLotComments(comment, sFileName.FileName, oFieldsmodal.transid.ToString(), doption, tostage, jobid, lotid);
        //                var i2 = JsonConvert.DeserializeObject<object>(insertComments.ToString());
        //                JArray a2 = JArray.Parse(i2.ToString());
        //                JObject obj2 = JObject.Parse(a2[0].ToString());
        //                string cid = obj2["cid"].ToString();
        //                string sPath = oWorkAreaService.getFileSaveLcation(Convert.ToInt32(oFieldsmodal.transid.ToString()));
        //                sPath = sPath.Replace("/", "\\");
        //                sPath = @"\\" + sPath;
        //                if (sPath != string.Empty)
        //                {
        //                    var serverPath = Path.Combine(sPath, "Comments");
        //                    if (!Directory.Exists(serverPath))
        //                        Directory.CreateDirectory(serverPath);
        //                    var serverPath1 = Path.Combine(serverPath, cid);
        //                    if (!Directory.Exists(serverPath1))
        //                        Directory.CreateDirectory(serverPath1);
        //                    var filePath = serverPath1 + "/" + sFileName.FileName;
        //                    using (var stream = new FileStream(filePath, FileMode.Create))
        //                    {
        //                        sFileName.CopyTo(stream);
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            if (batchid != "" && doption != "H")
        //            {
        //                var lotbatch = oWorkAreaService.getBatchStatus(batchid);
        //                if (lotbatch != null)
        //                {
        //                    var i_lotbatch = JsonConvert.DeserializeObject<object>(lotbatch.ToString());
        //                    JArray a_lotbatch = JArray.Parse(i_lotbatch.ToString());
        //                    JObject obj_lotbatch = JObject.Parse(a_lotbatch[0].ToString());
        //                    var lotid_lotbatch = obj_lotbatch["lotid"].ToString();
        //                    //need to check batch process
        //                    if (!string.IsNullOrEmpty(comment) || comment != "undefined")
        //                    {
        //                        var insertComments_lotbatch = oWorkAreaService.insertLotComments(comment, null, oFieldsmodal.transid.ToString(), doption, tostage, jobid, lotid);
        //                    }
        //                }
        //                //var lotbatch = db_.GetDataTable(db, "select lotid from lot_batch_details where batchid = " + batchid + " and ignored = false", null);
        //                //if (lotbatch.Rows.Count > 0)
        //                //{
        //                //    for (int i = 0; i <= lotbatch.Rows.Count - 1; i++)
        //                //    {
        //                //        lotid = lotbatch.Rows[i][0].ToString();
        //                //        var cid = insert_lot_comments(comment, null, fields.transid.ToString(), doption, tostage, jobid, lotid);
        //                //    }
        //                //}
        //            }
        //            else
        //            {
        //                if (!string.IsNullOrEmpty(comment) && comment != "undefined" && comment != "")
        //                {
        //                    var insertComments = oWorkAreaService.insertLotComments(comment, null, oFieldsmodal.transid.ToString(), doption, tostage, jobid, lotid);
        //                }

        //            }
        //        }



        //        long transactionid = oFieldsmodal.transid;
        //        string option = oFieldsmodal.option;
        //        string cfalg = oFieldsmodal.cflag;
        //        string userid = oFieldsmodal.userid;
        //        if (oFieldsmodal.fields != "null")
        //        {
        //            var metaFieldsUpdate = oWorkAreaService.metaFieldsUpdate(oFieldsmodal.transid.ToString(), oFieldsmodal.fields);
        //        }

        //       // var updateLotStatus = oWorkAreaService.updateLotStatus(oFieldsmodal.transid.ToString(), "Q"); if (lotid.ToString() != "")
        //        {
        //            var updateLotStatus = oWorkAreaService.updateLotStatus(oFieldsmodal.transid.ToString(), "Q");
        //        }

        //        lottraninfo lotinfo = new lottraninfo();
        //        lotinfo.p_tranid = transactionid.ToString();
        //        lotinfo.p_userid = userid;
        //        lotinfo.p_option = option;
        //        lotinfo.p_holdreason = "";

        //        if (option == "hold")
        //        {
        //            var usrLotTransactionUpdate = oWorkAreaService.getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "I", "hold", "0", lotinfo.p_holdreason);
        //            return Ok(usrLotTransactionUpdate);

        //        }
        //        else if (option == "checkout")
        //        {
        //            oCommonRepository.WriteLog("PostUpdatelot_transaction_V1:", "PostUpdatelot_transaction_V1-Checkout");
        //            if (cfalg == "G")
        //            {
        //                oCommonRepository.WriteLog("PostUpdatelot_transaction_V1:", "Flag:G");
        //                RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
        //            }
        //            else
        //            {
        //                oCommonRepository.WriteLog("PostUpdatelot_transaction_V1:", "Flag:else part");
        //                appdetails appdetails = new appdetails();
        //                appdetails = oWorkAreaService.CheckAppType(lotinfo.p_tranid, lotinfo.p_userid);

        //                if (appdetails != null)
        //                {
        //                    if (appdetails.checkin_app != null && appdetails.checkout_app != "" && appdetails.stagetype == "server")
        //                    {
        //                        RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                        sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkin_apps", "", "", cfalg, extravalues, "", "", comment);
        //                    }
        //                    else if (appdetails.checkout_app != null && appdetails.checkout_app != "")
        //                    {
        //                        var PublicationID = "";
        //                        if (lotid.ToString() != "")
        //                        {
        //                            var lotlist = _LotBatchService.GetSupplementDetailsBylotid(Int32.Parse(lotid));
        //                            if (lotlist != null)
        //                            {
        //                                var dt = JArray.Parse(lotlist.ToString());
        //                                var obj1_jobid = JObject.Parse(dt[0].ToString());
        //                                var Batch = obj1_jobid["batchname"].ToString();
        //                                var PublicationType = obj1_jobid["supplementtype"].ToString();

        //                                if (obj1_jobid["jobmetadata"].ToString() != "")
        //                                {
        //                                    var PublicationIDs = JArray.Parse(obj1_jobid["jobmetadata"].ToString());
        //                                    var publicationmetadataId = Startup.Configuration.GetValue<string>("AppSettings:publicationmetadataId");
        //                                    var metadatalists = PublicationIDs.Where(c =>
        //                                    c["jobmetaid"].ToString() == publicationmetadataId);
        //                                    foreach (var metadatalist in metadatalists)
        //                                    {
        //                                        PublicationID = metadatalist["FieldValue"].ToString();
        //                                    }
        //                                }
        //                                oCommonRepository.WriteLog("PostUpdatelot_transaction_V1:", "appdetails.checkout_app != null && appdetails.checkout_app != ''");
        //                                RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                                if (appdetails.coaisservice == 1)
        //                                {
        //                                    sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps_service_withfile", "", "", cfalg, extravalues, Batch, PublicationType, comment, PublicationID);
        //                                }
        //                                else
        //                                {
        //                                    sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps", "", "", cfalg, extravalues, Batch, PublicationType, comment, PublicationID);
        //                                }
        //                            }
        //                            else
        //                            {
        //                                if (appdetails.coaisservice == 1)
        //                                {
        //                                    RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                                    sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps_service_withfile", "", "", cfalg, extravalues, "", "", comment, PublicationID);
        //                                }
        //                                else
        //                                {
        //                                    RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                                    sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps", "", "", cfalg, extravalues, "", "", comment, PublicationID);
        //                                }
        //                            }
        //                        }
        //                        else
        //                        {
        //                            RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps_forcmapprove", "", "", cfalg, extravalues, "", "", comment, PublicationID);
        //                        }

        //                    }
        //                    else if (appdetails.process_without_file == 1)
        //                    {
        //                        oWorkAreaService.Checkout_transaction(lotinfo);
        //                    }
        //                    else if (appdetails.process_without_file == 0)
        //                    {
        //                        oCommonRepository.WriteLog("PostUpdatelot_transaction_V1 Started :", "PostUpdatelot_transaction_V1-process_without_file");
        //                        RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                        sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withfile", "", "", cfalg, extravalues);
        //                        oCommonRepository.WriteLog("PostUpdatelot_transaction_V1 after calling watcher :", "PostUpdatelot_transaction_V1-process_without_file");
        //                    }
        //                    else
        //                    {
        //                        RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                        sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
        //                    }
        //                }
        //                else
        //                {
        //                    RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                    sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
        //                }

        //            }

        //        }
        //        else if (option == "save")
        //        {
        //            appdetails appdetails = new appdetails();
        //            appdetails = oWorkAreaService.CheckAppType(lotinfo.p_tranid, lotinfo.p_userid);
        //            if (appdetails != null)
        //            {
        //                if (appdetails.inprocessapp != null)
        //                {
        //                    RabbitMq sendmsg = new RabbitMq(_requestClient);
        //                    sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "inprocess_apps", "", "", cfalg, extravalues, "", "", comment);
        //                }
        //            }
        //        }

        //        return Ok(list);
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //    //  return "Done";
        //}


        // [Authorize]
        [HttpPost("PostUpdatelot_transaction")]

        public object PostUpdatelot_transaction(Fields fields)
        {

            var extravalues = "";
            string stagename = string.Empty;
            string projectdefinitionid = string.Empty;
            var list = oWorkAreaService.checkLotTransactionStatus(fields.transid.ToString());

            if (list != null)
            {
                var i1 = JsonConvert.DeserializeObject<object>(list.ToString());
                JArray a1 = JArray.Parse(i1.ToString());
                JObject obj1 = JObject.Parse(a1[0].ToString());
                string lotstatus = obj1["lotstatus"].ToString();
                 stagename= obj1["stagename_alias"].ToString();
                projectdefinitionid = obj1["projectdefinitionid"].ToString();
                if (lotstatus == "C" || lotstatus == "G")
                {
                    return Ok("C");
                }
            }

            long transactionid = fields.transid;
            string option = fields.option;
            string cfalg = fields.cflag;
            string userid = fields.userid;
            if (fields.fields != "")
            {
                var metaFieldsUpdate = oWorkAreaService.metaFieldsUpdate(fields.transid.ToString(), fields.fields);
            }

            if (fields.comment != "")
            {
                if (option == "hold")
                {
                    var usrLotTransactionUpdate = oWorkAreaService.usrLotTransactionUpdate(fields.transid.ToString(), fields.userid, "I", "0", fields.comment, "hold_commentUpdatehr");
                }
                else
                {
                    var usrLotTransactionUpdate = oWorkAreaService.usrLotTransactionUpdate(fields.transid.ToString(), fields.userid, "I", "0", fields.comment, "hold_commentUpdater");
                }
            }
            var updateLotStatus = oWorkAreaService.updateLotStatus(fields.transid.ToString(), "Q");

            if(stagename == Startup.Configuration.GetValue<string>("AppSettings:OCR2stage") ||
                stagename == Startup.Configuration.GetValue<string>("AppSettings:OCR1stage")
                )
            {
                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission(projectdefinitionid))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                    {
                        WindowsIdentity useri = WindowsIdentity.GetCurrent();
                        System.Console.WriteLine(useri.Name);
                        //move files 
                        string nextstage_serverpath = oCommonRepository.GetServerPath(transactionid.ToString(), "serverinfo", true);
                        string nextstageinpath = Path.Combine(nextstage_serverpath, "IN");
                        string[] pdfFiles = Directory.GetFiles(nextstageinpath, "*_Redacted.pdf", SearchOption.AllDirectories);
                        string filenamewithextension = Path.GetFileName(pdfFiles[0]);
                        string ocrpath = Startup.Configuration.GetValue<string>("AppSettings:OCRInPath");
                        string ocrfilepath = Path.Combine(ocrpath, filenamewithextension);
                        System.IO.File.Copy(pdfFiles[0], ocrfilepath);
                    });
                }
                }

                lottraninfo lotinfo = new lottraninfo();
            lotinfo.p_tranid = transactionid.ToString();
            lotinfo.p_userid = userid;
            lotinfo.p_option = option;
            lotinfo.p_holdreason = fields.comment;

            if (option == "hold")
            {
                var usrLotTransactionUpdate = oWorkAreaService.getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "I", "hold", "0", lotinfo.p_holdreason);
                return Ok(usrLotTransactionUpdate);

            }
            else if (option == "checkout")
            {
                if (cfalg == "G")
                {
                    RabbitMq sendmsg = new RabbitMq(_requestClient);
                    sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout+_stage_withoutfile", "", "", cfalg, extravalues);
                }
                else
                {
                    appdetails appdetails = new appdetails();
                    appdetails = oWorkAreaService.CheckAppType(lotinfo.p_tranid, lotinfo.p_userid);

                    if (appdetails != null)
                    {

                        if (appdetails.checkin_app != null && appdetails.stagetype == "server")
                        {
                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkin_apps", "", "", cfalg, extravalues, "", "", "");
                        }

                        if (appdetails.checkin_app != null && appdetails.checkout_app != "" && appdetails.stagetype == "server")
                        {
                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkin_apps", "", "", cfalg, extravalues, "", "", "");
                        }
                        else if (appdetails.checkout_app != null && appdetails.checkout_app != "")
                        {
                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps", "", "", cfalg, extravalues, "", "", "");
                        }
                        else if (appdetails.process_without_file == 1)
                        {
                            oWorkAreaService.Checkout_transaction(lotinfo);
                        }
                        else if (appdetails.process_without_file == 0)
                        {
                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                            sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withfile", "", "", cfalg, extravalues);
                        }
                        else
                        {
                            RabbitMq sendmsg = new RabbitMq(_requestClient);
                            sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
                        }
                    }
                    else
                    {
                        RabbitMq sendmsg = new RabbitMq(_requestClient);
                        sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
                    }
                  

                }

                

            }

           


            else if (option == "save")
            {
                appdetails appdetails = new appdetails();
                appdetails = oWorkAreaService.CheckAppType(lotinfo.p_tranid, lotinfo.p_userid);
                if (appdetails != null)
                {
                    if (appdetails.inprocessapp != null)
                    {
                        RabbitMq sendmsg = new RabbitMq(_requestClient);
                        sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "inprocess_apps", "", "", cfalg, extravalues, "", "", "");
                    }
                }
            }

            return Ok(list);

        }
        [Authorize]
        [HttpPost("getCheckincur")]
        public object getCheckincur()
        {
            if (Request.Form != null)
            {
                lottraninfo lotinfo = new lottraninfo();
                lotinfo.p_tranid = Request.Form["tranid"];
                lotinfo.p_userid = Request.Form["userid"];
                lotinfo.p_option = Request.Form["p_option"];
                lotinfo.p_holdreason = "";
                lotinfo.jobworkflowid = Request.Form["jobworkflowid"];
                lotinfo.p_lotstatus = Request.Form["lotstatus"];
                var usrLotTransactionUpdate = oWorkAreaService.getCheckout(lotinfo.p_tranid, lotinfo.p_userid, lotinfo.p_lotstatus, lotinfo.p_option, lotinfo.jobworkflowid, lotinfo.p_holdreason);
                return Ok(usrLotTransactionUpdate); 
            }
            else
            {
                return null;
            }

        }
        [Authorize]
        [HttpPost("CC_PostUpdatelot_transaction")]
        public object CC_PostUpdatelot_transaction()
        {
            oCommonRepository.WriteLog("CC_PostUpdatelot_transaction Started:", "CC_PostUpdatelot_transaction");
            if (Request.Form != null)
            {
                string model = Request.Form["model"].ToString();
                string iReflectData = Request.Form["iReflect"].ToString();
                var jsonArray = JArray.Parse(model);
                string tostage = string.Empty;
                string jobid = string.Empty;
                string jobworkflowid = string.Empty;
                string skipto = string.Empty;
                string comment = string.Empty;
                string lotid = string.Empty;
                string batchid = string.Empty;
                string option = string.Empty;
                string cflag = string.Empty;
                long transactionid = 0;
                long selected_categorygroup = 0;
                string userid = string.Empty;
                string P_fromorder = string.Empty;
                string P_toorder = string.Empty;
                object return_result = null;
                string lotstatus_checkin = string.Empty;
                string mul_tranid = string.Empty;
                foreach (var i in jsonArray)
                {
                    tostage = i["tostage"].ToString();
                    jobid = i["jobid"].ToString();
                    jobworkflowid = i["jobworkflowid"].ToString();
                    skipto = i["skipto"].ToString();
                    comment = i["comment"].ToString();
                    comment = Regex.Replace(comment, "<(.|\n)*?>", "");
                    comment = Regex.Replace(comment, @"\t|\n|\r", "");
                    lotid = i["lotid"].ToString();
                    batchid = i["batchid"].ToString();
                    option = i["option"].ToString();
                    cflag = i["cflag"].ToString();
                    transactionid = Convert.ToInt64(i["transid"]);
                    userid = i["userid"].ToString();
                    P_fromorder = i["fromorder"].ToString();
                    P_toorder = i["toorder"].ToString();
                    selected_categorygroup = Convert.ToInt64(i["selected_categorygroup"]);
                    if (string.IsNullOrEmpty(mul_tranid))
                    {
                        mul_tranid = (i["transid"]).ToString();
                    }
                    else
                    {
                        mul_tranid =mul_tranid +","+(i["transid"]).ToString();
                    }
                    if (i["lotstatus_checkin"] != null)
                    {
                        lotstatus_checkin = i["lotstatus_checkin"].ToString();

                        if (lotstatus_checkin == "R")
                        {
                            lottraninfo lotinfo_checkin = new lottraninfo();
                            lotinfo_checkin.p_tranid = transactionid.ToString();
                            lotinfo_checkin.p_userid = userid;
                            lotinfo_checkin.p_option = "checkin";
                            lotinfo_checkin.p_holdreason = "";
                            lotinfo_checkin.jobworkflowid = jobworkflowid;
                            lotinfo_checkin.p_lotstatus = "P";
                            var usrLotTransactionUpdate = oWorkAreaService.getCheckout(lotinfo_checkin.p_tranid, lotinfo_checkin.p_userid, lotinfo_checkin.p_lotstatus, lotinfo_checkin.p_option, lotinfo_checkin.jobworkflowid, lotinfo_checkin.p_holdreason);
                        }
                    }
                    list = oWorkAreaService.checkLotTransactionStatus(transactionid.ToString());
                    if (list != null)
                    {
                        var i1 = JsonConvert.DeserializeObject<object>(list.ToString());
                        JArray a1 = JArray.Parse(i1.ToString());
                        JObject obj1 = JObject.Parse(a1[0].ToString());
                        string lotstatus = obj1["lotstatus"].ToString();
                        if (string.IsNullOrEmpty(tostage)) tostage = obj1["nextstage"].ToString();
                        //check already complete
                        if (lotstatus == "C" || lotstatus == "G")
                        {
                            return Ok("C");
                        }
                    }
                    //S for Comments, H for Hold Comments, C for Correction Comments.
                    var doption = "S";
                    if (option == "hold")
                        doption = "H";
                    if (cflag == "B")
                        doption = "C";
                    if (cflag == "G")
                        doption = "G";
                    //without file
                    if (batchid != "" && doption != "H")
                    {
                        //for batch
                        var lotbatch = oWorkAreaService.getBatchStatus(batchid);
                        if (lotbatch != null)
                        {
                            var i_lotbatch = JsonConvert.DeserializeObject<object>(lotbatch.ToString());
                            JArray a_lotbatch = JArray.Parse(i_lotbatch.ToString());
                            JObject obj_lotbatch = JObject.Parse(a_lotbatch[0].ToString());
                            var lotid_lotbatch = obj_lotbatch["lotid"].ToString();
                            //need to check batch process
                            if (comment != "undefined")
                            {
                                var insertComments_lotbatch = oWorkAreaService.insertLotComments(comment, null, transactionid.ToString(), doption, tostage, jobid, lotid);
                            }

                        }
                    }
                    else
                    {
                        //for lot
                        if (comment != "undefined" && comment !="")
                        {
                            var insertComments = oWorkAreaService.insertLotComments(comment, null, transactionid.ToString(), doption, tostage, jobid, lotid);
                        }
                    }
                    lottraninfo lotinfo = new lottraninfo();
                    lotinfo.p_tranid = transactionid.ToString();
                    lotinfo.p_userid = userid;
                    lotinfo.p_option = option;
                    lotinfo.p_holdreason = "";
                    lotinfo.jobworkflowid = jobworkflowid;
                    if (option == "hold")
                    {
                        var usrLotTransactionUpdate = oWorkAreaService.getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "I", "hold", "0", lotinfo.p_holdreason);
                        return Ok(usrLotTransactionUpdate);
                    }
                   // else if (option == "checkout" || option == "Bid date too close" || option == "New Project" || option == "With Docs")
                   else if (option == "checkout" || selected_categorygroup ==2)
                    {
                        oCommonRepository.WriteLog("CC_PostUpdatelot_transaction:", "CC_PostUpdatelot_transaction-Checkout");
                        oWorkAreaService.CC_Checkout_transaction(lotinfo, cflag, Convert.ToInt64(jobid));
                        //if (option == "Bid date too close" || option == "New Project" || option == "With Docs")
                        if (selected_categorygroup == 2)
                        {
                            lotmasterModel olotmaster = new lotmasterModel();
                            olotmaster.lotid = Convert.ToInt32(lotid);
                            olotmaster.lotstatus = option;
                            olotmaster.createdby = Convert.ToInt32(userid);
                            olotmaster.option = "updatelot_lotstatus";
                            string inputstr = JsonConvert.SerializeObject(olotmaster);
                            var retval1 = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, olotmaster.option);
                        }
                    }
                   // else if (option == "duplicate" || option == "norecord" || option == "skip" || option.Contains("Already Exist") || option.Contains("Query") || option.Contains("Invalid") || option.Contains("Broken Agent"))
                    else if (option == "duplicate" || option == "norecord" || option == "skip" || selected_categorygroup == 1)
                    {
                        var data = new { fromorder = P_fromorder, option = cflag, toorder = P_toorder, tranid = transactionid,userid= userid, categorygroup= selected_categorygroup };
                        oCommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data, option, null);
                    }

                }

                //if (jsonArray.Count > 1)
                //{
                //    var res = oWorkAreaService.InsertFor_Multiple_lot(jsonArray.ToString(), mul_tranid);
                    
                //    if (res.ToString() == "0")
                //        oCommonRepository.WriteLog("Multiple lot Inserted Successfully", "InsertForMultiple");
                //    else
                //        oCommonRepository.WriteLog("Error in inserting multiple lot Data", "InsertForMultiple");

                //}
                if (!string.IsNullOrEmpty(iReflectData) && iReflectData !="[]")
                {
                    //if (jsonArray.Count == 1)
                    //{
                    //    return_result = oWorkAreaService.InsertForIReflect(iReflectData);
                    //}
                    // else
                    // {
                        return_result = oWorkAreaService.InsertForIReflect_QA_Multiple(iReflectData);                       
                     //}
                    if (return_result != null)
                        oCommonRepository.WriteLog("Ireflect Data Inserted Successfully", "InsertForIReflect");
                    else
                        oCommonRepository.WriteLog("Error in inserting Ireflect Data", "InsertForIReflect");

                }
                return Ok(list);

            }
            else
            {
                return null;
            }
        }

        [AllowAnonymous]
        [HttpPost("Nextstagecreate/{tranid}/{userid}/{lotid}")]
        public IActionResult nextstagecreate(string tranid,string userid,string lotid)
        {
            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 = 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());
                            string jsonString = list.ToString();
                            var list_ = JsonConvert.DeserializeObject<List<Dictionary<string, Dictionary<string, int>>>>(jsonString);
                            int p_tranid = list_[0]["json_build_object"]["p_tranid"];
                            var lst = oWorkAreaService.getCheckout(p_tranid.ToString(), userid, "P", "checkin", "0", "");
                        }
                    }
                }
            }
            return Ok(list);
        }
        [AllowAnonymous]
        [HttpPost("checkin/{tranid}/{userid}")]
        public IActionResult checkin(string tranid, string userid)
        {
            var lst = (object)null;
            var data1 = new { vendorkey = tranid, p_option = "getlotstatusbyvendorkey" };
            var jsonstr1 = JsonConvert.SerializeObject(data1);
            var next_ordernores1 = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", jsonstr1);
            var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
            JArray LotDetails = JArray.Parse(next_ordernodata1.ToString());
            for (var item = 0; item < LotDetails.Count; item++)
            {
                 lst = oWorkAreaService.getCheckout(LotDetails[item]["transactionid"].ToString(), userid, "P", "checkin", "0", "");
            }
            return Ok(lst);
        }
        [AllowAnonymous]
        [HttpPost("getJobDetails")]
        public IActionResult getJobDetails([FromBody] object data)
        {
            var _list = oWorkAreaService.getJobDetails(data);
            return Ok(_list);
        }
        [AllowAnonymous]
        [HttpPost("getLotDetailsComments")]
        public IActionResult getLotDetailsComments([FromBody] object data)
        {
            var _list = oWorkAreaService.getLotDetailsComments(data);
            return Ok(_list);
        }
        //[Authorize]
        //[HttpGet("getalllotDetails/{jobid}")]
        //public IActionResult getalllotDetails(long jobid)
        //{
        //    try
        //    {
        //        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.cc_sp_selectjoblotlist", param, commandType: CommandType.StoredProcedure).ToList();
        //            //List<alllotdetails> json = new List<alllotdetails>();
        //            //foreach (var item in getReportJobDetails)
        //            //{
        //            //    json.Add(JsonConvert.DeserializeObject<alllotdetails>(item.ToString()));
        //            //}
        //            //return Ok(json);
        //            return Ok(getReportJobDetails);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        oCommonRepository.ErrorLog(ex);
        //        return BadRequest(new { message = ex.Message });
        //    }
        //}


        [Authorize]
        [HttpPost("getalllotDetails")]
        public IActionResult getalllotDetails(Get_lot_details data)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    var list = new
                    {
                        jobid = data.jobid,
                        prodefid = data.prodefid,
                        userid = data.userid,
                        jobworkflowid = data.jobworkflowid,
                    };
                    string inputstr = JsonConvert.SerializeObject(list);
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    param.Add("inputjsonstr", dbType: DbType.String, value: inputstr, direction: ParameterDirection.Input);
                    param.Add("mode_p", dbType: DbType.String, value: data.mode, direction: ParameterDirection.Input);
                    var getReportJobDetails = dbConnection.Query<string>("public.cc_sp_selectjoblotlist_new", param, commandType: CommandType.StoredProcedure).ToList();
                    return Ok(getReportJobDetails);
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpPost]
        public object PostUpdatelot_transaction_V1_extravalues()
        {
            //var httpRequest = HttpContext.Request.Form;
            //var model = Request.Form["model"];
            //var tostage = Request.Form["tostage"];
            //var jobid = Request.Form["jobid"];
            //var comment = Request.Form["comment"];
            //var lotid = Request.Form["lotid"];
            //var batchid = Request.Form["batchid"];
            //var extravalues = Request.Form["extravalues"];

            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //Fields fields = serializer.Deserialize<Fields>(model);

            //DBContext db = new DBContext();
            //BLDatamanipulation db_ = new BLDatamanipulation();
            //db.CheckLogin();

            //var lotstatus = db_.GetDataTable(db, "select lotstatus from lot_transaction where transactionid = " + fields.transid, null);
            //if (lotstatus.Rows.Count > 0) if (lotstatus.Rows[0][0].ToString() == "C" || lotstatus.Rows[0][0].ToString() == "G") return "C";

            ////S for Comments, H for Hold Comments, C for Currection Comments.
            //var doption = "S";
            //if (fields.option == "hold")
            //    doption = "H";
            //if (fields.cflag == "B")
            //    doption = "C";
            //if (fields.cflag == "G")
            //    doption = "G";

            //if (httpRequest.Files.Count > 0)
            //{
            //    var sFileName = httpRequest.Files[0];

            //    DBContext db1 = new DBContext();
            //    if (batchid != "" && doption != "H")
            //    {
            //        var lotbatch = db_.GetDataTable(db, "select lotid from lot_batch_details where batchid = " + batchid + " and ignored = false", null);
            //        if (lotbatch.Rows.Count > 0)
            //        {
            //            for (int i = 0; i <= lotbatch.Rows.Count - 1; i++)
            //            {
            //                lotid = lotbatch.Rows[i][0].ToString();
            //                var cid = insert_lot_comments(comment, sFileName.FileName, fields.transid.ToString(), doption, tostage, jobid, lotid);
            //                var serverPath = ConfigurationManager.AppSettings["serverfilepath"] + "/Comments/" + cid;
            //                if (!Directory.Exists(serverPath))
            //                    Directory.CreateDirectory(serverPath);
            //                var filePath = serverPath + "/" + sFileName.FileName;
            //                sFileName.SaveAs(filePath);
            //            }
            //        }
            //    }
            //    else
            //    {
            //        var cid = insert_lot_comments(comment, sFileName.FileName, fields.transid.ToString(), doption, tostage, jobid, lotid);
            //        var serverPath = ConfigurationManager.AppSettings["serverfilepath"] + "/Comments/" + cid;
            //        if (!Directory.Exists(serverPath))
            //            Directory.CreateDirectory(serverPath);
            //        var filePath = serverPath + "/" + sFileName.FileName;
            //        sFileName.SaveAs(filePath);
            //    }
            //}
            //else
            //{
            //    if (batchid != "" && doption != "H")
            //    {
            //        var lotbatch = db_.GetDataTable(db, "select lotid from lot_batch_details where batchid = " + batchid + " and ignored = false", null);
            //        if (lotbatch.Rows.Count > 0)
            //        {
            //            for (int i = 0; i <= lotbatch.Rows.Count - 1; i++)
            //            {
            //                lotid = lotbatch.Rows[i][0].ToString();
            //                var cid = insert_lot_comments(comment, null, fields.transid.ToString(), doption, tostage, jobid, lotid);
            //            }
            //        }
            //    }
            //    else
            //    {
            //        var cid = insert_lot_comments(comment, null, fields.transid.ToString(), doption, tostage, jobid, lotid);
            //    }
            //}

            //long transactionid = fields.transid;
            //string option = fields.option;
            ////string comment = fields.comment;
            //string cfalg = fields.cflag;
            //string userid = fields.userid;
            //if (string.IsNullOrEmpty(userid)) userid = (HttpContext.Current.Session["UserID"] as string);

            //if (fields.fields != "null")
            //{
            //    List<NpgsqlParameter> parms = new List<NpgsqlParameter>();
            //    db_.InsertQuery(db, "update lot_master set lotmastermetafields = '" + fields.fields + "' where lotid in (select a.lotid from lot_transaction a where a.transactionid = " + fields.transid + ")", parms);
            //    db_.InsertQuery(db, "update lot_transaction set lotmetafields = '" + fields.fields + "' where transactionid = " + fields.transid + "", parms);
            //}

            ////db_.InsertQuery(db, "update lot_transaction set lotstatus = 'Q'  where transactionid = " + fields.transid + "", null);

            //lot_tran_info lotinfo = new lot_tran_info();
            //lotinfo.p_tranid = transactionid.ToString();
            //lotinfo.p_userid = userid;
            //lotinfo.p_option = option;
            //lotinfo.p_holdreason = "";

            //if (option == "hold")
            //{
            //    getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "I", "hold", "0", lotinfo.p_holdreason);
            //}
            //else if (option == "checkout")
            //{

            //    if (cfalg == "G")
            //    {
            //        RabbitMq sendmsg = new RabbitMq();
            //        sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
            //    }
            //    else
            //    {
            //        List<appdetails> appdetails = new List<appdetails>();
            //        appdetails = CheckAppType(lotinfo.p_tranid, lotinfo.p_userid);
            //        if (appdetails.Count > 0)
            //        {
            //            if (appdetails[0].checkin_app != null && appdetails[0].stagetype == "server")
            //            {
            //                RabbitMq sendmsg = new RabbitMq();
            //                sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkin_apps", "", "", cfalg, extravalues);
            //            }
            //            else if (appdetails[0].checkout_app != null)
            //            {
            //                RabbitMq sendmsg = new RabbitMq();
            //                sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_apps", "", "", cfalg, extravalues);
            //            }
            //            else if (appdetails[0].process_without_file == 1)
            //            {
            //                Checkout_transaction(lotinfo);
            //            }
            //            else if (appdetails[0].process_without_file == 0)
            //            {
            //                RabbitMq sendmsg = new RabbitMq();
            //                sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withfile", "", "", cfalg, extravalues);
            //            }
            //            else
            //            {
            //                RabbitMq sendmsg = new RabbitMq();
            //                sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
            //            }
            //        }
            //        else
            //        {
            //            RabbitMq sendmsg = new RabbitMq();
            //            sendmsg.SendMq_StageComplete(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
            //        }
            //    }
            //    //**If equal to File Move
            //}
            //else if (option == "save")
            //{
            //    List<appdetails> appdetails = new List<appdetails>();
            //    appdetails = CheckAppType(lotinfo.p_tranid, lotinfo.p_userid);
            //    if (appdetails.Count > 0)
            //    {
            //        if (appdetails[0].inprocessapp != null)
            //        {
            //            RabbitMq sendmsg = new RabbitMq();
            //            sendmsg.SendMq_WorkArea(lotinfo.p_tranid.ToString(), lotinfo.p_userid, "inprocess_apps", "", "", cfalg, extravalues);
            //        }
            //    }
            //    //**If equal to File Move
            //}
            return "Done";
        }
        [Authorize]
        [HttpPost]
        public object PostUpdatelot_transaction_V1_comments_only()
        {
            //var httpRequest = HttpContext.Request.Form;
            //var model = Request.Form["model"];
            //var tostage = Request.Form["tostage"];
            //var jobid = Request.Form["jobid"];
            //var comment = Request.Form["comment"];
            //var lotid = Request.Form["lotid"];
            //var batchid = Request.Form["batchid"];
            //var extravalues = Request.Form["extravalues"];

            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //Fields fields = serializer.Deserialize<Fields>(model);

            //DBContext db = new DBContext();
            //BLDatamanipulation db_ = new BLDatamanipulation();
            //db.CheckLogin();

            //var lotstatus = db_.GetDataTable(db, "select lotstatus from lot_transaction where transactionid = " + fields.transid, null);
            //if (lotstatus.Rows.Count > 0) if (lotstatus.Rows[0][0].ToString() == "C" || lotstatus.Rows[0][0].ToString() == "G") return "C";

            ////S for Comments, H for Hold Comments, C for Currection Comments.
            //var doption = "S";
            //if (fields.option == "hold")
            //    doption = "H";
            //if (fields.cflag == "B")
            //    doption = "C";
            //if (fields.cflag == "G")
            //    doption = "G";

            //if (httpRequest.Files.Count > 0)
            //{
            //    var sFileName = httpRequest.Files[0];

            //    DBContext db1 = new DBContext();
            //    if (batchid != "" && doption != "H")
            //    {
            //        var lotbatch = db_.GetDataTable(db, "select lotid from lot_batch_details where batchid = " + batchid + " and ignored = false", null);
            //        if (lotbatch.Rows.Count > 0)
            //        {
            //            for (int i = 0; i <= lotbatch.Rows.Count - 1; i++)
            //            {
            //                lotid = lotbatch.Rows[i][0].ToString();
            //                var cid = insert_lot_comments(comment, sFileName.FileName, fields.transid.ToString(), doption, tostage, jobid, lotid);
            //                var serverPath = ConfigurationManager.AppSettings["serverfilepath"] + "/Comments/" + cid;
            //                if (!Directory.Exists(serverPath))
            //                    Directory.CreateDirectory(serverPath);
            //                var filePath = serverPath + "/" + sFileName.FileName;
            //                sFileName.SaveAs(filePath);
            //            }
            //        }
            //    }
            //    else
            //    {
            //        var cid = insert_lot_comments(comment, sFileName.FileName, fields.transid.ToString(), doption, tostage, jobid, lotid);
            //        var serverPath = ConfigurationManager.AppSettings["serverfilepath"] + "/Comments/" + cid;
            //        if (!Directory.Exists(serverPath))
            //            Directory.CreateDirectory(serverPath);
            //        var filePath = serverPath + "/" + sFileName.FileName;
            //        sFileName.SaveAs(filePath);
            //    }
            //}
            //else
            //{
            //    if (batchid != "" && doption != "H")
            //    {
            //        var lotbatch = db_.GetDataTable(db, "select lotid from lot_batch_details where batchid = " + batchid + " and ignored = false", null);
            //        if (lotbatch.Rows.Count > 0)
            //        {
            //            for (int i = 0; i <= lotbatch.Rows.Count - 1; i++)
            //            {
            //                lotid = lotbatch.Rows[i][0].ToString();
            //                var cid = insert_lot_comments(comment, null, fields.transid.ToString(), doption, tostage, jobid, lotid);
            //            }
            //        }
            //    }
            //    else
            //    {
            //        var cid = insert_lot_comments(comment, null, fields.transid.ToString(), doption, tostage, jobid, lotid);
            //    }
            //}
            return "Done";
        }

        [HttpPost]

        public object PostUpdatelot_transaction_V1_MSMQ(string p_tranid, string p_userid, string apptype, string cfalg, string extravalues)
        {
            if (cfalg == "G")
            {
                RabbitMq sendmsg = new RabbitMq(_requestClient);
                sendmsg.SendMq_StageComplete(p_tranid.ToString(), p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
            }
            else
            {
                appdetails appdetails = new appdetails();
                appdetails = oWorkAreaService.CheckAppType(p_tranid, p_userid);
                if (appdetails != null)
                {
                    if (appdetails.checkin_app != null && appdetails.stagetype == "server")
                    {
                        RabbitMq sendmsg = new RabbitMq(_requestClient);
                        sendmsg.SendMq_WorkArea(p_tranid.ToString(), p_userid, "checkin_apps", "", "", cfalg, extravalues);
                    }
                    else if (appdetails.checkout_app != null)
                    {
                        RabbitMq sendmsg = new RabbitMq(_requestClient);
                        sendmsg.SendMq_WorkArea(p_tranid.ToString(), p_userid, "checkout_apps", "", "", cfalg, extravalues);
                    }

                    else if (appdetails.process_without_file == 0)
                    {
                        RabbitMq sendmsg = new RabbitMq(_requestClient);
                        sendmsg.SendMq_StageComplete(p_tranid.ToString(), p_userid, "checkout_stage_withfile", "", "", cfalg, extravalues);
                    }
                    else
                    {
                        RabbitMq sendmsg = new RabbitMq(_requestClient);
                        sendmsg.SendMq_StageComplete(p_tranid.ToString(), p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
                    }
                }
                else
                {
                    RabbitMq sendmsg = new RabbitMq(_requestClient);
                    sendmsg.SendMq_StageComplete(p_tranid.ToString(), p_userid, "checkout_stage_withoutfile", "", "", cfalg, extravalues);
                }
            }
            return true;
        }

        [HttpPost("Call_Msmq_watcher")]

        public object Call_Msmq_watcher(string p_tranid, string p_userid, string checkout, string cfalg)
        {
            //DBContext db = new DBContext();
            //BLDatamanipulation db_ = new BLDatamanipulation();
            //db_.InsertQuery(db, "update lot_transaction set lotstatus = 'Q'  where transactionid = " + p_tranid + "", null);

            RabbitMq sendmsg = new RabbitMq(_requestClient);
            sendmsg.SendMq_StageComplete(p_tranid.ToString(), p_userid, checkout, "", "", cfalg, "");
            return true;
        }
        [HttpGet]
        public object tetx()
        {
            return true;

        }

        public void laps_queue_status(string tranid, string queue_id, string status, string remarks, string message_from, string apptype, string cflag, string extravalues)
        {
            try
            {
                //var squery = "select * from laps_queue_status_function(" + tranid + ",'" + queue_id + "','" + status + "','" + DateTime.Now.ToString() + "',null,null,'insert','" + remarks + "','" + message_from + "','" + apptype + "','" + cflag + "','" + extravalues + "')";
                //DBContext db = new DBContext();
                //BLDatamanipulation db_ = new BLDatamanipulation();
                //var lotstatus = db_.GetDataTable(db, squery, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }

        public void TriggerMail(string tranid, string ordernumber, string nxttranid)
        {
            try
            {
                if (ordernumber == "1")
                {
                    System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_PM?tranid=", tranid, "&sflag=", "1")));
                    System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_Ack?tranid=", tranid, "&sflag=", "2")));
                }
                else if (ordernumber == "2")
                {
                    System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_SignOff?tranid=", nxttranid, "&jobworkflowid=", 0, "&sflag=", "2", "&curtranid=", tranid)));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }
        public void SendMailRequest(string apiUrl)
        {
            try
            {
                HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
                authRequest.ContentType = "application/xml";
                authRequest.Method = "POST";
                authRequest.ContentLength = 0;
                WebResponse authResponseTwitter = authRequest.GetResponse();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }
        public int insert_lot_comments(string comment, string FileName, string transid, string doption, string tostage, string jobid, string lotid)
        {
            var cid = oWorkAreaService.insertLotComments(comment, FileName, transid, doption, tostage, jobid, lotid);
            return Convert.ToInt32(cid);

        }
        [HttpPost]


        public List<jobmetafields> GetJobMetaData(string tranid, string completedtranid, string jobworkflowid)
        {
            //DBContext db = new DBContext();
            //BLDatamanipulation db1 = new BLDatamanipulation();
            var finalout = new List<jobmetafields>();
            //var workflowid = "";
            //var completed_workflowid = ""; var job_id = "";
            //DataTable dt = db1.GetDataTable(db, "select wfdid,jobid from job_workflow_master a where a.jobworkflowid = " + jobworkflowid + "", null);
            //if (dt.Rows.Count > 0)
            //{
            //    completed_workflowid = dt.Rows[0]["wfdid"].ToString();
            //    job_id = dt.Rows[0]["jobid"].ToString();
            //}

            //var str = "select b.jobmetafields as jobworkflow_metafields,b.wfdid,c.lotmastermetafields as lot_metafields from lot_transaction a left outer join job_workflow_master b on a.jobworkflowid = b.jobworkflowid left outer join lot_master c on c.lotid = a.lotid where a.transactionid = @tranid";
            //var jobmeta = db.Database.SqlQuery<lot_tran_metafields>(str, new Npgsql.NpgsqlParameter { ParameterName = "@tranid", Value = tranid }).ToList();
            //if (jobmeta.Count > 0)
            //{
            //    //jobworkflow_metafields
            //    var jobworkflow_metafields = new List<jobmetafields>();
            //    var lotmastermetafields = new List<jobmetafields>();

            //    foreach (var item in jobmeta)
            //    {
            //        if (item.jobworkflow_metafields != null)
            //        {
            //            dynamic json = JsonConvert.DeserializeObject(item.jobworkflow_metafields);
            //            workflowid = item.wfdid.ToString();
            //            for (int i = 0; i < json.Count; i++)
            //            {
            //                var jdata = new jobmetafields();
            //                foreach (var s in json[i])
            //                {
            //                    if (s.Name == "name")
            //                        jdata.name = string.Join(",", s);
            //                    else if (s.Name == "type")
            //                        jdata.type = string.Join(",", s);
            //                    else if (s.Name == "value")
            //                        jdata.value = string.Join(",", s);
            //                    else if (s.Name == "workflowdid")
            //                        jdata.workflowdid = string.Join(",", s);
            //                    else if (s.Name == "label")
            //                        jdata.label = string.Join(",", s);
            //                }
            //                jobworkflow_metafields.Add(jdata);
            //            }
            //            //lotmastermetafields
            //            dynamic json_ = JsonConvert.DeserializeObject(item.lot_metafields);
            //            for (int i = 0; i < json_.Count; i++)
            //            {
            //                var jdata = new jobmetafields();
            //                foreach (var s in json_[i])
            //                {
            //                    if (s.Name == "name")
            //                        jdata.name = string.Join(",", s);
            //                    else if (s.Name == "type")
            //                        jdata.type = string.Join(",", s);
            //                    else if (s.Name == "value")
            //                        jdata.value = string.Join(",", s);
            //                    else if (s.Name == "workflowdid")
            //                        jdata.workflowdid = string.Join(",", s);
            //                    else if (s.Name == "label")
            //                        jdata.label = string.Join(",", s);
            //                }
            //                lotmastermetafields.Add(jdata);
            //            }
            //        }
            //    }

            //    var completed_field = (from job in jobworkflow_metafields
            //                           join lot in lotmastermetafields on new { job.workflowdid, job.name } equals new { lot.workflowdid, lot.name } //where lot.workflowdid == completed_workflowid
            //                           select new
            //                           {
            //                               lot.name,
            //                               lot.type,
            //                               job.label,
            //                               lot.workflowdid,
            //                               lot.value,
            //                               lot.status
            //                           }).ToList();

            //    var current_field = (from job in jobworkflow_metafields
            //                         where job.workflowdid == workflowid
            //                         select new
            //                         {
            //                             job.name,
            //                             job.type,
            //                             job.label,
            //                             job.workflowdid,
            //                             job.value,
            //                             job.status
            //                         }).ToList();

            //    foreach (var item in completed_field)
            //    {
            //        var stemp = new jobmetafields();
            //        stemp.name = item.name;
            //        stemp.type = item.type;
            //        stemp.label = item.label.Replace("$$JobNo", job_id);
            //        stemp.workflowdid = item.workflowdid;
            //        stemp.value = item.value;
            //        stemp.status = "Completed";
            //        finalout.Add(stemp);
            //    }
            //    foreach (var item in current_field)
            //    {
            //        var stemp = new jobmetafields();
            //        stemp.name = item.name;
            //        stemp.type = item.type;
            //        stemp.label = item.label;
            //        stemp.workflowdid = item.workflowdid;
            //        stemp.value = item.value;
            //        stemp.status = "Current";
            //        finalout.Add(stemp);
            //    }

            //}
            return finalout;
        }
        public object Postmail_SignOff(string tranid, string jobworkflowid, string sflag, string curtranid, List<jobmetafields> smeta)
        {
            //try
            //{
            //    using (DBContext db = new DBContext())
            //    {
            //        using (MailMessage mailMessage = new MailMessage())
            //        {

            //            string allocationtypename = ""; var frommail = "";
            //            var allocationtype = db.Database.SqlQuery<jsonvalue>("select json_build_object('allocationtypeid',jwm.allocationtype, 'allocationtype',atm.allocationtype)as json from lot_transaction lt left join job_workflow_master jwm  on lt.jobworkflowid=jwm.jobworkflowid left join allocationtype_master atm on atm.allocationtypeid = jwm.allocationtype where lt.transactionid = @tranid", new Npgsql.NpgsqlParameter { ParameterName = "@tranid", Value = tranid }).ToList();
            //            if (allocationtype.Count > 0)
            //            {
            //                foreach (var item in allocationtype)
            //                {
            //                    allocation obj = JsonConvert.DeserializeObject<allocation>(item.json);
            //                    allocationtypename = obj.allocationtype;
            //                }
            //            }
            //            if (allocationtypename.Contains("Push"))
            //                sflag = "2";
            //            else if (allocationtypename.Contains("Pull"))
            //                sflag = "3";

            //            var emaildetails = db.Database.SqlQuery<jsonvalue>("select * from  usr_email_info_job_v1(@p_tranid,@p_wfdid, @p_option,@p_curtranid) as json",
            //            new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = tranid },
            //            new Npgsql.NpgsqlParameter { ParameterName = "@p_wfdid", Value = jobworkflowid },
            //            new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = sflag },
            //            new Npgsql.NpgsqlParameter { ParameterName = "@p_curtranid", Value = curtranid }).ToList();
            //            long userId_s = Convert.ToInt64((HttpContext.Current.Session["UserID"] as string));
            //            var from_mailid = db.User_Masters.Where(u => u.userid == userId_s).Select(u => u.emailid).ToList();
            //            if (from_mailid.Count > 0)
            //                frommail = from_mailid[0];

            //            if (emaildetails.Count > 0)
            //            {
            //                foreach (var item in emaildetails)
            //                {
            //                    emaildata_v1 obj = JsonConvert.DeserializeObject<emaildata_v1>(item.json);
            //                    if (obj.signoffnotification == 1)
            //                    {
            //                        StringBuilder sb = new StringBuilder(obj.body);
            //                        StringBuilder subject = new StringBuilder(obj.subject);

            //                        dynamic json = JsonConvert.DeserializeObject(item.json);
            //                        foreach (var s in json)
            //                        {
            //                            subject.Replace("$$" + s.Name, string.Join(",", s));
            //                            sb.Replace("$$" + s.Name, string.Join(",", s));
            //                        }

            //                        var userdetails = db.Database.SqlQuery<jsonvalue>("select * from  usr_email_info_userdetails(@p_userid,@p_option) as json",
            //                        new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = obj.userid },
            //                        new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "1" }).ToList();
            //                        string PMmail = "";
            //                        if (userdetails.Count > 0)
            //                        {
            //                            dynamic json1 = JsonConvert.DeserializeObject(userdetails[0].json);
            //                            foreach (var s in json1)
            //                            {
            //                                subject.Replace("$$" + s.Name, string.Join(",", s));
            //                                sb.Replace("$$" + s.Name, string.Join(",", s));
            //                                if (s.Name == "PM_mail") PMmail = string.Join(",", s);
            //                            }
            //                        }
            //                        mailMessage.Subject = subject.ToString();

            //                        ServerInfo servinfo1 = new ServerInfo();
            //                        var FilledValue = ""; var CurrentValue = "";
            //                        foreach (var metaitem in smeta)
            //                        {
            //                            if (metaitem.status == "Completed")
            //                                FilledValue = FilledValue + metaitem.label + " : " + metaitem.value + " <br>";
            //                            if (metaitem.status == "Current")
            //                            {
            //                                if (metaitem.label != "")
            //                                    CurrentValue = CurrentValue + metaitem.label + " : " + metaitem.value + " <br>";
            //                            }
            //                        }
            //                        if (CurrentValue == "")
            //                            CurrentValue = @"Click ""Complete"" button to finish the task.";
            //                        else
            //                            CurrentValue = "2. Provide below details: <br> " + CurrentValue;
            //                        sb.Replace("$$completed", FilledValue);
            //                        sb.Replace("$$current", CurrentValue);

            //                        if (frommail == "") frommail = obj.emailid;
            //                        if (obj.emailid != null) mailMessage.To.Add(new MailAddress(obj.emailid));
            //                        if (PMmail != "") mailMessage.To.Add(new MailAddress(PMmail));
            //                        if (obj.defemailid != null)
            //                        {
            //                            var dt1 = servinfo1.GetDataSet("select emailid from mail_template_mailid md left outer join user_master um on um.userid = md.userid where mtid = " + obj.defemailid + "");
            //                            if (dt1.Tables[0].Rows.Count > 0)
            //                            {
            //                                for (int i = 0; i <= dt1.Tables[0].Rows.Count - 1; i++)
            //                                {
            //                                    if (dt1.Tables[0].Rows[i][0].ToString() != "")
            //                                        mailMessage.To.Add(new MailAddress(dt1.Tables[0].Rows[i][0].ToString()));
            //                                }
            //                            }
            //                        }

            //                        var dt2 = servinfo1.GetDataSet("SELECT fieldvalue FROM public.mailtemplatevalues where active = 1");
            //                        for (int i = 0; i <= dt2.Tables[0].Rows.Count - 1; i++)
            //                        {
            //                            subject.Replace(dt2.Tables[0].Rows[i]["fieldvalue"].ToString(), "");
            //                            sb.Replace(dt2.Tables[0].Rows[i]["fieldvalue"].ToString(), "");
            //                        }

            //                        MailAddress fromAddress = null;
            //                        SmtpClient smtp = new SmtpClient();
            //                        fromAddress = new MailAddress("workflow.ssg@luminad.com", "PM Assist");
            //                        smtp.Host = "mail.luminad.com";
            //                        smtp.EnableSsl = true;
            //                        System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential("workflow.ssg@luminad.com", "69Tt5fvm");
            //                        smtp.Credentials = myCredential;
            //                        mailMessage.From = fromAddress;
            //                        string b = WebUtility.HtmlDecode(sb.ToString());
            //                        mailMessage.Body = b;
            //                        mailMessage.IsBodyHtml = true;
            //                        smtp.Send(mailMessage);

            //                        Email_Master email = new Email_Master();
            //                        email.transactionid = Convert.ToInt32(obj.transactionid);
            //                        email.mailsubject = mailMessage.Subject;
            //                        email.mailfrom = frommail;
            //                        email.mailto = String.Join(";", mailMessage.To);
            //                        email.mailbody = mailMessage.Body;
            //                        email.senton = DateTime.Now;
            //                        email.readflag = 0;
            //                        db.MailBoxs.Add(email);
            //                        db.SaveChanges();

            //                    }
            //                }

            //            }
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{

            //}
            return Ok();
        }
        private void CreateZip(string directoryPathToZip, string outputZipFileName)
        {
            //try
            //{
            //    if (File.Exists(outputZipFileName))
            //        File.Delete(outputZipFileName);
            //    using (ZipFile outputZip = new ZipFile(outputZipFileName))
            //    {
            //        outputZip.AddDirectory(directoryPathToZip);
            //        outputZip.Save();
            //    }
            //}
            //catch (Exception ex)
            //{ }
        }

        [Authorize]
        [HttpPost]
        public object SaveStage(Fields fields)
        {
            //BLDatamanipulation db = new BLDatamanipulation();
            //DBContext db1 = new DBContext();
            //List<NpgsqlParameter> parms = new List<NpgsqlParameter>();
            //db.InsertQuery(db1, "update lot_master set lotmastermetafields = '" + fields.fields + "' where lotid in (select a.lotid from lot_transaction a where a.transactionid = " + fields.transid + ")", parms);
            //db.InsertQuery(db1, "update lot_transaction set lotmetafields = '" + fields.fields + "' where transactionid = " + fields.transid + "", parms);

            return Ok();
        }

        [HttpGet]

        public void call_sendmail(string p_tranid, string nexttranval, string jobworkflowid, string userId_t)
        {
            RabbitMq sendmsg = new RabbitMq(_requestClient);
            sendmsg.SendMqMail(p_tranid.ToString(), jobworkflowid.ToString(), "2", nexttranval.ToString(), userId_t.ToString());
        }


        [AllowAnonymous]
        [HttpPost("DownloadFormFile")]
        public IActionResult DownloadFormFile(dynamic fileData)
        {
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            int tranid = Convert.ToInt32(fileData.Transactionid.ToString());
            string webRootPath = oWorkAreaService.getFileSaveLcation(tranid);
            string filePath = string.Empty;
            //string folderPath = Path.Combine(webRootPath, folderName, fileData.Transactionid.ToString().ToLower(), fileData.cid.ToString());
            string folderPath = @"\\" + webRootPath.ToString().Replace("/", @"\");
            if (Directory.Exists(folderPath))
            {
                DirectoryInfo dinfo = new DirectoryInfo(folderPath);
                DirectoryInfo latestdir = dinfo.GetDirectories().OrderByDescending(f => f.CreationTime).FirstOrDefault();
                string tmppath = "";
                if (latestdir != null)
                {
                    tmppath = Path.Combine(folderPath, latestdir.Name.ToString(), fileData.cid.ToString(), fileData.fileName.ToString());
                    if (System.IO.File.Exists(tmppath))
                    { filePath = tmppath; }
                }
                else
                {
                    tmppath = Path.Combine(folderPath, fileData.fileName.ToString());
                    if (System.IO.File.Exists(tmppath))
                    { filePath = tmppath; }
                }
            }
            if (filePath != "" || filePath.Length > 0)
            {
                byte[] file = System.IO.File.ReadAllBytes(filePath);
                return Ok(new { File = file });
            }
            else
            {
                return BadRequest(new { message = "File notfound" });
            }
            // return Ok();
        }

        [Authorize]
        [HttpGet("getchecklistdetails/{tranid}")]
        public IActionResult getchecklistdetails(int tranid)
        {
            var user = oWorkAreaService.getchecklistdetails(tranid);
            return Ok(user);
        }


        [Authorize]
        [HttpPost("InsertchecklistTransaction")]
        public IActionResult InsertchecklistTransaction([FromBody] Checklistdetail[] ochecklistdetail)
        {
            int retval = 0;
            try
            {
                for (int i = 0; i < ochecklistdetail.Length; i++)
                {
                    retval = oWorkAreaService.insertCheckListTransaction(ochecklistdetail[i]);
                }
                return Ok(retval);
            }
            catch (Exception ex)
            {
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpGet("GetPreviousStageTranid/{tranid}")]
        public IActionResult GetPreviousStageTranid(int tranid)
        {
            var user = oWorkAreaService.getPreviousStageTranid(tranid);
            return Ok(user);
        }

        [Authorize]
        [HttpGet("GetFeatureList")]
        public IActionResult GetFeatureList()
        {
            try
            {

                var array = _config.GetSection("Features").GetChildren().ToList();
                //.Select(configSection => configSection.Value);

                List<object> features = new List<object>();

                for (int i = 0; i < array.Count; i++)
                {
                    var id = _config.GetValue<int>(array[i].Path + ":metadataid");
                    var metadata = _config.GetValue<string>(array[i].Path + ":mdata");
                    features.Add(new { metadataid = id, mdata = metadata });
                }

                //_config.GetValue<string>("AppSettings:Secret");

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

        }

        //code to add the project workflow definition 
        [Authorize] 
        [HttpPost("updateStatusandProductionId")]
        public IActionResult updateStatusandProductionId([FromBody] List<lotmasterModel> olotmasterModelModel)
        {
            try
            {
                var list = oWorkAreaService.updateStatusandProductionId(olotmasterModelModel);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        //code to add the project workflow definition 
        [Authorize]
        [HttpPost("CMApprovalUpdate")]
        public IActionResult CMApprovalUpdate([FromBody] List<lotmasterModel> olotmasterModelModel)
        {
            try
            {
                foreach (var metadatalist in olotmasterModelModel)
                {
                    var transobject = new
                    {
                        tranid = metadatalist.transactionid,
                        fromorder = 3,
                        toorder = 5,
                        option = 'F'
                    };
                    var jsonstr = JsonConvert.SerializeObject(transobject);
                    var list = oWorkAreaService.CMApprovalUpdate(jsonstr);
                }
                return Ok();
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }


        [Authorize]
        [HttpPost("Author_MS_Review")]
        public IActionResult Author_MS_Review(Checklistdetail oChecklistdetail)
        {
            oCommonRepository.WriteLog("Author_MS_Review:", "calling Author_MS_Review");
            var url = "https://klidev.luminad.com/orchestration/api/CdbApi/Author_MS_Review";
            var client = new RestClient(url);
            var cdbapiRequest = new RestRequest(Method.POST);
            cdbapiRequest.AddHeader("Content-Type", "application/json");
            cdbapiRequest.RequestFormat = DataFormat.Json;
            cdbapiRequest.AddParameter("application/json", "" +
                                                        "{ " +
                                                        "\"tranid\":" + oChecklistdetail.tranid +
                                                        "}", ParameterType.RequestBody);
            // cdbapiRequest.AddParameter("tranid" , oChecklistdetail.tranid);
            IRestResponse responseResult = client.Execute(cdbapiRequest);
            return Ok(responseResult.StatusCode);
        }

        [Authorize]
        [HttpPost("Recorderror")]
        public IActionResult Recorderror()
        {
            try
            {
                var httpRequest = HttpContext.Request.Form;
                var mode = Request.Form["mode"].ToString();

                var errorid = Request.Form["errorid"].ToString();
                var errortype = Request.Form["errortype"].ToString();
                var qaremarks = Request.Form["remarks"].ToString();
                var projectid = Request.Form["projectid"].ToString();
                var prodefid = Request.Form["projectdefinitionid"].ToString();
                var productionagent = Request.Form["productionagent"].ToString();
                var jobtitle = Request.Form["jobtitle"].ToString();
                var qaagent = Request.Form["qaagent"].ToString();
                var lottile = Request.Form["lottitle"].ToString();
                var productiondate = Request.Form["productiondate"].ToString();
                var qadate = Request.Form["qadate"].ToString();
                var createdby = Request.Form["createdby"].ToString();
                var biddate = Request.Form["biddate"].ToString();
                var jobid = Request.Form["jobid"];
                var tranid = Request.Form["tranid"];
                //var multiple_tranid = Request.Form["multiple_tranid"].ToString();
                var lotid = Request.Form["lotid"];
                var recorderrorid = Request.Form["recorderrorid"];
                var updatedby = Request.Form["updatedby"];
                var active = Request.Form["active"];
                var transid = Request.Form["transid"];
                var bidentryid = Request.Form["bidentryid"];
                var userid = Request.Form["userid"];
                var in_ = Request.Form["input_filename"];
                var out_ = Request.Form["output_filename"];
                var startdate = Request.Form["p_startdate"];
                var enddate = Request.Form["p_enddate"];
                string in_filename = "";
                string out_filename = "";

                List<File> bal_in_files = new List<File>();
                List<File> bal_out_files = new List<File>();

                var file_ = HttpContext.Request.Form.Files.Count;


                if (mode == "get")
                {
                    var list = new { jobid = Convert.ToInt64(jobid), tranid = Convert.ToInt64(tranid), lotid = Convert.ToInt64(lotid) };
                    //, multiple_tranid= multiple_tranid
                    string input = JsonConvert.SerializeObject(list);
                    var _list = oWorkAreaService.GetRecorderrorDetails(input);

                    return Ok(_list);
                }
                else if (mode == "dashboard_report")
                {
                    var list = new { jobid = Convert.ToInt64(jobid), tranid = Convert.ToInt64(tranid), lotid = Convert.ToInt64(lotid), userid = Convert.ToInt64(userid), projectid = Convert.ToInt64(projectid), startdate = startdate, enddate = enddate };
                    string input = JsonConvert.SerializeObject(list);
                    var _list = oWorkAreaService.Dashboard_RecordError(input);
                    return Ok(_list);

                }
                else if (mode == "add" || mode == "edit" || mode == "delete")
                {
                    List<File> in_file = new List<File>();
                    List<File> out_file = new List<File>();

                    if (in_.Count != 0)
                    {

                        in_file = JsonConvert.DeserializeObject<List<File>>(Request.Form["input_filename"]);
                        in_filename = string.Join(",", in_file.Select(x => x.filename));
                    }

                    if (out_.Count != 0)
                    {
                        out_file = JsonConvert.DeserializeObject<List<File>>(Request.Form["output_filename"]);
                        out_filename = string.Join(",", out_file.Select(x => x.filename));

                    }
                    Recorderror list = new Recorderror();
                    if (mode == "add")
                    {
                        list.errorid = Convert.ToInt64(errorid);
                        list.remarks = qaremarks;
                        list.projectid = projectid;
                        list.workflowid = Convert.ToInt64(prodefid);
                        list.productionagent = Convert.ToInt64(productionagent);
                        list.jobtitle = Convert.ToInt64(jobtitle);
                        list.qaagent = Convert.ToInt64(qaagent);
                        list.lottitle = Convert.ToInt64(lottile);
                        list.productiondate = productiondate;
                        list.qadate = qadate;
                        list.createdby = Convert.ToInt64(createdby);
                        list.biddate = biddate;
                        list.transid = Convert.ToInt64(transid);
                        list.bidentryid = Convert.ToInt64(bidentryid);

                        if (0 == HttpContext.Request.Form.Files.Count)
                        {
                            string input = JsonConvert.SerializeObject(list);
                            var _list = oWorkAreaService.AddRecorderror(input);
                        }
                    }
                    else if (mode == "edit")
                    {

                        if (Request.Form["bal_in_files"].Count != 0)
                        {
                            bal_in_files = JsonConvert.DeserializeObject<List<File>>(Request.Form["bal_in_files"]);
                        }
                        if (Request.Form["bal_out_files"].Count != 0)
                        {
                            bal_out_files = JsonConvert.DeserializeObject<List<File>>(Request.Form["bal_out_files"]);
                        }
                        list.errorid = Convert.ToInt64(errorid);
                        list.remarks = qaremarks;
                        list.projectid = projectid;
                        list.workflowid = Convert.ToInt64(prodefid);
                        list.productionagent = Convert.ToInt64(productionagent);
                        list.jobtitle = Convert.ToInt64(jobtitle);
                        list.qaagent = Convert.ToInt64(qaagent);
                        list.lottitle = Convert.ToInt64(lottile);
                        list.productiondate = productiondate;
                        list.qadate = qadate;
                        list.biddate = biddate;
                        list.transid = Convert.ToInt64(transid);
                        list.recorderrorid = Convert.ToInt64(recorderrorid);
                        list.updatedby = Convert.ToInt16(updatedby);
                        list.filename = Request.Form["saved_filename"];


                        if (0 == HttpContext.Request.Form.Files.Count)
                        {
                            list.in_files = JsonConvert.SerializeObject(bal_in_files);
                            list.out_files = JsonConvert.SerializeObject(bal_out_files);
                            string input = JsonConvert.SerializeObject(list);
                            var _list = oWorkAreaService.UpdateRecorderror(input);
                        }
                    }
                    else if (mode == "delete")
                    {

                        if (Request.Form["saved_filename"] != "file_delete")
                        {
                            list.recorderrorid = Convert.ToInt64(recorderrorid);
                            string input = JsonConvert.SerializeObject(list);
                            var _list = oWorkAreaService.DeleteRecorderror(input);
                        }
                        else
                        {
                            bal_out_files = JsonConvert.DeserializeObject<List<File>>(Request.Form["bal_out_files"]);
                            bal_in_files = JsonConvert.DeserializeObject<List<File>>(Request.Form["bal_in_files"]);

                            if (Request.Form["input_filename"].Count != 0)
                            {
                                var index = bal_in_files.FindIndex(x => x.filename == in_file[0].filename);
                                bal_in_files.RemoveAt(index);

                            }

                            if (Request.Form["output_filename"].Count != 0)
                            {
                                var index = bal_out_files.FindIndex(x => x.filename == out_file[0].filename);
                                bal_out_files.RemoveAt(index);

                            }
                            list.in_files = JsonConvert.SerializeObject(bal_in_files);
                            list.out_files = JsonConvert.SerializeObject(bal_out_files);
                            list.recorderrorid = Convert.ToInt64(recorderrorid);
                            list.updatedby = Convert.ToInt16(updatedby);
                            list.errorid = Convert.ToInt64(errorid);
                            string input = JsonConvert.SerializeObject(list);
                            var _list = oWorkAreaService.Filedelete_Recorderror(input);


                            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);
                                    // getting path
                                    //var ds = oCommonRepository.ExecuteSP_ReturnListForLot("spusrserverpathinfo", inputstr, "serverinfo_projid");
                                    //string serverpath = FormatPath(ds.serverpath);
                                    //check jobid folder
                                    //serverpath = Path.Combine(serverpath, "Record_error", jobtitle, lottile, errorid);

                                    string serverpath = string.Empty;

                                    if (in_file.Count != 0)
                                    {
                                        serverpath = FormatPath(in_file[0].path);
                                    }
                                    else if (out_file.Count != 0)
                                    {
                                        serverpath = FormatPath(out_file[0].path);
                                    }
                                    try
                                    {
                                        serverpath = Path.Combine(serverpath);
                                        System.IO.File.Delete(serverpath);

                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message.ToString());
                                        throw;
                                    }


                                });
                            }
                        }
                    }
                    for (int file = 0; file < HttpContext.Request.Form.Files.Count; file++)
                    {
                        var FileDataContent = HttpContext.Request.Form.Files[file];
                        if (FileDataContent != null && FileDataContent.Length > 0)
                        {
                            string fileName = string.Empty;
                            string type = string.Empty;
                            var stream = FileDataContent;
                            string[] col = Path.GetFileName(FileDataContent.FileName).Split('~');
                            fileName = col[0];
                            string sFilePath = string.Empty;

                            //insert record error file name

                            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission(prodefid))
                            {
                                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);
                                    // getting path Record_error

                                    var ds = oCommonRepository.ExecuteSP_ReturnListForLot("spusrserverpathinfo", inputstr, "serverinfo_projid");
                                    string serverpath = FormatPath(ds.serverpath);

                                    //check jobid folder
                                    serverpath = Path.Combine(serverpath, "Record_error", jobid.ToString());

                                    if (!Directory.Exists(serverpath))
                                        Directory.CreateDirectory(serverpath);
                                    //check lotid folder
                                    serverpath = Path.Combine(serverpath, lottile);

                                    if (!Directory.Exists(serverpath))
                                        Directory.CreateDirectory(serverpath);

                                    serverpath = Path.Combine(serverpath, errorid);

                                    if (!Directory.Exists(serverpath))
                                        Directory.CreateDirectory(serverpath);

                                    if (in_file.Exists(x => x.filename == fileName && x.status != "uploaded"))
                                    {
                                        serverpath = Path.Combine(serverpath, "IN");

                                        if (!Directory.Exists(serverpath))
                                            Directory.CreateDirectory(serverpath);

                                        sFilePath = Path.Combine(serverpath, fileName);

                                        var index = in_file.FindIndex(x => x.filename == fileName);
                                        in_file[index].path = sFilePath;
                                        in_file[index].type = "IN";
                                        in_file[index].status = "uploaded";

                                    }
                                    else if (out_file.Exists(x => x.filename == fileName && x.status != "uploaded"))
                                    {
                                        serverpath = Path.Combine(serverpath, "OUT");

                                        if (!Directory.Exists(serverpath))
                                            Directory.CreateDirectory(serverpath);

                                        sFilePath = Path.Combine(serverpath, fileName);

                                        var index = out_file.FindIndex(x => x.filename == fileName);
                                        out_file[index].path = sFilePath;
                                        out_file[index].type = "OUT";
                                        out_file[index].status = "uploaded";
                                    }
                                    if (!Directory.Exists(serverpath))
                                        Directory.CreateDirectory(serverpath);

                                    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;
                                    }


                                });

                            }
                        }
                    }
                    if (mode == "add" && HttpContext.Request.Form.Files.Count != 0)
                    {
                        if (in_file.Count != 0)
                            list.in_files = JsonConvert.SerializeObject(in_file);

                        if (out_file.Count != 0)
                            list.out_files = JsonConvert.SerializeObject(out_file);

                        string input = JsonConvert.SerializeObject(list);
                        var _list = oWorkAreaService.AddRecorderror(input);

                    }
                    else if (mode == "edit" && HttpContext.Request.Form.Files.Count != 0)
                    {
                        if (in_file.Count != 0)
                        {
                            if (bal_in_files.Count != 0)
                            {
                                foreach (var item in bal_in_files)
                                {
                                    in_file.Add(item);
                                }
                            }
                        }

                        if (out_file.Count != 0)
                        {
                            if (bal_out_files.Count != 0)
                            {
                                foreach (var item in bal_out_files)
                                {
                                    out_file.Add(item);
                                }
                            }
                        }
                        list.in_files = JsonConvert.SerializeObject(in_file.Count == 0 ? bal_in_files : in_file);
                        list.out_files = JsonConvert.SerializeObject(out_file.Count == 0 ? bal_out_files : out_file);

                        string input = JsonConvert.SerializeObject(list);
                        var _list = oWorkAreaService.UpdateRecorderror(input);
                    }

                }
                else if (mode == "select")
                {

                    var list = new { lotid = Convert.ToInt64(lotid), tranid = Convert.ToInt64(tranid), jobid = Convert.ToInt64(jobid) };
                    var input = JsonConvert.SerializeObject(list);
                    var _list = oWorkAreaService.Recorderrorlst(input);
                    return Ok(_list);
                }

                return Ok(new
                {
                    msg = "success"
                });

            }
            catch (Exception ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }
        [AllowAnonymous]
        [HttpPost("Bidnobyname")]
        public IActionResult Bidnobyname(bidnumberModel data)
        {
            try
            {
                var res = oWorkAreaService.Bidnobyname(data);


                return Ok(res);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }

        [AllowAnonymous]
        [HttpGet("Getbidlist")]
        public IActionResult Getbidlist()
        {
            try
            {
                var list = new { search = "" };
                var input = JsonConvert.SerializeObject(list);
                var result = oWorkAreaService.GetallbidList(input);

                return Ok(result);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }
        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);
        }
        [Authorize]
        [HttpPost("workareaCheckin")]
        public object workareaCheckin(workareastatusmodel list)
        {
            try
            {
                List<string> res = new List<string>();
                List<string> val = new List<string>();
                res = (List<string>)oWorkAreaService.check_workareaexist(list);
                foreach (string s in res)
                {
                    if (s == null)
                    {
                        val = (List<string>)oWorkAreaService.Insert_workarea(list);

                    }
                    else
                    {
                        val = (List<string>)oWorkAreaService.update_workarea(list);

                    }
                }

                return Ok(val);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        public class alllotdetails
        {
            public long jobid { get; set; }
            public long lotid { get; set; }
            public long jobworkflowid { get; set; }
            public long transactionid { get; set; }
            public int pickedby { get; set; }
            public int sequence { get; set; }
            public string title { get; set; }
            public string lotkey { get; set; }
            public string batchid { get; set; }
            public string endtime { get; set; }
            public string job_url { get; set; }
            public string lotstatus { get; set; }
            public string projectid { get; set; }
            public string starttime { get; set; }
            public string transactionkey { get; set; }
            public string bitnumber { get; set; }
            public string lotmastermetafields { get; set; }

        }
        public class File
        {
            public string filename { get; set; }
            public string path { get; set; }
            public string type { get; set; }
            public string mode { get; set; }
            public string status { get; set; }
        }
        public class Get_lot_details
        {
            public long jobid { get; set; }
            public long prodefid { get; set; }
            public long userid { get; set; }
            public long jobworkflowid { get; set; }
            public string mode { get; set; }
        }
    }
}