using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using WK_KLI_LAPS_Service.App_Data;
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
{
    public interface IWorkAreaService
    {
       
        object checkLotTransactionStatus(string transactionId);
        object checkLotStatus(string transactionId);
        object insertLotComments(string comment, string filename, string transid, string doption, string tostage, string jobid, string lotid,string Status,string querytype);
        object metaFieldsUpdate(string transid, string fields);
        object updateLotStatus(string transid, string lotstatus);
        //object getCheckout(string tranid, string userid, string status, string jobworkflowid, string comments, string mode);
        object getCheckout(string tranid, string userid, string status, string jobworkflowid, string comments, string mode, string lotid = "0");
        string getFileSaveLcation(int id);
        appdetails CheckAppType(string tranid, string userid);
        List<StageData> getNextStageDetails(string jobid);
        object getBatchStatus(string batchid);

        object Checkout_transaction(lottraninfo lotinfo);
        void sendmail(lottraninfo lotinfo, string nexttranval, string jobworkflowid);
        object usrLotTransactionUpdate(string tranid, string userid, string status, string jobworkflowid, string comments, string mode);
        object getchecklistdetails(int tranid);
        int insertCheckListTransaction(Checklistdetail ochecklistdetail);
        int getPreviousStageTranid(int tranid);
        object updatenochange(string transactionId);
        object updateStatusandProductionId(List<lotmasterModel> data);
        object CMApprovalUpdate(string data);
        object GetRecorderrorDetails(string data);
        object Recorderrorlst(string data);

        object UpdateRecorderror(string data);
        object AddRecorderror(string data);
        object DeleteRecorderror(string data);
        object checkRecorderror(string data);
        object Bidnobyname(bidnumberModel data);
        object GetallbidList(string data);
        object InsertForIReflect(string data);
       object InsertForIReflect_QA_Multiple(string data);
       object InsertFor_Multiple_lot(string data, string mode);
        object check_workareaexist(workareastatusmodel data);
        object Insert_workarea(workareastatusmodel data);
        object update_workarea(workareastatusmodel data);
    }
    public class WorkAreaService : IWorkAreaService
    {
        //private readonly IRequestClient<ISimpleRequest, ISimpleResponse> _requestClient;

        //public WorkAreaService(IRequestClient<ISimpleRequest, ISimpleResponse> requestClient)
        //{
        //    _requestClient = requestClient;
        //}
        WorkAreaRepository oWorkAreaRepository = new WorkAreaRepository();
        CommonRepository oCommonRepository = new CommonRepository();
        public object checkLotTransactionStatus(string transactionId)
        {
            Fields oFieldsmodal = new Fields();
            oFieldsmodal.transid = Convert.ToUInt32(transactionId);
            oFieldsmodal.p_option = "gettransactionstatus";
            var input = JsonConvert.SerializeObject(oFieldsmodal);
            return oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
        }
   
        public object checkLotStatus(string transactionId)
        {
            Fields oFieldsmodal = new Fields();
            oFieldsmodal.transid = Convert.ToUInt32(transactionId);
            oFieldsmodal.p_option = "getlotstatus";
            var input = JsonConvert.SerializeObject(oFieldsmodal);
            return oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

        }
        public object InsertForIReflect(string data)
        {
            return oCommonRepository.ExecuteSP_ReturnList("spinsertireflectdata", data, "insert");
        } 
        public object InsertForIReflect_QA_Multiple(string data)
        {
            return oCommonRepository.ExecuteSP_ReturnList("spireflect_QAerror_multiple", data, "insert");
        }
        public object InsertFor_Multiple_lot(string data,string mode)
        {
            return oCommonRepository.ExecuteSP_ReturnList("splotupdatereviseddate_multiple", data, mode);
        }

        public object insertLotComments(string comment, string filename, string transid, string doption, string tostage, string jobid, string lotid, string Status, string querytype)
        {
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.transid = Convert.ToUInt32(transid);
            oInsertComments.comments = comment;
            oInsertComments.filename = filename;
            oInsertComments.doption = doption;
            oInsertComments.jobid = Convert.ToUInt32(jobid);
            oInsertComments.lotid = Convert.ToUInt32(lotid);
            oInsertComments.Status = Status;
            oInsertComments.querytype = querytype;
            oInsertComments.p_option = "insertlotcomments";
            var input = JsonConvert.SerializeObject(oInsertComments);
            return oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
        }
        public object insertLotComments(string comment, string filename, string transid, string doption, string tostage, string jobid, string lotid)
        {
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.transid = Convert.ToUInt32(transid);
            oInsertComments.comments = comment;
            oInsertComments.filename = filename;
            oInsertComments.doption = doption;
            oInsertComments.jobid = Convert.ToUInt32(jobid);
            oInsertComments.lotid = Convert.ToUInt32(lotid);
            oInsertComments.tojobworkflowid = tostage;
            oInsertComments.p_option = "insertlotcomments";
            var input = JsonConvert.SerializeObject(oInsertComments);
            return oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

        }
        public object metaFieldsUpdate(string transid, string fields)
        {
            Fields oFieldsmodal = new Fields();
            oFieldsmodal.transid = Convert.ToUInt32(transid);
            oFieldsmodal.fields = fields;
            oFieldsmodal.option = "metafieldsupdate";
            var input = JsonConvert.SerializeObject(oFieldsmodal);
            return oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
        }
        public object Dashboard_RecordError(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("sprecorderrorselect", input, "dashboard_report");
        }
        #region
        //public object CC_Checkout_transaction(lottraninfo lotinfo, string cflag, long jobid)
        //{
        //    var trans_id = lotinfo.p_tranid;
        //    if (string.IsNullOrEmpty(cflag))
        //        cflag = string.Empty;
        //    var cur_status = "";
        //    if (!string.IsNullOrEmpty(cflag))
        //    {
        //        if (cflag == "G")
        //        {
        //            cur_status = cflag;
        //        }
        //        else
        //        {
        //            cur_status = "C";
        //        }
        //    }
        //    else
        //    {
        //        cflag = "C";
        //        cur_status = "C";
        //    }
        //    //var checkout = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "C", "checkout_only", "0", lotinfo.p_holdreason);
        //    //current stage complete
        //    var checkout = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, cur_status, (cflag.Equals("G") || cflag.Equals("B") ? "ignore" : "checkout_only"), lotinfo.jobworkflowid, lotinfo.p_holdreason);

        //    if (checkout != null)
        //    {
        //        var i_checkout = JsonConvert.DeserializeObject<object>(checkout.ToString());
        //        JArray a_checkout = JArray.Parse(i_checkout.ToString());
        //        var checknextasfinal = checknextisfinal(jobid);
        //        string last_stage_workflowid = string.Empty;
        //        if (checknextasfinal != null)
        //        {
        //            var i1 = JsonConvert.DeserializeObject<object>(checknextasfinal.ToString());
        //            JArray a1 = JArray.Parse(i1.ToString());
        //            JObject obj1 = JObject.Parse(a1[0].ToString());
        //            last_stage_workflowid = obj1["last_stage_workflowid"].ToString();
        //        }
        //        foreach (var item in a_checkout)
        //        {
        //            JobWorkflow_ obj = JsonConvert.DeserializeObject<JobWorkflow_>(item.ToString());
        //            List<StageData> lst = new List<StageData>();

        //            //******************* Get Next Stage Details **************
        //            lst = getNextStageDetails(obj.jobid);
        //            //*******************
        //            List<StageData> newList = lst.Where(m => m.CURRENT == obj.jobworkflowid).ToList();

        //            //**********Code to check the parallel decision is occur *******
        //            var data = new { tranid = trans_id };
        //            var jsonstr = JsonConvert.SerializeObject(data);
        //            var next_ordernores = CommonRepository.ExecuteSP_ReturnList2("spparalleldecisionmakingselect", jsonstr, "getbytranid");
        //            JArray dtparallelnextstage = new JArray();
        //            if (next_ordernores != null)
        //            {
        //                var next_ordernodata = JsonConvert.DeserializeObject<object>(next_ordernores.ToString());
        //                dtparallelnextstage = JArray.Parse(next_ordernodata.ToString());
        //            }
        //            List<string> listparallelnextstage = new List<string>();
        //            foreach (var dr in dtparallelnextstage)
        //            {
        //                listparallelnextstage.Add(dr[0].ToString());
        //            }
        //            List<StageData> newListparallel = newList.Where(p => listparallelnextstage.Any(p2 => p2 == p.PARALLEL || p2 == p.NEXT)).ToList();
        //            if (newListparallel.Count > 0)
        //                newList = newListparallel;
        //            //**************
        //            //******************* To Check Next Stage 
        //            foreach (var items in newList)
        //            {
        //                var next_workflow_id = "";
        //                //Correction Back
        //                if (cflag == "B")
        //                {
        //                    if (items.MOVEBACKYES != null)
        //                    {
        //                        next_workflow_id = items.MOVEBACKYES;
        //                        CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R");

        //                        var trandata = new { p_tranid = trans_id };
        //                        oCommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata, "updatedocrejected", "Üpdate lottrans");
        //                        var data1 = new { jobworkflowid = next_workflow_id, jobworkflowid2 = obj.jobworkflowid.ToString() };
        //                        var jsonstr1 = JsonConvert.SerializeObject(data1);
        //                        var next_ordernores1 = oCommonRepository.ExecuteSP_ReturnList("spjobworkflowdefinitionselect", jsonstr1, "getbyjobworkflowid1");
        //                        var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
        //                        JArray dt = JArray.Parse(next_ordernodata1.ToString());

        //                        if (dt.Count > 1)
        //                        {
        //                            var data2 = new { jobworkflowid = next_workflow_id, jobworkflowid2 = obj.jobworkflowid.ToString() };
        //                            var jsonstr2 = JsonConvert.SerializeObject(data2);
        //                            var next_ordernores2 = oCommonRepository.ExecuteSP_ReturnList("spjobworkflowdefinitionselect", jsonstr2, "getbyjobworkflowid1");
        //                            var next_ordernodata2 = JsonConvert.DeserializeObject<object>(next_ordernores2.ToString());
        //                            JArray dt_order = JArray.Parse(next_ordernodata2.ToString());

        //                            if (dt_order.Count > 1)
        //                            {
        //                                if (Convert.ToInt32(dt_order[0][0].ToString()) > Convert.ToInt32(dt_order[1][0].ToString()))
        //                                {
        //                                    //Backward
        //                                    var data3 = new { tranid = trans_id, fromorder = dt[1][0].ToString(), toorder = dt[0][0].ToString(), option = 'B' };
        //                                    var data31 = oCommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data3, null, "jobBackForward");
        //                                }
        //                                if (Convert.ToInt32(dt_order[0][0].ToString()) < Convert.ToInt32(dt_order[1][0].ToString()))
        //                                {
        //                                    //Forward
        //                                    var data4 = new { tranid = trans_id, fromorder = dt[0][0].ToString(), toorder = dt[1][0].ToString(), option = 'F' };
        //                                    var data31 = oCommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data4, null, "jobBackForward");

        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //                //Correction Next
        //                else if (cflag == "F")
        //                {
        //                    if (items.MOVEBACKNO != null)
        //                    {
        //                        next_workflow_id = items.MOVEBACKNO;
        //                        if (next_workflow_id == last_stage_workflowid)
        //                        {
        //                            //archieve
        //                            //cc_getarchievedetails
        //                            var call_archievedetails = call_archive(jobid, Convert.ToInt64(obj.lotid));
        //                            string result = string.Empty;
        //                            if (call_archievedetails != null)
        //                            {

        //                                var i1 = JsonConvert.DeserializeObject<object>(call_archievedetails.ToString());
        //                                JArray a1 = JArray.Parse(i1.ToString());
        //                                JObject obj1 = JObject.Parse(a1[0].ToString());
        //                                result = obj1["result"].ToString();
        //                            }
        //                            if (result != "Done")
        //                            {
        //                                return "error";
        //                            }


        //                        }
        //                        else
        //                        {
        //                            CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R");
        //                        }


        //                    }
        //                }
        //                else if (cflag == "G")
        //                {

        //                    if (items.MOVEBACKNO != null)
        //                    {
        //                        next_workflow_id = items.MOVEBACKNO;
        //                        CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "G");
        //                    }
        //                    else if (items.NEXT != null)
        //                    {
        //                        next_workflow_id = items.NEXT;
        //                        CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "G");
        //                    }
        //                }
        //                else
        //                {
        //                    if (items.NEXT != null)
        //                        next_workflow_id = items.NEXT;
        //                    else if (items.PARALLEL != null)
        //                        next_workflow_id = items.PARALLEL;

        //                    //*******************
        //                    if (next_workflow_id != null)
        //                    {
        //                        next_workflow_id = next_workflow_id.Trim();
        //                        List<StageData> checkParallalList = lst
        //                               .Where(m => m.NEXT == next_workflow_id || m.PARALLEL == next_workflow_id)
        //                               .ToList();

        //                        List<StageData> checkParallalList_Duplicate = new List<StageData>();
        //                        if (checkParallalList.Count > 0)
        //                        {
        //                            var if_check_parallel = true;
        //                            //***************** Only One Next Stage
        //                            if (checkParallalList.Count == 1)
        //                            {
        //                                CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R");
        //                            }
        //                            //***************** More than One Next Stage
        //                            else
        //                            {
        //                                ////***************** To check Move back is availabale
        //                                checkParallalList_Duplicate = checkParallalList;
        //                                try
        //                                {
        //                                    foreach (var item_checkParallalList in checkParallalList)
        //                                    {
        //                                        var data3 = new { jobworkflowid = item_checkParallalList.NEXT };
        //                                        var jsonstr3 = JsonConvert.SerializeObject(data3);
        //                                        var next_ordernores3 = CommonRepository.ExecuteSP_ReturnList2("spgetlotandstagedetails", jsonstr3, "getstageorder");
        //                                        var next_ordernodata3 = JsonConvert.DeserializeObject<object>(next_ordernores3.ToString());
        //                                        JArray next_orderno3 = JArray.Parse(next_ordernodata3.ToString());
        //                                        var data4 = new { jobworkflowid = item_checkParallalList.CURRENT };
        //                                        var jsonstr4 = JsonConvert.SerializeObject(data4);
        //                                        var current_ordernores4 = CommonRepository.ExecuteSP_ReturnList2("spgetlotandstagedetails", jsonstr4, "getstageorder");
        //                                        var current_ordernodata4 = JsonConvert.DeserializeObject<object>(current_ordernores4.ToString());
        //                                        JArray current_orderno4 = JArray.Parse(current_ordernodata4.ToString());

        //                                        if (Convert.ToInt32(next_orderno3[0]["stageorder"]) < Convert.ToInt32(current_orderno4[0]["stageorder"]))
        //                                        {
        //                                            checkParallalList_Duplicate.RemoveAll(x => x.CURRENT == item_checkParallalList.CURRENT);
        //                                        }
        //                                    }
        //                                }
        //                                catch (Exception ex)
        //                                {
        //                                    Console.WriteLine(ex.Message.ToString());
        //                                }
        //                                checkParallalList = checkParallalList_Duplicate;
        //                                ////***************** More than One Next Stage but moveback yes or no available . do not use parallel completion


        //                                if (checkParallalList.Count == 1)
        //                                {
        //                                    CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R");
        //                                }
        //                                else
        //                                {
        //                                    foreach (var item_checkParallalList in checkParallalList)
        //                                    {
        //                                        //***************** To Check All Parallal stage are completed or put Wait
        //                                        var checkout_check_parallel = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_parallel_check", item_checkParallalList.CURRENT.ToString(), "");
        //                                        if (checkout_check_parallel != null)
        //                                        {
        //                                            var i_checkout1 = JsonConvert.DeserializeObject<object>(checkout_check_parallel.ToString());
        //                                            JArray a_checkout1 = JArray.Parse(i_checkout1.ToString());
        //                                            foreach (var parallel_item in a_checkout1)
        //                                            {
        //                                                // JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.json);


        //                                                //var next_ordernodata11 = JsonConvert.DeserializeObject<object>(parallel_item.json);
        //                                                //JArray dtparallelnextstage11 = JArray.Parse(next_ordernodata11.ToString());

        //                                                JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.ToString());


        //                                                if (parallel_item_obj.lotstatus == "P" || parallel_item_obj.lotstatus == "R" || parallel_item_obj.lotstatus == "W" || parallel_item_obj.lotstatus == "" || parallel_item_obj.lotstatus == null)
        //                                                {
        //                                                    if_check_parallel = false;
        //                                                }
        //                                            }
        //                                        }
        //                                    }
        //                                    if (if_check_parallel == true)
        //                                    {
        //                                        CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R", false);
        //                                    }
        //                                    else
        //                                    {
        //                                        CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "W", false);
        //                                    }
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //                //*******************
        //            }
        //        }
        //    }
        //    return "Done";
        //}
        #endregion
        public object CC_Checkout_transaction(lottraninfo lotinfo, string cflag, long jobid)
        {
            var trans_id = lotinfo.p_tranid;
            if (string.IsNullOrEmpty(cflag))
                cflag = string.Empty;
            var cur_status = "";
            if (!string.IsNullOrEmpty(cflag))
            {
                if (cflag == "G")
                {
                    cur_status = cflag;
                }
                else
                {
                    cur_status = "C";
                }
            }
            else
            {
                cflag = "C";
                cur_status = "C";
            }
            //var checkout = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "C", "checkout_only", "0", lotinfo.p_holdreason);
            //current stage complete
            var checkout = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, cur_status, (cflag.Equals("G") || cflag.Equals("B") ? "ignore" : "checkout_only"), lotinfo.jobworkflowid, lotinfo.p_holdreason);

            if (checkout != null)
            {
                var i_checkout = JsonConvert.DeserializeObject<object>(checkout.ToString());
                JArray a_checkout = JArray.Parse(i_checkout.ToString());
                var checknextasfinal = checknextisfinal(jobid);
                string last_stage_workflowid = string.Empty;
                if (checknextasfinal != null)
                {
                    var i1 = JsonConvert.DeserializeObject<object>(checknextasfinal.ToString());
                    JArray a1 = JArray.Parse(i1.ToString());
                    JObject obj1 = JObject.Parse(a1[0].ToString());
                    last_stage_workflowid = obj1["last_stage_workflowid"].ToString();
                }
                foreach (var item in a_checkout)
                {
                    JobWorkflow_ obj = JsonConvert.DeserializeObject<JobWorkflow_>(item.ToString());
                    List<StageData> lst = new List<StageData>();

                    //******************* Get Next Stage Details **************
                    lst = getNextStageDetails(obj.jobid);
                    //*******************
                    List<StageData> newList = lst.Where(m => m.CURRENT == obj.jobworkflowid).ToList();

                    //**********Code to check the parallel decision is occur *******
                    var data = new { tranid = trans_id };
                    var jsonstr = JsonConvert.SerializeObject(data);
                    var next_ordernores = CommonRepository.ExecuteSP_ReturnList2("spparalleldecisionmakingselect", jsonstr, "getbytranid");
                    JArray dtparallelnextstage = new JArray();
                    if (next_ordernores != null)
                    {
                        var next_ordernodata = JsonConvert.DeserializeObject<object>(next_ordernores.ToString());
                        dtparallelnextstage = JArray.Parse(next_ordernodata.ToString());
                    }
                    List<string> listparallelnextstage = new List<string>();
                    foreach (var dr in dtparallelnextstage)
                    {
                        listparallelnextstage.Add(dr[0].ToString());
                    }
                    List<StageData> newListparallel = newList.Where(p => listparallelnextstage.Any(p2 => p2 == p.PARALLEL || p2 == p.NEXT)).ToList();
                    if (newListparallel.Count > 0)
                        newList = newListparallel;
                    //**************
                    //******************* To Check Next Stage 
                    foreach (var items in newList)
                    {
                        var next_workflow_id = "";
                        //Correction Back
                        if (cflag == "B")
                        {
                            if (items.MOVEBACKYES != null)
                            {
                                next_workflow_id = items.MOVEBACKYES;
                                //CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R");

                                var trandata = new { p_tranid = trans_id };
                                oCommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata, "updatedocrejected", "Üpdate lottrans");
                                var data1 = new { jobworkflowid = next_workflow_id, jobworkflowid2 = obj.jobworkflowid.ToString() };
                                var jsonstr1 = JsonConvert.SerializeObject(data1);
                                var next_ordernores1 = CommonRepository.ExecuteSP_ReturnList2("spjobworkflowdefinitionselect", jsonstr1, "getbyjobworkflowid1");

                                var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());

                                //var next_ordernodata1 = JsonConvert.SerializeObject(next_ordernores1);
                                JArray dt = JArray.Parse(next_ordernodata1.ToString());

                                if (dt.Count > 1)
                                {
                                    var data2 = new { jobworkflowid = next_workflow_id, jobworkflowid2 = obj.jobworkflowid.ToString() };
                                    var jsonstr2 = JsonConvert.SerializeObject(data2);
                                    // var next_ordernores2 = oCommonRepository.ExecuteSP_ReturnList("spjobworkflowdefinitionselect", jsonstr2, "getbyjobworkflowid1");
                                    var next_ordernores2 = CommonRepository.ExecuteSP_ReturnList2("spjobworkflowdefinitionselect", jsonstr2, "getbyjobworkflowid2");
                                    var next_ordernodata2 = JsonConvert.DeserializeObject<object>(next_ordernores2.ToString());
                                    JArray dt_order = JArray.Parse(next_ordernodata2.ToString());

                                    if (dt_order.Count > 1)
                                    {
                                        if (Convert.ToInt32(dt_order[0]["stageorder"].ToString()) > Convert.ToInt32(dt_order[1]["stageorder"].ToString()))
                                        {
                                            //Backward
                                            var data3 = new { tranid = trans_id, fromorder = dt_order[0]["stageorder"].ToString(), toorder = dt_order[1]["stageorder"].ToString(), option = 'B' };
                                            var data31 = oCommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data3, "jobBackForward", "Job backward");
                                        }
                                        if (Convert.ToInt32(dt_order[0]["stageorder"].ToString()) < Convert.ToInt32(dt_order[1]["stageorder"].ToString()))
                                        {
                                            //Forward
                                            //tas
                                            //var data4 = new { tranid = trans_id, fromorder = dt_order[1]["stageorder"].ToString(), toorder = dt_order[0]["stageorder"].ToString(), option = 'F' };
                                            var data4 = new { tranid = trans_id, fromorder = dt_order[0]["stageorder"].ToString(), toorder = dt_order[1]["stageorder"].ToString(), option = 'F' };
                                            var data31 = oCommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data4, "jobBackForward", "Job forward");

                                        }
                                    }
                                }
                            }
                        }
                        //Correction Next
                        else if (cflag == "F")
                        {
                            if (items.MOVEBACKNO != null)
                            {
                                next_workflow_id = items.MOVEBACKNO;
                                if (next_workflow_id == last_stage_workflowid)
                                {
                                    getCheckout(trans_id, lotinfo.p_userid, "R", "nextstageinsertandcheckout", next_workflow_id, lotinfo.p_holdreason);
                                    //archieve
                                    //cc_getarchievedetails
                                    var call_archievedetails = call_archive(jobid, Convert.ToInt64(obj.lotid));
                                    string result = string.Empty;
                                    if (call_archievedetails != null)
                                    {

                                        var i1 = JsonConvert.DeserializeObject<object>(call_archievedetails.ToString());
                                        JArray a1 = JArray.Parse(i1.ToString());
                                        JObject obj1 = JObject.Parse(a1[0].ToString());
                                        result = obj1["result"].ToString();
                                    }
                                    if (result != "Done")
                                    {
                                        return "error";
                                    }


                                }
                                else
                                {
                                    CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R");
                                }


                            }
                        }
                        else if (cflag == "G")
                        {

                            if (items.MOVEBACKNO != null)
                            {
                                next_workflow_id = items.MOVEBACKNO;
                                CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "G");
                            }
                            else if (items.NEXT != null)
                            {
                                next_workflow_id = items.NEXT;
                                CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "G");
                            }
                        }
                        else
                        {
                            if (items.NEXT != null)
                                next_workflow_id = items.NEXT;
                            else if (items.PARALLEL != null)
                                next_workflow_id = items.PARALLEL;

                            //*******************
                            if (next_workflow_id != null)
                            {
                                next_workflow_id = next_workflow_id.Trim();
                                List<StageData> checkParallalList = lst
                                       .Where(m => m.NEXT == next_workflow_id || m.PARALLEL == next_workflow_id)
                                       .ToList();
                                List<StageData> checkParallalList_Duplicate = new List<StageData>();
                                if (checkParallalList.Count > 0)
                                {
                                    var if_check_parallel = true;
                                    //***************** Only One Next Stage
                                    if (checkParallalList.Count == 1)
                                    {
                                        CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R");
                                    }
                                    //***************** More than One Next Stage
                                    else
                                    {
                                        ////***************** To check Move back is availabale
                                        checkParallalList_Duplicate = checkParallalList;
                                        try
                                        {
                                            foreach (var item_checkParallalList in checkParallalList)
                                            {
                                                var data3 = new { jobworkflowid = item_checkParallalList.NEXT };
                                                var jsonstr3 = JsonConvert.SerializeObject(data3);
                                                var next_ordernores3 = CommonRepository.ExecuteSP_ReturnList2("spgetlotandstagedetails", jsonstr3, "getstageorder");
                                                var next_ordernodata3 = JsonConvert.DeserializeObject<object>(next_ordernores3.ToString());
                                                JArray next_orderno3 = JArray.Parse(next_ordernodata3.ToString());
                                                var data4 = new { jobworkflowid = item_checkParallalList.CURRENT };
                                                var jsonstr4 = JsonConvert.SerializeObject(data4);
                                                var current_ordernores4 = CommonRepository.ExecuteSP_ReturnList2("spgetlotandstagedetails", jsonstr4, "getstageorder");
                                                var current_ordernodata4 = JsonConvert.DeserializeObject<object>(current_ordernores4.ToString());
                                                JArray current_orderno4 = JArray.Parse(current_ordernodata4.ToString());

                                                if (Convert.ToInt32(next_orderno3[0]["stageorder"]) < Convert.ToInt32(current_orderno4[0]["stageorder"]))
                                                {
                                                    checkParallalList_Duplicate.RemoveAll(x => x.CURRENT == item_checkParallalList.CURRENT);
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Console.WriteLine(ex.Message.ToString());
                                        }
                                        checkParallalList = checkParallalList_Duplicate;
                                        ////***************** More than One Next Stage but moveback yes or no available . do not use parallel completion


                                        if (checkParallalList.Count == 1)
                                        {
                                            CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R");
                                        }
                                        else
                                        {
                                            foreach (var item_checkParallalList in checkParallalList)
                                            {
                                                //***************** To Check All Parallal stage are completed or put Wait
                                                var checkout_check_parallel = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_parallel_check", item_checkParallalList.CURRENT.ToString(), "");
                                                if (checkout_check_parallel != null)
                                                {
                                                    var i_checkout1 = JsonConvert.DeserializeObject<object>(checkout_check_parallel.ToString());
                                                    JArray a_checkout1 = JArray.Parse(i_checkout1.ToString());
                                                    foreach (var parallel_item in a_checkout1)
                                                    {
                                                        // JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.json);


                                                        //var next_ordernodata11 = JsonConvert.DeserializeObject<object>(parallel_item.json);
                                                        //JArray dtparallelnextstage11 = JArray.Parse(next_ordernodata11.ToString());

                                                        JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.ToString());


                                                        if (parallel_item_obj.lotstatus == "P" || parallel_item_obj.lotstatus == "R" || parallel_item_obj.lotstatus == "W" || parallel_item_obj.lotstatus == "" || parallel_item_obj.lotstatus == null)
                                                        {
                                                            if_check_parallel = false;
                                                        }
                                                    }
                                                }
                                            }
                                            if (if_check_parallel == true)
                                            {
                                                CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "R", false);
                                            }
                                            else
                                            {
                                                CC_Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, "", lotinfo, "W", false);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //*******************
                    }
                }
            }
            return "Done";
        }
        public object CC_Checkout_next(string trans_id, string p_userid, string jobworkflowid, string next_workflow_id, string p_holdreason, string filemove, lottraninfo lotinfo, string status, bool isTakeFileBackup = true)
        {
            List<jsonvalue> checkout_next = null;
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.transid = Convert.ToUInt32(trans_id);
            oInsertComments.p_option = "getcurrentstage";
            var input = JsonConvert.SerializeObject(oInsertComments);
            var CurrentStageres = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
            oInsertComments = new insertcomments();
            oInsertComments.jobworkflowid = Convert.ToUInt32(next_workflow_id);
            oInsertComments.p_option = "getnextstage";
            input = JsonConvert.SerializeObject(oInsertComments);
            var NextStageres = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
            if (CurrentStageres != null)
            {
                var data = JsonConvert.DeserializeObject<object>(CurrentStageres.ToString());
                JArray CurrentStage = JArray.Parse(data.ToString());
                data = JsonConvert.DeserializeObject<object>(NextStageres.ToString());
                JArray NextStage = JArray.Parse(data.ToString());
                var merged_lot_current = CurrentStage[0]["merged_lot"].ToString();
                var merged_lot_next = NextStage[0]["merged_lot"].ToString();
                //0 means lot wise stage, 1 means batch wise stage
                if (merged_lot_current == "0" && merged_lot_next == "0")
                {
                    getCheckout(trans_id, p_userid, status, "checkout_next", next_workflow_id, p_holdreason);
                    //Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, status, checkout_next, "checkout_next", isTakeFileBackup);
                }
                else if (merged_lot_current == "0" && merged_lot_next == "1")
                {
                    if (status == "G")
                    {
                        getCheckout(trans_id, p_userid, status, "checkout_next_merged", next_workflow_id, p_holdreason, CurrentStage[0]["lotid"].ToString());

                        oInsertComments = new insertcomments();
                        oInsertComments.lotid = Convert.ToUInt32(CurrentStage[0]["lotid"].ToString());
                        oInsertComments.p_option = "updatelotbatchdetails";
                        input = JsonConvert.SerializeObject(oInsertComments);
                        oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
                    }
                    else
                        getCheckout(trans_id, p_userid, "W", "checkout_next_merged", next_workflow_id, p_holdreason);

                    var data1 = new { jobid = CurrentStage[0]["jobid"].ToString(), stageorder = CurrentStage[0]["stageorder"].ToString() };
                    var jsonstr1 = JsonConvert.SerializeObject(data1);
                    var next_ordernores1 = CommonRepository.ExecuteSP_ReturnList2("spchecklotbatchcomplete", jsonstr1, "getbyjobid");
                    var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
                    JArray Check_All_lot_come = JArray.Parse(next_ordernodata1.ToString());

                    if (Check_All_lot_come.Count > 0)
                    {
                        var lot_cont = Check_All_lot_come[0]["batch_id"].ToString();
                        if (lot_cont == "1")
                        {
                            var json = new List<transout>();
                            foreach (var checkout_next_item in checkout_next)
                            {
                                JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                json.Add(JsonConvert.DeserializeObject<transout>(aa[0].ToString()));
                            }
                            oInsertComments = new insertcomments();
                            oInsertComments.transid = Convert.ToUInt32(json[0].p_tranid);
                            oInsertComments.lotstatus = "R";
                            oInsertComments.p_option = "updatelotstatus";
                            input = JsonConvert.SerializeObject(oInsertComments);
                            oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

                            oInsertComments = new insertcomments();
                            oInsertComments.jobid = Convert.ToUInt32(CurrentStage[0]["jobid"].ToString());
                            oInsertComments.p_option = "updatelotbatch";
                            input = JsonConvert.SerializeObject(oInsertComments);
                            oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
                            //Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, status, checkout_next, "checkout_next_merged", isTakeFileBackup);
                        }
                        else
                        {
                            var json = new List<transout>();
                            foreach (var checkout_next_item in checkout_next)
                            {
                                JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                json.Add(JsonConvert.DeserializeObject<transout>(aa[0].ToString()));
                            }
                            if (json[0].p_tranid != trans_id && status != "G")
                            {
                                //Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, "W", checkout_next, "checkout_next_merged", isTakeFileBackup);
                            }
                        }
                    }
                    //W--
                }
                else if (merged_lot_current == "1" && merged_lot_next == "1")
                {

                    getCheckout(trans_id, p_userid, status, "checkout_next", next_workflow_id, p_holdreason);
                    //Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, status, checkout_next, "checkout_next_merged_to_merged", isTakeFileBackup);
                }
                else if (merged_lot_current == "1" && merged_lot_next == "0")
                {
                    var data1 = new { batchid = CurrentStage[0]["batchid"].ToString() };
                    var jsonstr1 = JsonConvert.SerializeObject(data1);
                    var next_ordernores1 = CommonRepository.ExecuteSP_ReturnList2("splotbatchdetails", 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 - 1; item++)
                        {
                            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)
                            {
                                getCheckout(trans_id, p_userid, status, "checkout_next_unmerged", next_workflow_id, p_holdreason, BatchLotDetails[item]["lotid"].ToString());
                                //Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, status, checkout_next, "checkout_next_unmerged");
                            }

                        }
                    }
                }
            }
            return null;
        }
        public object checknextisfinal(long jobid)
        {
            var data = new { jobid = jobid };
            var jsonstr = JsonConvert.SerializeObject(data);

            return oCommonRepository.ExecuteSP_ReturnList1("cc_getnextisfinalstage", jsonstr);

        }
        public object call_archive(long jobid, long lotid)
        {
            var data = new { jobid = jobid, lotid = lotid, p_option="C" };
            var jsonstr = JsonConvert.SerializeObject(data);

            return oCommonRepository.ExecuteSP_ReturnList1("cc_getarchievedetails", jsonstr);

        }
        public object updateLotStatus(string transid, string lotstatus)
        {
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.transid = Convert.ToUInt32(transid);
            oInsertComments.lotstatus = lotstatus;
            oInsertComments.p_option = "updatelotstatus";
            var input = JsonConvert.SerializeObject(oInsertComments);
            return oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

        }
        public object getCheckout(string tranid, string userid, string status, string option, string jobworkflowid, string comments, string lotid = "0")
        {
            //insertcomments oInsertComments = new insertcomments();
            //oInsertComments.tranid = Convert.ToUInt32(tranid);
            //oInsertComments.userid = Convert.ToUInt32(userid);
            //oInsertComments.status = status;
            //oInsertComments.jobworkflowid = Convert.ToUInt32(jobworkflowid);
            //oInsertComments.comments = comments;
            var data = new { p_tranid = tranid, p_userid = userid, p_status = status, p_option = option, p_comments = comments, n_jobworkflowid = jobworkflowid, n_lotid = lotid };
            var jsonstr = JsonConvert.SerializeObject(data);
            return oCommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);
        }
        public string getFileSaveLcation(int id)
        {
            string fileSaveLocation = oCommonRepository.getfilesavelocation(id);
            return fileSaveLocation;
        }
        public appdetails CheckAppType(string tranid, string userid)
        {
            appdetails appdetails = new appdetails();
            //  appdetails obj = null;
            List<appdetails> appdetails1 = new List<appdetails>();
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.tranid = Convert.ToUInt32(tranid);
            oInsertComments.userid = Convert.ToUInt32(userid);
            oInsertComments.status = "R";
            oInsertComments.p_option = "apptype";
            var input = JsonConvert.SerializeObject(oInsertComments);
            var appType = oCommonRepository.ExecuteSP_ReturnList1("spusrlottransactionupdate", input);
            if (appType != null)
            {
                var i_appType = JsonConvert.DeserializeObject<object>(appType.ToString());
                JArray a_appType = JArray.Parse(i_appType.ToString());
                JObject obj_appType = JObject.Parse(a_appType[0].ToString());
                appdetails.jobworkflowid = obj_appType["jobworkflowid"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["jobworkflowid"].ToString());
                appdetails.lotid = obj_appType["lotid"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["lotid"].ToString());
                appdetails.jobid = obj_appType["jobid"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["jobid"].ToString());
                appdetails.merged_lot = obj_appType["merged_lot"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["merged_lot"].ToString());
                appdetails.batchid = obj_appType["batchid"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["batchid"].ToString());
                appdetails.nextstage = obj_appType["nextstage"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["nextstage"].ToString());
                appdetails.movebackstage = obj_appType["movebackstage"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["movebackstage"].ToString());
                appdetails.stagetype = obj_appType["stagetype"].ToString();
                appdetails.process_without_file = obj_appType["process_without_file"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["process_without_file"].ToString());
                appdetails.checkin_app = obj_appType["checkin_app"].ToString();
                appdetails.inprocessapp = obj_appType["inprocessapp"].ToString();
                appdetails.checkout_app = obj_appType["checkout_app"].ToString();
                appdetails.exe_path = obj_appType["exepath"].ToString();
                appdetails.checkin_appwather = obj_appType["checkin_appwather"].ToString();
                appdetails.inprocessappwatcher = obj_appType["inprocessappwatcher"].ToString();
                appdetails.checkout_appwatcher = obj_appType["checkout_appwatcher"].ToString();
                appdetails.ipaexepath = obj_appType["ipaexepath"].ToString();
                appdetails.coaexepath = obj_appType["coaexepath"].ToString();
                appdetails.ciaisservice = obj_appType["ciaisservice"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["ciaisservice"].ToString());
                appdetails.ipaisservice = obj_appType["ipaisservice"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["ipaisservice"].ToString());
                appdetails.coaisservice = obj_appType["coaisservice"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["coaisservice"].ToString());
            }
            return appdetails;
        }
        public object getJobDetails(object data)
        {
            //var input = JsonConvert.SerializeObject(data);         
            var input = JsonConvert.DeserializeObject<object>(data.ToString());
            var lotDetails = oCommonRepository.ExecuteSP_ReturnList("spgetlotandstagedetails", input.ToString(), "getlot");
            var stageDetails = oCommonRepository.ExecuteSP_ReturnList("spgetlotandstagedetails", input.ToString(), "getstage");
            var commentsDetails = oCommonRepository.ExecuteSP_ReturnList("spgetlotcommentslot", input.ToString(), "null");
            var json = new List<object>();
            json.Add(lotDetails);
            json.Add(stageDetails);
            json.Add(commentsDetails);
            return json;
        }
        public object getLotDetailsComments(object data)
        {
            //var input = JsonConvert.SerializeObject(data);
            var input = JsonConvert.DeserializeObject<object>(data.ToString());
            return oCommonRepository.ExecuteSP_ReturnList("spgetlotcommentslot", input.ToString(), "null");
        }
        public List<StageData> getNextStageDetails(string jobid)
        {
            List<StageData> lst = new List<StageData>();
            JobWorkflow_ oFieldsmodal = new JobWorkflow_();
            oFieldsmodal.jobid = jobid;
            oFieldsmodal.p_option = "getnextstagedetails";
            var input = JsonConvert.SerializeObject(oFieldsmodal);

            var nextStageDetails = oCommonRepository.ExecuteSP_ReturnList1("spusrlottransactionupdate", input);
            var i_stageDetails = JsonConvert.DeserializeObject<object>(nextStageDetails.ToString());
            JArray a_stageDetails = JArray.Parse(i_stageDetails.ToString());
            if (a_stageDetails.Count > 0)
            {
                for (int k = 0; k <= a_stageDetails.Count - 1; k++)
                {
                    var splite = a_stageDetails[k]["flowchart"].ToString().Split(',');
                    if (splite.Length > 0)
                    {
                        var current = "";
                        foreach (string word in splite)
                        {
                            var stemp = ""; StageData st = new StageData();
                            var innersplite = word.ToString().Split(':');
                            for (int j = 0; j <= innersplite.Length; j++)
                            {
                                if (innersplite[0] == "CURRENT")
                                    current = innersplite[1].Trim();
                            }
                            for (int j = 0; j <= innersplite.Length; j++)
                            {
                                st.CURRENT = current;
                                if (innersplite[0] == "CURRENT")
                                    stemp = "CURRENT";
                                else if (innersplite[0] == "NEXT")
                                    st.NEXT = innersplite[1].Trim();
                                else if (innersplite[0] == "PARALLEL")
                                    st.PARALLEL = innersplite[1].Trim();
                                else if (innersplite[0] == "MOVEBACKNO")
                                    st.MOVEBACKNO = innersplite[1].Trim();
                                else if (innersplite[0] == "MOVEBACKYES")
                                    st.MOVEBACKYES = innersplite[1].Trim();
                            }
                            if (stemp != "CURRENT")
                                lst.Add(st);
                        }
                    }
                }
            }
            return lst;
        }
        public object getBatchStatus(string batchid)
        {
            Fields oFieldsmodal = new Fields();
            oFieldsmodal.batchid = Convert.ToInt32(batchid);
            oFieldsmodal.p_option = "getbatchstatus";
            var input = JsonConvert.SerializeObject(oFieldsmodal);
            return oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
        }

        public object Checkout_transaction(lottraninfo lotinfo)
        {
            var trans_id = lotinfo.p_tranid;

            var checkout = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "C", "checkout_only", "0", lotinfo.p_holdreason);
            if (checkout != null)
            {
                var i_checkout = JsonConvert.DeserializeObject<object>(checkout.ToString());
                JArray a_checkout = JArray.Parse(i_checkout.ToString());
                foreach (var item in a_checkout)
                {
                    JobWorkflow_ obj = JsonConvert.DeserializeObject<JobWorkflow_>(item.ToString());
                    List<StageData> lst = new List<StageData>();

                    //******************* Get Next Stage Details **************
                    lst = getNextStageDetails(obj.jobid);
                    //*******************
                    List<StageData> newList = lst.Where(m => m.CURRENT == obj.jobworkflowid).ToList();


                    //******************* To Check Next Stage 
                    foreach (var items in newList)
                    {
                        var next_workflow_id = "";
                        if (items.NEXT != null)
                            next_workflow_id = items.NEXT;
                        else if (items.PARALLEL != null)
                            next_workflow_id = items.PARALLEL;
                        if (next_workflow_id != null)
                        {
                            next_workflow_id = next_workflow_id.Trim();
                            List<StageData> checkParallalList = lst
                                   .Where(m => m.NEXT == next_workflow_id || m.PARALLEL == next_workflow_id).ToList();
                            if (checkParallalList.Count > 0)
                            {
                                var if_check_parallel = true;
                                //***************** Only One Next Stage
                                if (checkParallalList.Count == 1)
                                {
                                    var checkout_next = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "R", "checkout_next", next_workflow_id, lotinfo.p_holdreason);
                                    var i_checkout_next = JsonConvert.DeserializeObject<object>(checkout_next.ToString());
                                    JArray a_checkout_next = JArray.Parse(i_checkout_next.ToString());
                                    var json = new List<transout>();
                                    foreach (var checkout_next_item in a_checkout_next)
                                        json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.ToString()));
                                    //  sendmail(lotinfo, json[0].p_tranid, obj.jobworkflowid);
                                }
                                //***************** More than One Next Stage
                                else
                                {
                                    foreach (var item_checkParallalList in checkParallalList)
                                    {
                                        //***************** To Check All Parallal stage are completed or put Wait
                                        var checkout_check_parallel = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "C", "checkout_parallel_check", item_checkParallalList.CURRENT, lotinfo.p_holdreason);
                                        var i_checkout_parallel = JsonConvert.DeserializeObject<object>(checkout_check_parallel.ToString());
                                        JArray a_checkout_parallel = JArray.Parse(i_checkout_parallel.ToString());
                                        if (a_checkout_parallel.Count > 0)
                                        {
                                            foreach (var parallel_item in a_checkout_parallel)
                                            {
                                                JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.ToString());
                                                if (parallel_item_obj.lotstatus == "P" || parallel_item_obj.lotstatus == "R" || parallel_item_obj.lotstatus == "W" || parallel_item_obj.lotstatus == "" || parallel_item_obj.lotstatus == null)
                                                {
                                                    if_check_parallel = false;
                                                }
                                            }
                                        }
                                    }
                                    if (if_check_parallel == true)
                                    {
                                        var checkout_next = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "R", "checkout_next", next_workflow_id, lotinfo.p_holdreason);
                                        var i_checkout_next = JsonConvert.DeserializeObject<object>(checkout_next.ToString());
                                        JArray a_checkout_next = JArray.Parse(i_checkout_next.ToString());
                                        var json = new List<transout>();
                                        foreach (var checkout_next_item in a_checkout_next)
                                            json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.ToString()));
                                        //     sendmail(lotinfo, json[0].p_tranid, obj.jobworkflowid.ToString());
                                    }
                                    else
                                    { var checkout_next = getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "W", "checkout_next", next_workflow_id, lotinfo.p_holdreason); }
                                }
                            }
                        }

                    }

                }

            }

            return "Done";
        }
        public void sendmail(lottraninfo lotinfo, string nexttranval, string jobworkflowid)
        {
            // Convert.ToInt64((HttpContext.Current.Session["UserID"] as string));
            long userId_t = Convert.ToInt64("4");
            //RabbitMq sendmsg = new RabbitMq();
            //sendmsg.SendMqMail(lotinfo.p_tranid.ToString(), jobworkflowid.ToString(), "2", nexttranval.ToString(), userId_t.ToString());
            //var JobMetaFields = GetJobMetaData(nexttranval.ToString(), lotinfo.p_tranid.ToString(), jobworkflowid);
            //Postmail_SignOff(nexttranval, jobworkflowid, "", lotinfo.p_tranid.ToString(), JobMetaFields);
            //TriggerMail(lotinfo.p_tranid.ToString(), "2", nexttranval);
            //System.Threading.Thread.Sleep(100);
            //TriggerMail(lotinfo.p_tranid.ToString(), "1", (HttpContext.Current.Session["UserID"] as string));
        }
        public object usrLotTransactionUpdate(string tranid, string userid, string status, string jobworkflowid, string comments, string mode)
        {
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.tranid = Convert.ToUInt32(tranid);
            oInsertComments.userid = Convert.ToUInt32(userid);
            oInsertComments.status = status;
            oInsertComments.jobworkflowid = Convert.ToUInt32(jobworkflowid);
            oInsertComments.comments = comments;
            oInsertComments.p_option = mode;
            var input = JsonConvert.SerializeObject(oInsertComments);
            return oCommonRepository.ExecuteSP_ReturnList1("spusrlottransactionupdate", input);
        }
        public object usrLotTransactionInsert(Int32? userid, Int64? lotid, Int64 jobworkflowid, string transkey, string mode)
        {
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.userid = Convert.ToUInt32(userid);
            oInsertComments.lotid = Convert.ToUInt32(lotid);
            oInsertComments.transactionkey = transkey;
            oInsertComments.jobworkflowid = Convert.ToUInt32(jobworkflowid);
            oInsertComments.p_option = mode;
            var input = JsonConvert.SerializeObject(oInsertComments);
            return oCommonRepository.ExecuteSP_ReturnList1("spusrlottransactionupdate", input);
        }
        public object getchecklistdetails(int tranid)
        {
            return oWorkAreaRepository.GetChecklistdetail(tranid);
        }

        public int insertCheckListTransaction(Checklistdetail ochecklistdetail)
        {
            var input = ochecklistdetail;
            return oCommonRepository.ExecuteSP_ReturnInt("spchecklisttransaction", input, "insert", "insertCheckListTransaction");
        }
        public int getPreviousStageTranid(int tranid)
        {
            return oWorkAreaRepository.GetPreviousStageTranid(tranid);
        }
        public object updatenochange(string transactionId)
        {
            Fields oFieldsmodal = new Fields();
            oFieldsmodal.transid = Convert.ToUInt32(transactionId);
            oFieldsmodal.p_option = "updatenochange";
            var input = JsonConvert.SerializeObject(oFieldsmodal);
            return oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
        }
        public object updateStatusandProductionId(List<lotmasterModel> data)
        {
            string input = JsonConvert.SerializeObject(data);
            return oCommonRepository.ExecuteSP_ReturnList("splotbatchdetails", input, "updateStatusandProductionId");
        }
        public object CMApprovalUpdate(string input)
        {
            //string input = JsonConvert.SerializeObject(data);
            return oCommonRepository.ExecuteSP_ReturnList("spjobbackforwardfromworkarea", input, "jobForward1");
        }
        private class jsonvalue
        {
            public string json { set; get; }

        }
        public object GetRecorderrorDetails(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("sprecorderrorselect", input, "get");
        }
        public object AddRecorderror(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("sprecorderror", input, "insert");
        }
        public object checkRecorderror(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("sprecorderrorselect", input, "checkexistence");
        }
        public object UpdateRecorderror(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("sprecorderror", input, "update");
        }
        public object DeleteRecorderror(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("sprecorderror", input, "delete");
        }
        public object Filedelete_Recorderror(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("sprecorderror", input, "file_delete");
        }
        public object Recorderrorlst(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("sprecorderrorselect", input, "select");
        }
        public object Bidnobyname(bidnumberModel data)
        {
            string input = JsonConvert.SerializeObject(data);
            return oCommonRepository.ExecuteSP_ReturnList("spbidnumbermasterselect", input, "search");
        }
        public object GetallbidList(string input)
        {
            return oCommonRepository.ExecuteSP_ReturnList("spbidnumbermasterselect", input, "getall");
        }
        public object check_workareaexist(workareastatusmodel data)
        {
            var input = JsonConvert.SerializeObject(data);
            return oCommonRepository.ExecuteSP_ReturnList("spworkareastatusselect", input, "check_exist");

        }

        public object Insert_workarea(workareastatusmodel data)
        {
            var input = JsonConvert.SerializeObject(data);
            return oCommonRepository.ExecuteSP_ReturnList("spworkareastatus", input, "insert");

        }
        public object update_workarea(workareastatusmodel data)
        {
            var input = JsonConvert.SerializeObject(data);
            return oCommonRepository.ExecuteSP_ReturnList("spworkareastatus", input, "update");

        }
    }
  
}
