using HRM.BO;
using HRM.DA;
using Ease.Core.DataAccess;
using Ease.Core.Model;
using Ease.Core.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using NPOI.SS.Formula.Functions;
using System.Text;
using Microsoft.Data.SqlClient;
using System.Linq;
using Azure;
using System.Runtime.ConstrainedExecution;
using static iTextSharp.text.pdf.AcroFields;
using System.Net;
using System.Security.Policy;
using static Org.BouncyCastle.Math.EC.ECCurve;
using System.Transactions;

namespace HRM.DA
{
    public class DataIntergrationRequestService : ServiceTemplate, IDataIntergrationRequestService
    {
        public DataIntergrationRequestService()
        {
        }
        List<DataIntegration> _oHRDataUploads = null;
        List<SuccessorErrorList> _oSuccessOrErrorList = new List<SuccessorErrorList>();
        List<Employee> _oEmployeeCollection = null;
        List<Department> _oDepartments = null;
        List<Designation> _oDesignations = null;
        List<Location> _oLocations = new List<Location>();
        List<Employee> _oEmployees = new List<Employee>();
        List<Bank> _oBanks = new List<Bank>();
        List<Branch> _oBranchs = new List<Branch>();
        List<Religion> _oReligions = new List<Religion>();
        List<Category> _oCategories = new List<Category>();
        List<Grade> _oGrades = new List<Grade>();
        private List<Employee> _allEmployee = new List<Employee>();

        //process data variable
        private int _emloyeeId = 0;
        private int _departmentid = 0;
        private int _locationid = 0;
        private int _categoryID = 0;
        private int _religionID = 0;
        private int _designationid = 0;
        private int _gradeid = 0;
        private int _branchid = 0;
        private int _costCenterId = 0;
        private int _bankid = 0;
        private int _accessCardID = 0;
        private int _payrollTypeID = 0;
        private List<Category> _categorys = new List<Category>();
        private List<Grade> _grades = new List<Grade>();
        private List<Department> _departments = new List<Department>();
        private List<Location> _locations = new List<Location>();
        private List<Religion> _religions = new List<Religion>();
        private List<Designation> _designations = new List<Designation>();
        private List<Bank> _banks = new List<Bank>();
        private List<Branch> _branches = new List<Branch>();
        private List<Costcenter> _costCenters = new List<Costcenter>();
        private List<EmployeeStatus> _oEmployeeStatus = new List<EmployeeStatus>();
        private List<UploadErrorOrSuccess> _errorOrSuccessList;
        private List<Employee> _employees = new List<Employee>();
        private List<AccessCard> _accessCards = new List<AccessCard>();


        DepartmentService dserv = new DepartmentService();
        MiscellaneousService miserv = new MiscellaneousService();
        CategoryService cserv = new CategoryService();
        GradeService gserv = new GradeService();
        ReligionService rserv = new ReligionService();
        LocationService locserv = new LocationService();
        DesignationService degserv = new DesignationService();
        BankService bankserv = new BankService();
        BranchService branchserve = new BranchService();
        SearchEmployeeService seserv = new SearchEmployeeService();
        public int _userID;


        protected override T CreateObject<T>(DataReader oReader)
        {
            return null;
        }

        #region Service implementation

        public List<UploadErrorOrSuccess> getErrorList()
        {
            return _errorOrSuccessList;
        }

        public List<SuccessorErrorList> getErrorORSuccessList()
        {
            // return _oSuccessList;
            return _oSuccessOrErrorList;
        }

        public bool ProcessBasicData(List<DataIntegration> oHRDataUploads)
        {
            _allEmployee = new EmployeeService().GetAllEmps();
            _errorOrSuccessList = new List<UploadErrorOrSuccess>();
            RefreshObject();
            SystemConfigarationService ocManager = new SystemConfigarationService();
            List<SystemConfigaration> deptConfig = ocManager.GetAllChildrenByParentNode(EnumConfigurationType.Logic, "department");
            List<SystemConfigaration> locConfig = ocManager.GetAllChildrenByParentNode(EnumConfigurationType.Logic, "location");

            bool isCategoryCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "category", "codeautogenerate"));
            bool isGradeCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "codeautogenerate"));
            bool isDeptCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "department", "codeautogenerate"));
            bool islocCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "location", "codeautogenerate"));
            bool isreligionCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "religion", "codeautogenerate"));
            bool isdesignationCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "designation", "codeautogenerate"));
            bool isbankCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "bank", "codeautogenerate"));
            bool isbranchCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "branch", "codeautogenerate"));
            bool iscrgCodeAutoGenerte = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "costcenter", "codeautogenerate"));

            Employee oemployee = new Employee();
            int nRow = 0;
            int nIndex = 0;
            int count = 0;
            _emloyeeId = _emloyeeId + 1;
            foreach (DataIntegration row in oHRDataUploads)
            {
                
                count++;
                oemployee = new Employee();
                oemployee.EmployeeNo = row.EmployeeNo;
             
                var empExist = this._allEmployee.FirstOrDefault(x => x.EmployeeNo == oemployee.EmployeeNo);
                if (empExist != null)
                {
                    oemployee.ID = empExist.ID;
                }
                else
                {
                    _emloyeeId = _emloyeeId + 1;
                    oemployee.ID = _emloyeeId;
                  //  oemployee.SetObjectID(_emloyeeId);
                }

                // object[] obj = row.ItemArray;
                nRow = nRow + 1;

                #region Category upload
                Category oCategory = null;
                if (isCategoryCodeAutoGen == false)
                    oCategory = _categorys.Find(delegate (Category item) { return item.Code == row.Category.ToString(); });
                else
                    oCategory = _categorys.Find(delegate (Category item) { return item.Name == row.Category.ToString(); });

                if (oCategory == null)
                {
                    AddStatus(nRow, row.EmployeeNo, "New Category added:"+ row.Category.ToString()
                             , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    oCategory = new Category();
                    oCategory.Name = row.Category.ToString();
                    oCategory.Status = EnumStatus.Active;
                    if (isCategoryCodeAutoGen == false)
                        oCategory.Code = oCategory.Code.ToString();
                    _categoryID = _categoryID + 1;
                    oemployee.CategoryID = (_categoryID);
                    oCategory.SetObjectID(_categoryID);
                    oCategory.WagesType = EnumWagesType.Monthly;
                    oCategory.CreatedBy = _userID;
                    oCategory.PayrollTypeID = this._payrollTypeID;
                    _categorys.Add(oCategory);
                }
                else
                {
                    // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Grade", nRow, "Grade Code already exist in other payroll type."));
                    oemployee.CategoryID = oCategory.ID;
                    oCategory.ModifiedBy = this._userID;
                }


                #endregion Category upload

                /// <summary>                
                /// Process grade whether it is already in the system or new grade
                /// </summary>   
                /// 
                #region Grade upload
                Grade ograde = null;
                if (isGradeCodeAutoGen == false)
                    ograde = _grades.Find(delegate (Grade item) { return item.Code == row.GradeCode.ToString(); });
                else
                    ograde = _grades.Find(delegate (Grade item) { return item.Name == row.Grade.ToString(); });

                if (ograde == null)
                {
                    ograde = new Grade();
                    ograde.Status = EnumStatus.Active;
                    AddStatus(nRow, row.EmployeeNo, "New grade has been created:" + ograde.Name
                                  , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);

                    ograde.GradeSegmentID = (1);
                    ograde.HasPayscale = false; //new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "payscaleapplicable ");
                    ograde.HasGrossConcept = false; //new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "grossapplicable");
                    ograde.Name = row.Grade.ToString().Trim();
                    if (isGradeCodeAutoGen == false)
                        ograde.Code = row.GradeCode.ToString().Trim();
                    _gradeid = _gradeid + 1;
                    oemployee.GradeID = (_gradeid);
                    ograde.SetObjectID(_gradeid);
                    ograde.CreatedBy = this._userID;
                    ograde.PayrollTypeID = this._payrollTypeID;
                    _grades.Add(ograde);

                    if (gserv.Get(ograde.Code) != null)
                        AddStatus(nRow, row.EmployeeNo, "Grade Code already exist in other payroll type." + row.Grade.ToString(), EnumSAPProcessStatus.Error, EnumDataIntegrationType.EmployeeBasic);
                    //  _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Grade", nRow, "Grade Code already exist in other payroll type."));
                }
                else
                {
                    //AddStatus(nRow, row.EmployeeNo, "Grade has been changed, new grade:" + ograde.Name
                    //               , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    oemployee.GradeID = ograde.ID;
                    ograde.ModifiedBy = this._userID;
                }


                #endregion Grade upload

                /// <summary>                
                /// Process Department whether it is already in the system or new location
                /// </summary>   
                #region Department
                int nparentid = 0;
                nIndex = 0;
                var dtires = deptConfig.FindAll(x => x.Node == "text");

                foreach (SystemConfigaration oconfig in dtires)
                {
                    nIndex = nIndex + 1;
                    // if (row[oconfig.Value + " Name"].ToString() == "") continue;
                    string devCode = "";
                    string devName = "";

                    if (nIndex == 1)
                    {
                        devCode = row.DivisionCode;
                        devName = row.Division;
                    }
                    else if (nIndex == 2)
                    {
                        devCode = row.DepartmentCode;
                        devName = row.Department;
                    }
                    else if (nIndex == 3)
                    {
                        //devCode = row.SectionCode;
                        //devName = row.Section;
                        devCode = row.SubDepartmentCode;
                        devName = row.SubDepartment;
                    }
                    else if (nIndex == 4)
                    {
                        devCode = row.SectionCode;
                        devName = row.Section;
                    }

                    Department odepartment = null;
                    if (isDeptCodeAutoGen == false)
                    {
                        if (nIndex > 1)
                            odepartment = _departments.Find(delegate (Department item) { return item.Code == devCode.Trim() && item.Tier == nIndex && item.ParentID == nparentid; });
                        else
                            odepartment = _departments.Find(delegate (Department item) { return item.Code == devCode.Trim() && item.Tier == nIndex; });
                    }
                    else
                    {
                        if (nIndex > 1)
                            odepartment = _departments.Find(delegate (Department item) { return item.Name == devName.ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; });
                        else
                            odepartment = _departments.Find(delegate (Department item) { return item.Name == devName.ToString().Trim() && item.Tier == nIndex; });
                    }

                    if (odepartment == null)
                    {
                        odepartment = new Department();
                        AddStatus(nRow, row.EmployeeNo, "New "+ oconfig.Value + " has been created:" + devName
                                  , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        // odepartment.Name = row[oconfig.Value + " Name"].ToString().Trim();
                        odepartment.Name = devName.ToString().Trim();
                        odepartment.Tier = nIndex;
                        odepartment.Status = EnumStatus.Active;
                        odepartment.CreatedBy = this._userID;
                        odepartment.PayrollTypeID = this._payrollTypeID;

                        if (isDeptCodeAutoGen == false)
                        {
                            // odepartment.Code = row[oconfig.Value + " Code"].ToString().Trim();
                            odepartment.Code = devCode.ToString().Trim();
                            if (odepartment.Code == "")
                                AddStatus(nRow, row.EmployeeNo, "Code can't be empty." + oconfig.Value, EnumSAPProcessStatus.Error, EnumDataIntegrationType.EmployeeBasic);
                          //  _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(oconfig.Value + " Code", nRow, oconfig.Value + " Code can't be empty"));
                        }

                        if (nIndex > 1) odepartment.ParentID = (nparentid);
                        _departmentid = _departmentid + 1;
                        nparentid = _departmentid;

                        oemployee.DepartmentID = (_departmentid);
                        odepartment.SetObjectID(_departmentid);

                        _departments.Add(odepartment);
                    }
                    else
                    {
                        nparentid = odepartment.ID;
                        oemployee.DepartmentID = odepartment.ID;
                        odepartment.ModifiedBy = this._userID;
                    }
                }

                #endregion
                /// <summary>                
                /// Process location whether it is already in the system or new location
                /// </summary>               
                #region Location
                nparentid = 0;
                nIndex = 0;
                var ltires = locConfig.FindAll(x => x.Node == "text");
                foreach (SystemConfigaration oconfig in ltires)
                {
                    nIndex = nIndex + 1;
                    string locCode = "";
                    string locName = "";
                    if (nIndex == 1)
                    {
                        locCode = row.ZoneCode;
                        locName = row.Zone;
                    }
                    else if (nIndex == 2)
                    {
                        locCode = row.LocationCode;
                        locName = row.Location;
                    }

                    Location olocation = null;
                    if (islocCodeAutoGen == false)
                    {
                        if (nIndex > 1)
                        {
                            //olocation = _locations.Find(delegate (Location item) { return item.Code == row[oconfig.Value + " Code"].ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; });
                            olocation = _locations.Find(delegate (Location item) { return item.Code == locCode.Trim() && item.Tier == nIndex && item.ParentID == nparentid; });
                        }
                        else
                        {
                            olocation = _locations.Find(delegate (Location item) { return item.Code == locCode.Trim() && item.Tier == nIndex; });
                        }
                    }
                    else
                    {
                        if (nIndex > 1)
                        {
                            olocation = _locations.Find(delegate (Location item) { return item.Name == locName.ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; });
                        }
                        else
                        {
                            olocation = _locations.Find(delegate (Location item) { return item.Name == locName.ToString().Trim() && item.Tier == nIndex; });
                        }
                    }

                    if (olocation == null)
                    {
                        olocation = new Location();
                        //olocation.Name = row[oconfig.Value + " Name"].ToString().Trim();

                        olocation.Name = locName.Trim();
                        olocation.Tier = nIndex;
                        olocation.Status = EnumStatus.Active;
                        if (olocation.Name == "")
                            AddStatus(nRow, row.EmployeeNo, "Name can't be empty." + oconfig.Value, EnumSAPProcessStatus.Error, EnumDataIntegrationType.EmployeeBasic);
                       // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(oconfig.Value + " Name", nRow, oconfig.Value + " Name can't be empty"));
                        AddStatus(nRow, row.EmployeeNo, "New " + oconfig.Value + " has been created:" + olocation.Name
                                  , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);


                        if (islocCodeAutoGen == false)
                        {
                            //  olocation.Code = row[oconfig.Value + " Code"].ToString().Trim();
                            olocation.Code = locCode.Trim();
                            if (olocation.Code == "")
                                AddStatus(nRow, row.EmployeeNo, " Code can't be empty." + oconfig.Value, EnumSAPProcessStatus.Error, EnumDataIntegrationType.EmployeeBasic);
                          //  _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(oconfig.Value + " Code", nRow, oconfig.Value + " Code can't be empty"));

                        }
                        if (nIndex > 1) olocation.ParentID = (nparentid);
                        _locationid = _locationid + 1;
                        nparentid = _locationid;
                        oemployee.LocationID = (_locationid);

                        olocation.SetObjectID(_locationid);
                        olocation.PayrollTypeID = this._payrollTypeID;
                        olocation.CreatedBy = this._userID;
                        _locations.Add(olocation);
                    }
                    else
                    {
                        //AddStatus(nRow, row.EmployeeNo, "Location has been changed, new Location:" + olocation.Name
                        //          , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        nparentid = olocation.ID;
                        oemployee.LocationID = olocation.ID;
                        olocation.ModifiedBy = this._userID;
                    }
                }
                #endregion
                /// <summary>                
                /// Process religion whether it is already in the system or new religion
                /// </summary>               
                #region Religion upload
                Religion oreligion = null;
                if (isreligionCodeAutoGen == false)
                    oreligion = _religions.Find(delegate (Religion item) { return item.Code == row.ReligionCode.ToString().Trim(); });
                else
                    oreligion = _religions.Find(delegate (Religion item) { return item.Name == row.Religion.ToString().Trim(); });

                if (oreligion == null)
                {
                    oreligion = new Religion();
                    oreligion.Name = row.Religion.ToString().Trim();
                    if (isreligionCodeAutoGen == false)
                    {
                        oreligion.Code = oreligion.Code.ToString().Trim();

                    }
                    _religionID = _religionID + 1;
                    oemployee.ReligionID = (_religionID);
                    oreligion.CreatedBy = this._userID;

                    oreligion.SetObjectID(_religionID);
                    AddStatus(nRow, row.EmployeeNo, "Religion has been created, new religion:" + oreligion.Name
                                  , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    _religions.Add(oreligion);
                }
                else
                {
                    //AddStatus(nRow, row.EmployeeNo, "Religion has been changed, religion:" + oreligion.Name
                    //              , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    oemployee.ReligionID = oreligion.ID;
                    oreligion.ModifiedBy = this._userID;
                }

                #endregion Religion upload
                /// <summary>                
                /// Process designation whether it is already in the system or new designation
                /// </summary>       
                #region Designation upload
                Designation odesignation = null;
                if (isdesignationCodeAutoGen == false)
                    odesignation = _designations.Find(delegate (Designation item) { return item.Code == row.DesignationCode.ToString().Trim(); });
                else
                    odesignation = _designations.Find(delegate (Designation item) { return item.Name == row.Designation.ToString().Trim(); });

                if (odesignation == null)
                {
                    odesignation = new Designation();
                    odesignation.Name = row.Designation.ToString().Trim();

                    if (isdesignationCodeAutoGen == false)
                        odesignation.Code = odesignation.Code.ToString().Trim();
                    _designationid = _designationid + 1;
                    oemployee.DesignationID = (_designationid);
                    odesignation.SetObjectID(_designationid);
                    odesignation.Status = EnumStatus.Active;
                    odesignation.CreatedBy = this._userID;
                    odesignation.PayrollTypeID = this._payrollTypeID;
                    AddStatus(nRow, row.EmployeeNo, "Designation has been created, designation: " + odesignation.Name
                                  , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    _designations.Add(odesignation);
                }
                else
                {
                    //AddStatus(nRow, row.EmployeeNo, "Designation has been changed, designation: " + odesignation.Name
                    //              , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    oemployee.DesignationID = odesignation.ID;
                    odesignation.ModifiedBy = this._userID;
                }

                #endregion Designation upload
                Costcenter crg = null;
                if (iscrgCodeAutoGenerte == false)
                    crg = _costCenters.Find(delegate (Costcenter item) 
                    { return item.Code == row.CostCenterCode.ToString().Trim(); });
                else
                    crg = _costCenters.Find(delegate (Costcenter item) { 
                        return item.Name == row.CostCenterName.ToString().Trim(); });

                if (crg == null)
                {
                    crg = new Costcenter();
                    crg.Name = row.CostCenterName.ToString().Trim();
                    crg.Code = row.CostCenterCode.ToString().Trim();

                    //if (iscrgCodeAutoGenerte == false)
                    //    crg.Code = crg.Code.ToString().Trim();
                    _costCenterId = _costCenterId + 1;
                    oemployee.CrgId = (_costCenterId);
                    crg.PayrollTypeID = this._payrollTypeID;
                    crg.SetObjectID(_costCenterId);
                    crg.Tier = 1;
                    //crg.ParentID
                    crg.Status = EnumStatus.Active;
                    crg.CreatedBy = this._userID;
                    crg.PayrollTypeID = this._payrollTypeID;
                    AddStatus(nRow, row.EmployeeNo, "Cost-center has been created, : " + crg.Name
                                  , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    _costCenters.Add(crg);
                }
                else
                {
                    //AddStatus(nRow, row.EmployeeNo, "Designation has been changed, designation: " + odesignation.Name
                    //              , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    oemployee.CrgId = crg.ID;
                    crg.ModifiedBy = this._userID;
                }


                #region Bank & Branch upload

                if (row.SalaryBank.ToString().Trim() != "")
                {

                    Bank obank = null;
                    if (isbankCodeAutoGen == false)
                    {
                        obank = _banks.Where(x =>
                                             x.Code.ToUpper().Trim() == row.SalaryBankCode.ToString().ToUpper().Trim())
                                      .FirstOrDefault();
                    }
                    else
                    {
                        obank = _banks.Where(x =>
                                             x.Name.ToUpper().Trim() == row.SalaryBank.ToString().ToUpper().Trim())
                                      .FirstOrDefault();
                    }
                    if (obank == null)
                    {
                        obank = new Bank();
                        obank.Name = row.SalaryBank.ToString().Trim();
                        if (isbankCodeAutoGen == false)
                            obank.Code = row.SalaryBankCode.ToString().Trim();
                        _bankid = _bankid + 1;
                        obank.SetObjectID(_bankid);
                        obank.CreatedBy = this._userID;
                        obank.PayrollTypeID = this._payrollTypeID;
                        AddStatus(nRow, row.EmployeeNo, "new Salary bank Account has been created, Bank account:  " + obank.Name
                                 , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        _banks.Add(obank);
                    }

                    if (row.SalaryBranch.ToString() != "")
                    {

                        Branch oBranch = null;
                        if (isbranchCodeAutoGen == false)
                        {
                            oBranch = _branches.Where(item =>
                                                      item.Code.ToUpper().Trim() == row.SalaryBranchCode.ToString().ToUpper().Trim()
                                                      && item.BankID == obank.ID)
                                               .FirstOrDefault();
                        }
                        else
                        {
                            oBranch = _branches.Where(item =>
                                                      item.Name.ToUpper().Trim() == row.SalaryBranch.ToString().ToUpper().Trim()
                                                      && item.BankID == obank.ID)
                                               .FirstOrDefault();
                        }
                        if (oBranch == null)
                        {
                            oBranch = new Branch();
                            oBranch.Name = row.SalaryBranch.ToString().Trim();
                            if (isbranchCodeAutoGen == false)
                                oBranch.Code = row.SalaryBranchCode.ToString().Trim();
                            _branchid = _branchid + 1;
                            oBranch.BankID = obank.ID;
                            oBranch.SetObjectID(_branchid);
                            oemployee.BranchID = (_branchid);
                            oBranch.CreatedBy = this._userID;
                            oBranch.PayrollTypeID = this._payrollTypeID;
                            AddStatus(nRow, row.EmployeeNo, "new branch has been created, Branch:  " + obank.Name
                                 , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                            _branches.Add(oBranch);
                        }
                        else
                        {
                            //AddStatus(nRow, row.EmployeeNo, "Branch has been changed, Branch:  " + oBranch.Name
                            //     , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                            oemployee.BranchID = oBranch.ID;
                            oBranch.ModifiedBy = this._userID;
                        }
                    }
                }
                bool isOPISeparateAcountApplicable = true; // ConfigurationManager.GetBoolValue("opi", "separateaccount", EnumConfigurationType.Logic);

                if (isOPISeparateAcountApplicable)
                {
                    if (!String.IsNullOrEmpty(row.OPIBankName))
                    {

                        Bank obank = null;

                        //if (isbankCodeAutoGen == false)
                        //{
                        //    obank = _banks.Where(x =>
                        //                         x.Code.ToUpper().Trim() == row.opi.ToString().ToUpper().Trim())
                        //                  .FirstOrDefault();
                        //}
                        //else
                        //{
                        obank = _banks.Where(x =>
                                             x.Name.ToUpper().Trim() == row.OPIBankName.ToString().ToUpper().Trim())
                                      .FirstOrDefault();
                        // }

                        if (obank == null)
                        {
                            obank = new Bank();
                            obank.Name = row.OPIBankName.ToString().Trim();
                            if (isbankCodeAutoGen == false)
                                obank.Code = obank.Code.ToString().Trim();
                            _bankid = _bankid + 1;
                            obank.SetObjectID(_bankid);
                            obank.CreatedBy = this._userID;
                            _banks.Add(obank);
                            AddStatus(nRow, row.EmployeeNo, "new OPI Bank has been created, Bank:  " + obank.Name
                                , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        }

                        if (!string.IsNullOrEmpty(row.OPIBranchName))
                        {

                            Branch oBranch = null;
                            //if (isbranchCodeAutoGen == false)
                            //{
                            //    oBranch = _branches.Where(item =>
                            //                              item.Code.ToUpper().Trim() == row["OPI Branch Code"].ToString().ToUpper().Trim()
                            //                              && item.BankID == obank.ID)
                            //                       .FirstOrDefault();
                            //}
                            //else
                            //{
                            oBranch = _branches.Where(item =>
                                                      item.Name.ToUpper().Trim() == row.OPIBranchName.ToString().ToUpper().Trim()
                                                      && item.BankID == obank.ID)
                                               .FirstOrDefault();
                            //}

                            if (oBranch == null)
                            {
                                oBranch = new Branch();
                                oBranch.Name = row.OPIBranchName.ToString().Trim();
                                if (isbranchCodeAutoGen == false)
                                    oBranch.Code = oBranch.Code.ToString().Trim();
                                _branchid = _branchid + 1;
                                oBranch.BankID = obank.ID;
                                oBranch.CreatedBy = this._userID;
                                oBranch.SetObjectID(_branchid);
                                oemployee.OutPayBranchID = (_branchid);
                                _branches.Add(oBranch);
                                AddStatus(nRow, row.EmployeeNo, "new OPI Branch has been created, Branch:  " + oBranch.Name
                                , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                            }
                            else
                            {
                                oemployee.OutPayBranchID = oBranch.ID;
                                obank.ModifiedBy = this._userID;

                            }
                        }
                    }
                }

                #endregion Life Cycle Event

                if (row.LIFE_CYCLE_EVENT != null)
                {
                    EmployeeStatus empStatus = _oEmployeeStatus.Where(x => x.Description.ToLower().Trim() == row.LIFE_CYCLE_EVENT.ToLower().Trim()).FirstOrDefault();
                    if (empStatus == null)
                    {
                        AddStatus(nRow, row.EmployeeNo, "Life Cycle Event not found :  " + row.LIFE_CYCLE_EVENT
                               , EnumSAPProcessStatus.Error, EnumDataIntegrationType.EmployeeBasic);
                    }
                    else
                    {
                        if (oemployee.EmpLifeCycle == null) oemployee.EmpLifeCycle = new EmpLifeCycle();
                        oemployee.EmpLifeCycle.EmpStatusObject = empStatus;
                        oemployee.EmpLifeCycle.StatusDetailID = empStatus.ID;
                        oemployee.EmpLifeCycle.Description = row.LIFE_CYCLE_EVENT.ToString().Trim();
                        oemployee.EmpLifeCycle.EffectDate = Convert.ToDateTime(row.AssignmentChangeDate);
                    }
                }


                _employees.Add(oemployee);

            }
            return true;
        }

        public void Save(int nPayrollTypeID, int userid, EnumRegularDataUpload uploaid)
        {
            try
            {
                foreach (Employee item in _employees)
                {
                    item.PayrollTypeID = nPayrollTypeID;
                    item.CreatedBy = userid;
                }
                RegularDataUploadService rdsrv = new RegularDataUploadService();

                //rdsrv.Save(_categorys, _grades, _departments, _locations, _religions,
                //                         _designations, _banks, _branches, _employees, _accessCards, nPayrollTypeID, uploaid);
                Save(_categorys, _grades, _departments, _locations, _religions,
                                         _designations, _banks, _branches, _employees, _accessCards,
                                        _costCenters, nPayrollTypeID, uploaid);
            }
            catch (Exception ex)
            {
                throw new ServiceException(ex.Message);
            }
        }

        public void Save(List<Category> categorys, List<Grade> grades, List<Department> departments,
            List<Location> locations,
            List<Religion> religions, List<Designation> designations, List<Bank> banks,
            List<Branch> branches, List<Employee> employees,
            List<AccessCard> oaccessCards, List<Costcenter> crgs,
            int payrollTypeID, EnumRegularDataUpload uploaid)
        {

            List<GradeSegment> segments = new GradeSegmentService().Get(EnumStatus.Regardless);
            TransactionContext tc = null;
            _payrollTypeID = payrollTypeID;
            try
            {
                if (segments.Count == 0)
                {
                    GradeSegment osg = new GradeSegment();
                    osg.Code = "001";
                    osg.Name = "Default";
                    osg.CreatedBy = this._userID;
                    osg.CreatedDate = DateTime.Today;
                    GradeSegmentService ogSrv = new GradeSegmentService();
                    ogSrv.Save(osg);
                    grades.ForEach(x => { x.GradeSegmentID = osg.ID; });
                }
                else
                {
                    grades.ForEach(x => { x.GradeSegmentID = segments[0].ID; });

                }

                List<Category> scategories = new CategoryService().Get(EnumStatus.Regardless, this._payrollTypeID);
                List<Grade> sGrades = new GradeService().Get(EnumStatus.Regardless, this._payrollTypeID);
                List<Location> sLocations = new LocationService().Get(EnumStatus.Regardless, this._payrollTypeID);
                List<Department> sdepartments = new DepartmentService().Get(EnumStatus.Regardless, this._payrollTypeID);
                List<Designation> sdesignation = new DesignationService().Get(EnumStatus.Regardless, this._payrollTypeID);
                List<Religion> sReligions = new ReligionService().Get(EnumStatus.Regardless);
                List<Bank> sBanks = new BankService().Get();
                List<Branch> sBrances = new BranchService().Get(EnumStatus.Regardless, this._payrollTypeID);
                List<Costcenter> scostcenters = new CostcenterService().Get(EnumStatus.Regardless,
                    this._payrollTypeID);

                tc = TransactionContext.Begin(true);

                CategoryService.SaveForUpload(tc, categorys, scategories);
                GradeService.SaveForUpload(tc, grades, sGrades);
                LocationService.SaveForUpload(tc, locations, sLocations);
                ReligionService.SaveForUpload(tc, religions, sReligions);
                DesignationService.SaveForUpload(tc, designations, payrollTypeID, sdesignation);
                DepartmentService.SaveForUpload(tc, departments, sdepartments);
                BankService.SaveForUpload(tc, banks, sBanks);
                BranchService.SaveForUpload(tc, branches, sBrances);
                CostcenterService.SaveForUpload(tc, crgs, scostcenters);


                EmployeeService.SaveForIntegration(tc, employees, uploaid);

                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void ImportEmpBasicInfo(List<DataIntegration> odataTable, int payrollTypeID, int userid)
        {
            Employee oemployee = null;
            this._payrollTypeID = payrollTypeID;
            this._userID = userid;  
            PayrollType ptype = new PayrollTypeService().Get(payrollTypeID);
            #region Refresh Objects
            if (ProcessBasicData(odataTable) == false) return;
            int nRow = 0;
            bool isGrossApplicable = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "grossapplicable");
            

            try
            {
                foreach (DataIntegration dr in odataTable)
                {
                    nRow = nRow + 1;
                    oemployee = _employees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr.EmployeeNo.ToString(); });
                    if (oemployee == null) throw new ServiceException("Employee not found in the collection; employeeNo:" + dr.EmployeeNo.ToString());
                    oemployee.Name = dr.EmployeeName.ToString().Trim();

                    var empExist = this._allEmployee.FirstOrDefault(x => x.EmployeeNo == oemployee.EmployeeNo);
                    if (empExist == null)
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "New Employee added in the System", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }
                    oemployee.FatherName = String.IsNullOrEmpty(dr.FathersName) ? "" : dr.FathersName.ToString().Trim();
                    //
                    oemployee.BirthDate = Convert.ToDateTime(dr.DateOfBirth);
                    if (empExist != null && oemployee.BirthDate != empExist.BirthDate)
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "Employee Birth date has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }
                    //
                    oemployee.JoiningDate = Convert.ToDateTime(dr.DateOfJoining);
                    if (empExist != null && oemployee.JoiningDate != empExist.JoiningDate)
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "Employee joining date has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }
                    //
                    oemployee.LineManagerNo = dr.LineManagerID != string.Empty ? dr.LineManagerID : null;
                    if (empExist != null && oemployee.LineManagerNo != empExist.LineManagerNo)
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "Employee Line Maneger has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }

                    if (oemployee.EmployeeNo == oemployee.LineManagerNo)
                    {
                        _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Line Manager", 
                            nRow, "Employee and line-Manager can't be Same-ID:" + 
                            oemployee.EmployeeNo, oemployee.EmployeeNo, oemployee.Name));
                    }
                    //  throw new ServiceException("Invalid line manager ID, Employee can not be his ownLine-manger; employeeNo:" + dr.EmployeeNo.ToString());

                    //For Novartis Discontinue Employee Upload and Fund Management Data Issue
                    //oemployee.Status = EnumEmployeeStatus.Discontinued;

                    oemployee.Gender = (dr.Gender.Trim() == "Male" || dr.Gender.Trim() == "M" || dr.Gender.Trim() == "MALE") ? EnumGender.Male : EnumGender.Female;
                    if (empExist != null && oemployee.Gender != empExist.Gender)
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "Employee Gender has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }

                    oemployee.MaritalStatus = (dr.MaritalStatus.Trim().ToUpper() == "MARRIED") ? EnumMaritalStatus.Married : EnumMaritalStatus.UnMarried;
                    if (empExist != null && oemployee.MaritalStatus != empExist.MaritalStatus)
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "Employee Marital Status has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }
                    //oemployee.TaxCircle = dr["Tax Circle"].ToString() != string.Empty ? (EnumTaxCircle)Enum.Parse(typeof(EnumTaxCircle), dr["Tax Circle"].ToString(), true) : EnumTaxCircle.Employee;
          //          oemployee.TaxCircle = String.IsNullOrEmpty(dr.TaxCircle) ? "" : dr.TaxCircle.ToString().Trim();
                    //if (empExist != null && oemployee.TaxCircle.Trim() != empExist.TaxCircle.Trim())
                    //{
                    //    AddStatus(nRow, oemployee.EmployeeNo, "Employee Tax Circle has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    //}
                    oemployee.TinNo = dr.TIN.Trim();
                    if (empExist != null && oemployee.TinNo.Trim() != empExist.TinNo.Trim())
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "Employee Tin No has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }
                    //if (dr.ConfirmationDate.ToString() != "") oemployee.ConfirDate = Convert.ToDateTime(dr.ConfirmationDate);
                    //if (empExist != null && oemployee.ConfirDate != empExist.ConfirDate)
                    //{
                    //    AddStatus(nRow, oemployee.EmployeeNo, "Employee Confirmation Date has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    //}
                    //if (oemployee.ConfirDate != null && oemployee.ConfirDate != DateTime.MinValue)
                    //    oemployee.IsConfirmed = true;

                    if (dr.PFMembership.ToUpper().Trim() == "Y")
                        oemployee.PFMemberType = EnumPFMembershipType.Live;

                    if (empExist != null && oemployee.PFMemberType != empExist.PFMemberType)
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "Employee PF Membership has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }

                    oemployee.EmailAddress = !string.IsNullOrEmpty(dr.EmailAddress) ? dr.EmailAddress : null;
                    if (empExist != null && !string.IsNullOrEmpty(empExist.EmailAddress) && !string.IsNullOrEmpty(oemployee.EmailAddress))
                    {
                       if (oemployee.EmailAddress != empExist.EmailAddress)
                            AddStatus(nRow, oemployee.EmployeeNo, "Employee Email Address has changed", EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(oemployee.EmailAddress))
                          AddStatus(nRow, oemployee.EmployeeNo, "New Email Address has added. new Email: " + oemployee.EmailAddress, EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                    }
                    //oemployee.ForeignExPat = dr["Is Foreign Expatriate"].ToString() != string.Empty ? (dr["Is Foreign Expatriate"].ToString() == "YES" ? true : false) : false;

                    //Refresh Employee Grade Salary
                    if (oemployee.GradeID != null)
                    {
                        Grade ograde = _grades.FirstOrDefault(x => x.ID == (int)oemployee.GradeID);
                        //     oemployee.EmployeeGradeSalary.ID = oemployee.ID;
                        //     oemployee.EmployeeGradeSalary.SetObjectID(oemployee.ID
                        oemployee.EmployeeGradeSalary = new EmployeeGradeSalary();
                        oemployee.EmployeeGradeSalary.EmployeeID = oemployee.ID;
                        oemployee.EmployeeGradeSalary.GradeID = (int)oemployee.GradeID;
                        oemployee.EmployeeGradeSalary.GradeSalaryTypeID = (1);
                        if (isGrossApplicable == true) oemployee.EmployeeGradeSalary.GrossSalary = dr.GrossSalary != string.Empty ? Convert.ToDouble(dr.GrossSalary) : 0.0;
                        oemployee.EmployeeGradeSalary.BasicSalary = dr.BasicSalary.ToString() != string.Empty ? Convert.ToDouble(dr.BasicSalary) : 0.0;
                        oemployee.BasicSalary = oemployee.EmployeeGradeSalary.BasicSalary;
                        oemployee.GrossSalary = oemployee.EmployeeGradeSalary.GrossSalary;
                        oemployee.EmployeeGradeSalary.EffectDate = Convert.ToDateTime( dr.BasicSalaryEffectDate);

                        if (empExist != null)
                        {
                            if (oemployee.GradeID != empExist.GradeID 
                                || oemployee.BasicSalary != empExist.BasicSalary)
                            {
                                AddStatus(nRow, oemployee.EmployeeNo, "Grade & Basic Salary has changed, new grade:" + ograde.Name
                                          + " , basic: " + oemployee.BasicSalary.ToString() + " & effect date:" + oemployee.EmployeeGradeSalary.EffectDate
                                         , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);

                            }
                            else
                            {
                                oemployee.EmployeeGradeSalary = null;
                                oemployee.GradeID = null;
                                oemployee.BasicSalary = 0;
                                oemployee.GrossSalary = 0;
                            }
                        }
                    }

                    //Location

                    if (empExist != null )
                    {
                        if (oemployee.LocationID != empExist.LocationID)
                        {
                            var newLocation = _locations?.Find(x => x.ID == oemployee.LocationID);
                            AddStatus(nRow, oemployee.EmployeeNo, "Location has been changed, new Location:" + newLocation.Name
                                      , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        }
                        else oemployee.LocationID = null;
                    }
                    //Department
                    if (empExist != null)
                    {
                        if (oemployee.DepartmentID != empExist.DepartmentID)
                        {
                            var neDep = _departments?.Find(x => x.ID == oemployee.DepartmentID);
                            AddStatus(nRow, oemployee.EmployeeNo, "Location has been changed, new Location:" + neDep.Name
                                      , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        }
                        else oemployee.DepartmentID = null;
                    }
                    //Religion
                    if (empExist != null)
                    {
                        if (oemployee.ReligionID != empExist.ReligionID)
                        {
                            var newReligion = _religions?.Find(x => x.ID == oemployee.ReligionID);
                            AddStatus(nRow, oemployee.EmployeeNo, "Religion has been changed, religion:" + newReligion.Name
                                      , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        }
                    }
                    //Designation
                    if (empExist != null)
                    {

                        if (oemployee.DesignationID != empExist.DesignationID)
                        {
                            var newdesig = _designations?.Find(x => x.ID == oemployee.DesignationID);
                            AddStatus(nRow, oemployee.EmployeeNo, "Designation has been changed, designation:" + newdesig.Name
                                      , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        }
                        else oemployee.DesignationID = null;
                    }

                    if (empExist != null)
                    {

                        if (oemployee.CrgId != empExist.CrgId)
                        {
                            var newdesig = _costCenters?.Find(x => x.ID == oemployee.CrgId);
                            AddStatus(nRow, oemployee.EmployeeNo, "Cost-Center has been changed, Cost-Center:" + newdesig.Name
                                      , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        }
                        else oemployee.CrgId = null;
                    }

                    if (oemployee.EmpLifeCycle == null) oemployee.EmpLifeCycle = new EmpLifeCycle();
                    bool confirmChange = false;
                    if (dr.ConfirmationDate != null && dr.ConfirmationDate !="")
                    {
                        confirmChange = true;
                        oemployee.ConfirDate = Convert.ToDateTime(dr.ConfirmationDate);
                        oemployee.IsConfirmed = true;
                    }
                    if (empExist != null && confirmChange == true)
                    {

                        if ( empExist.IsConfirmed ==false)
                        {
                            AddStatus(nRow, oemployee.EmployeeNo, "provision to confirmed "
                                      , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        }
                        else confirmChange = false;
                    }


                    if (oemployee.GradeID != null || oemployee.BasicSalary != 0 
                        || oemployee.DepartmentID != null
                        || oemployee.LocationID != null || oemployee.DesignationID != null 
                        || oemployee.CrgId !=null || confirmChange == true)
                    {
                        oemployee.EmpLifeCycle.Employee = oemployee;
                        oemployee.EmpLifeCycle.CategoryID = oemployee.CategoryID;
                        oemployee.EmpLifeCycle.EmployeeGradeSalary = oemployee.EmployeeGradeSalary;
                        oemployee.EmpLifeCycle.EmployeeID = oemployee.ID;
                        oemployee.EmpLifeCycle.BasicSalary = oemployee.BasicSalary;
                        oemployee.EmpLifeCycle.GrossSalary = oemployee.GrossSalary;
                        oemployee.EmpLifeCycle.EffectDate = Convert.ToDateTime(dr.AssignmentChangeDate);//oemployee.JoiningDate;?
                        oemployee.EmpLifeCycle.GradeID = oemployee.GradeID;
                        oemployee.EmpLifeCycle.DepartmentID = oemployee.DepartmentID;
                        oemployee.EmpLifeCycle.DesignationID = oemployee.DesignationID;
                        oemployee.EmpLifeCycle.LocationID = oemployee.LocationID;
                        oemployee.EmpLifeCycle.CostCenterID = oemployee.CrgId;
                        oemployee.EmpLifeCycle.IsConfirm = (oemployee.IsConfirmed == true) ? true : false;
                        if (confirmChange == false)
                            oemployee.EmpLifeCycle.IsConfirm = null;


                        oemployee.EmpLifeCycle.HREmployee = new HREmployee();
                        oemployee.EmpLifeCycle.HREmployee.CategoryID = oemployee.CategoryID;
                        oemployee.EmpLifeCycle.HREmployee.ID = oemployee.ID;
                        oemployee.EmpLifeCycle.HREmployee.BasicSalary = (oemployee.BasicSalary == 0) ? empExist.BasicSalary : oemployee.BasicSalary;
                        oemployee.EmpLifeCycle.HREmployee.GrossSalary = (oemployee.GrossSalary == 0) ? empExist.GrossSalary : oemployee.GrossSalary;
                        oemployee.EmpLifeCycle.HREmployee.GradeID = (oemployee.GradeID == 0 || oemployee.GradeID == null) ? empExist.GradeID : oemployee.GradeID;
                        oemployee.EmpLifeCycle.HREmployee.DepartmentID = (oemployee.DepartmentID == 0 || oemployee.DepartmentID == null) ? empExist.DepartmentID : oemployee.DepartmentID;
                        oemployee.EmpLifeCycle.HREmployee.DesignationID = (oemployee.DesignationID == 0 || oemployee.DesignationID == null) ? empExist.DesignationID : oemployee.DesignationID;
                        oemployee.EmpLifeCycle.HREmployee.LocationID = (oemployee.LocationID == 0 || oemployee.LocationID == null) ? empExist.LocationID : oemployee.LocationID;
                        oemployee.EmpLifeCycle.HREmployee.CrgId = (oemployee.CrgId == 0 || oemployee.CrgId == null) ? empExist.CrgId : oemployee.CrgId;
                        oemployee.EmpLifeCycle.HREmployee.CompanyID = null;
                        oemployee.EmpLifeCycle.HREmployee.IsConfirmed = oemployee.IsConfirmed;
                        oemployee.EmpLifeCycle.HREmployee.ConfirDate = oemployee.ConfirDate;
                    }

                    oemployee.BasicSalary = (oemployee.BasicSalary == 0) ? empExist.BasicSalary : oemployee.BasicSalary;
                    oemployee.GrossSalary = (oemployee.GrossSalary == 0) ? empExist.GrossSalary : oemployee.GrossSalary;
                    oemployee.GradeID = (oemployee.GradeID == 0 || oemployee.GradeID == null) ? empExist.GradeID : oemployee.GradeID;
                    oemployee.DepartmentID = (oemployee.DepartmentID == 0 || oemployee.DepartmentID == null) ? empExist.DepartmentID : oemployee.DepartmentID;
                    oemployee.DesignationID = (oemployee.DesignationID == 0 || oemployee.DesignationID == null) ? empExist.DesignationID : oemployee.DesignationID;
                    oemployee.LocationID = (oemployee.LocationID == 0 || oemployee.LocationID == null) ? empExist.LocationID : oemployee.LocationID;
                    oemployee.CrgId = (oemployee.CrgId == 0 || oemployee.CrgId == null) ? empExist.CrgId : oemployee.CrgId;
                   

                    //Refresh Emloyee Bank Account                        
                    if (oemployee.BranchID != null)
                    {
                        if (dr.SalaryAccountNumber.ToString() != "")
                        {
                            oemployee.AccountNo = dr.SalaryAccountNumber.ToString();
                            oemployee.EmployeeBankAccount = new EmployeeBankAccount();
                            // oemployee.EmployeeBankAccount.SetObjectID(oemployee.ID.Integer);
                            oemployee.EmployeeBankAccount.EmployeeID = oemployee.ID;
                            oemployee.PaymentMode = EnumPaymentMode.BankTransfer;
                            oemployee.EmployeeBankAccount.EffectDate = Convert.ToDateTime( dr.SALARY_ACCOUNT_EFFECT_DATE);
                            oemployee.EmployeeBankAccount.BranchID = oemployee.BranchID != null ? (int)oemployee.BranchID : 0;
                            oemployee.EmployeeBankAccount.AccountType = EnumBankAccountType.SalaryAccount;
                            oemployee.EmployeeBankAccount.AccountNo = dr.SalaryAccountNumber.ToString();
                            oemployee.AccountNo = oemployee.EmployeeBankAccount.AccountNo;
                            oemployee.EmployeeBankAccount.CreatedDate = DateTime.Today;
                            oemployee.CreatedBy = _userID;
                        }
                        else
                            _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Salary Account Number", nRow, "'Salary Account Number' Column not found for the employee No:" + oemployee.EmployeeNo, oemployee.EmployeeNo, oemployee.Name));

                        if (empExist != null)
                        {
                            if (oemployee.BranchID != empExist.BranchID ||
                                oemployee.AccountNo != empExist.AccountNo)
                            {
                                var newBranch = _branches?.Find(x => x.ID == oemployee.BranchID);
                                AddStatus(nRow, oemployee.EmployeeNo, "Employee Salary Branch has been changed, Branch:" + newBranch.Name
                                          , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                                if(oemployee.EmployeeBankAccount.EffectDate <= ptype.NextPayProcessDate)    
                                _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Bank Account Effect-Date", 
                                    nRow, "Bank-Account Change Effect Date can't be priror to last salary month."));

                            }
                            else oemployee.EmployeeBankAccount = null;
                        }
                    }

                    if (oemployee.OutPayBranchID != null)
                    {
                        if (dr.OPIAccountNumber != "")
                        {
                            oemployee.OutPayAccountNo = dr.OPIAccountNumber.ToString();
                            // oemployee.EmployeeOPIBankAccount.SetObjectID(oemployee.ID.Integer);
                            oemployee.EmployeeOPIBankAccount = new EmployeeBankAccount();
                            oemployee.OutPayPaymentMode = EnumPaymentMode.BankTransfer;
                            oemployee.EmployeeOPIBankAccount.EffectDate = oemployee.JoiningDate;
                            oemployee.EmployeeOPIBankAccount.BranchID = (int)oemployee.OutPayBranchID;
                            oemployee.EmployeeOPIBankAccount.AccountType = EnumBankAccountType.OutPayAccount;
                            oemployee.EmployeeOPIBankAccount.AccountNo = dr.OPIAccountNumber.ToString();

                        }
                        else
                            _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("OPI Account Number", nRow, "'OPI Account Number' Column not found for the employee No:" + oemployee.EmployeeNo, oemployee.EmployeeNo, oemployee.Name));

                        if (empExist != null && oemployee.OutPayBranchID != empExist.OutPayBranchID)
                        {
                            var newBranch = _branches?.Find(x => x.ID == oemployee.OutPayBranchID);
                            AddStatus(nRow, oemployee.EmployeeNo, "Employee OPI Branch has been changed, Branch:" + newBranch.Name
                                      , EnumSAPProcessStatus.Success, EnumDataIntegrationType.EmployeeBasic);
                        }
                    }

                    //if (dr["PROXID"].ToString() != "")
                    //{
                    //    _accessCardID = _accessCardID + 1;
                    //    oemployee.CardID = (_accessCardID);
                    //    AccessCard ocard = new AccessCard();
                    //    // ocard.SetObjectID(_accessCardID);
                    //    ocard.ID = _accessCardID;
                    //    ocard.CardNumber = dr["PROXID"].ToString();
                    //    ocard.TypeID = (1);
                    //    ocard.Status = EnumCardStatus.Attached;
                    //    ocard.CardOperation.EmployeeID = oemployee.ID;
                    //    ocard.CardOperation.CardID = ocard.ID;
                    //    ocard.CardOperation.AssignDate = oemployee.JoiningDate;
                    //    _accessCards.Add(ocard);
                    //}

                    oemployee.CreatedBy = userid;
                    oemployee.CreatedDate = DateTime.Today;
                }
                foreach (Employee item in _employees)
                {
                    if (item.LineManagerNo != null && item.LineManagerNo != string.Empty)
                    {
                        var linemanger = _employees.Find(delegate (Employee emp) { return emp.EmployeeNo == item.LineManagerNo; });
                        if (linemanger == null)
                        {
                            var existLineManager = _allEmployee.Find(delegate (Employee emp) { return emp.EmployeeNo == item.LineManagerNo; });
                            if (existLineManager == null)
                                _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Line Manager ID", nRow, "Invalid Line Manager"));
                        }
                    }
                    nRow = nRow + 1;
                }
            }
            catch (Exception ex)
            {
                throw new ServiceException("Error occered on row:" + nRow + " Reason:" + ex.Message);
            }

            #endregion

        }


        public void RefreshObject()
        {
            _departments = dserv.Get(EnumStatus.Regardless, this._payrollTypeID);
            _departmentid = miserv.GetNextID("Department", "DepartmentID", "");
            _categorys = cserv.Get(EnumStatus.Regardless, this._payrollTypeID);
            _categoryID = miserv.GetNextID("Category", "CategoryID", "");
            _grades = gserv.Get(EnumStatus.Regardless, this._payrollTypeID);
            _gradeid = miserv.GetNextID("Grades", "GradeID", "");

            _locations = locserv.Get(EnumStatus.Regardless, this._payrollTypeID);
            _locationid = miserv.GetNextID("Location", "LocationID", "");

            _religions = rserv.Get(EnumStatus.Regardless);
            _religionID = miserv.GetNextID("Religion", "ReligionID", "");

            _designations = degserv.Get(EnumStatus.Regardless, this._payrollTypeID);
            _designationid = miserv.GetNextID("Designation", "DesignationID", "");

            _banks = bankserv.Get(EnumStatus.Regardless, this._payrollTypeID);
            _bankid = miserv.GetNextID("Banks", "BankID", "");

            _branches = branchserve.Get(EnumStatus.Regardless, this._payrollTypeID);
            _branchid = miserv.GetNextID("BRANCHES", "BranchID", ""); ;

            _costCenters = new CostcenterService().Get(EnumStatus.Regardless, this._payrollTypeID);
            _costCenterId = miserv.GetNextID("CRG", "CRGID", ""); ;

            SearchManager omanager = new SearchManager(EnumSearchFrom.Employee);
            omanager.Parameter.Remove(EnumSearchParameter.PayrollTypeID);
            _oEmployeeStatus = new EmployeeStatusService().Get(EnumStatus.Regardless);

            // List<SearchEmployee> oemployees = omanager.Find();
            List<SearchEmployee> oemployees = seserv.Find(omanager);
            if (oemployees.Count > 0)
            {
                //_emloyeeId = oemployees.Max(x => x.EmployeeID.Integer);
                _emloyeeId = oemployees.Max(x => x.EmployeeID);
            }

        }

        //        public void ProcessData(DataIntegrationHeader dataList)
        //        {
        //            try
        //            {
        //                int nCount = 1;
        //                // find user from Data
        //                // find payrolltpye from data

        //                try
        //                {
        ////                    SaveBulkRequest(dataList);
        ////                    _oHRDataUploads = dataList;
        //                    _oEmployeeCollection = new List<Employee>();
        //                    _oErrorList = new List<SuccessorErrorList>();
        //                    _oDepartments = new DepartmentService().Get(EnumStatus.Active, 1);
        //                    _oLocations = new LocationService().Get();
        //                    _oDesignations = new DesignationService().Get(EnumStatus.Active, 1);
        //                    _oReligions = new ReligionService().Get();
        //                    _oCategories = new CategoryService().GetAll();
        //                    _oGrades = new GradeService().GetAllGrade(1, EnumStatus.Active, "", "");
        //                    CheckFieldValidation();
        //                }
        //                catch (Exception exp)
        //                {
        //                    throw new Exception(exp.Message);
        //                }
        //            }
        //            catch (Exception e)
        //            {
        //                #region Handle Exception

        //                //if (tc != null)
        //                //    tc.HandleError();
        //                ExceptionLog.Write(e);
        //                throw new ServiceException(e.Message, e);

        //                #endregion
        //            }
        //        }

        //public void SaveDataIntergration(DataIntegrationHeader dataList)
        //{
        //    try
        //    {
        //        int nCount = 1;


        //        try
        //        {
        //            //SaveBulkRequest(dataList);
        //            //_oHRDataUploads = dataList;
        //            _oEmployeeCollection = new List<Employee>();
        //            _oErrorList = new List<SuccessorErrorList>();
        //            _oDepartments = new DepartmentService().Get(EnumStatus.Active, 1);
        //            _oLocations = new LocationService().Get();
        //            _oDesignations = new DesignationService().Get(EnumStatus.Active, 1);
        //            _oEmployees = new EmployeeService().GetAllEmps();
        //            _oReligions = new ReligionService().Get();
        //            _oBanks = new BankService().Get();
        //            _oBranchs = new BranchService().Get(EnumStatus.Regardless, 1);
        //            _oCategories = new CategoryService().GetAll();
        //            _oGrades = new GradeService().GetAllGrade(1, EnumStatus.Active, "", "");
        //            CheckFieldValidation();
        //            if (_oErrorList.Count > 0)
        //            {
        //                BulkSave(_oErrorList);
        //                var response = new
        //                {
        //                    Message = "Validation Failed",
        //                    Errors = _oErrorList
        //                };

        //                //return new Exception(response);
        //                new Exception(response.ToString());
        //            }


        //            foreach (DataIntegration item in _oHRDataUploads)
        //            {
        //                Employee oEmp = null;
        //                EmpLifeCycle lifeCycle = new EmpLifeCycle();

        //                Employee emp = _oEmployees.Find(x => x.EmployeeNo == item.EmployeeNo);
        //                if (emp == null)
        //                {
        //                    oEmp = new Employee();
        //                    oEmp.EmployeeNo = item.EmployeeNo;
        //                    AddStatus(nCount, oEmp.EmployeeNo, "New Employee is created in the system with Employee No: " + item.EmployeeNo, EnumSAPProcessStatus.Success);
        //                }
        //                else
        //                    oEmp = emp;
        //                oEmp.EmpLifeCycle = new EmpLifeCycle();
        //                oEmp.Name = item.EmployeeName;
        //                oEmp.FatherName = item.FathersName;
        //                oEmp.GlobalID = item.GlobalID;
        //                oEmp.BirthDate = Convert.ToDateTime(item.DateOfBirth);
        //                if (oEmp.DescriptionText != item.Designation)
        //                {
        //                    oEmp.DescriptionText = item.Designation;
        //                    //  oEmp.EmpLifeCycle.DesignationText = item.Designation;
        //                }
        //                Category cat = _oCategories.Find(x => x.Name == item.Category);
        //                if (cat != null)
        //                {
        //                    if (oEmp.CategoryID != cat.ID)
        //                    {
        //                        oEmp.CategoryID = cat.ID;
        //                        oEmp.EmpLifeCycle.CategoryID = cat.ID;
        //                    }
        //                }
        //                else
        //                    AddStatus(nCount, oEmp.EmployeeNo, "Invalid Category : " + item.Category, EnumSAPProcessStatus.Error);
        //                Designation deg = _oDesignations.Find(x => x.Name == item.Designation);
        //                if (deg != null)
        //                {

        //                    if (oEmp.DesignationID != deg.ID)
        //                    {
        //                        oEmp.DesignationID = deg.ID;
        //                        oEmp.EmpLifeCycle.DesignationID = deg.ID;
        //                    }

        //                }
        //                else
        //                    AddStatus(nCount, oEmp.EmployeeNo, "Invalid Dsignation : " + item.Designation, EnumSAPProcessStatus.Error);

        //                //if (item.Category == "Apprentice")
        //                //    oEmp.PayrollTypeID = ID.FromInteger(2);
        //                //else
        //                //    oEmp.PayrollTypeID = ID.FromInteger(1);

        //                Grade grd = _oGrades.Find(x => x.Name == item.Grade);

        //                if (oEmp.GlobalID != item.GlobalID)
        //                {
        //                    oEmp.GlobalID = item.GlobalID;
        //                }
        //                if (oEmp.JoiningDate != null)
        //                {
        //                    if (oEmp.JoiningDate != Convert.ToDateTime(item.DateOfJoining))
        //                    {
        //                        oEmp.JoiningDate = Convert.ToDateTime(item.DateOfJoining);
        //                        oEmp.Status = EnumEmployeeStatus.Live;

        //                        oEmp.EmpLifeCycle.IsContinue = true;
        //                    }
        //                }

        //                Religion rel = _oReligions.Find(x => x.Name == item.Religion);
        //                if (rel != null)
        //                    oEmp.ReligionID = rel.ID;

        //                if (item.Gender == "M")
        //                    oEmp.Gender = EnumGender.Male;
        //                else if (item.Gender == "F")
        //                    oEmp.Gender = EnumGender.Female;
        //                if (item.TIN != "" && oEmp.TinNo == "")
        //                    oEmp.TinNo = item.TIN;
        //                if (item.IsForeignExpatriate.ToUpper() == "FALSE")
        //                    oEmp.ForeignExPat = false;
        //                else
        //                    oEmp.ForeignExPat = true;

        //                //Set Department
        //                Department oDept = null;
        //                if (!string.IsNullOrEmpty(item.SubUnit))
        //                {
        //                    oDept = _oDepartments.Find(x => x.Name == item.SubUnit);
        //                }
        //                else if (!string.IsNullOrEmpty(item.Unit))
        //                {
        //                    oDept = _oDepartments.Find(x => x.Name == item.Unit);
        //                }
        //                else if (!string.IsNullOrEmpty(item.SubSection))
        //                {
        //                    oDept = _oDepartments.Find(x => x.Name == item.SubSection);
        //                }
        //                else if (!string.IsNullOrEmpty(item.Section))
        //                {
        //                    oDept = _oDepartments.Find(x => x.Name == item.Section);
        //                }
        //                else if (!string.IsNullOrEmpty(item.Department))
        //                {
        //                    oDept = _oDepartments.Find(x => x.Name == item.Department);
        //                }

        //                if (oDept != null && oEmp.DepartmentID != oDept.ID)
        //                {
        //                    oEmp.DepartmentID = oDept.ID;
        //                    oEmp.EmpLifeCycle.DepartmentID = oDept.ID;
        //                    oEmp.EmpLifeCycle.EffectDate = Convert.ToDateTime(item.AssignmentChangeDate);
        //                }


        //                //Set Location
        //                Location oLoc = null;
        //                if (!string.IsNullOrEmpty(item.Location))
        //                {
        //                    oLoc = _oLocations.Find(x => x.Name == item.Location);
        //                    if (oLoc != null && oLoc.ParentID == null)
        //                    {
        //                        AddStatus(nCount, oEmp.EmployeeNo, "Employee Cannot be posted in Zone.", EnumSAPProcessStatus.Error);
        //                    }

        //                    if (oLoc != null && oEmp.LocationID != oLoc.ID)
        //                    {
        //                        oEmp.LocationID = oLoc.ID;
        //                        oEmp.EmpLifeCycle.LocationID = oLoc.ID;
        //                        oEmp.EmpLifeCycle.EffectDate = Convert.ToDateTime(item.AssignmentChangeDate);
        //                    }
        //                }
        //                //else if (!string.IsNullOrEmpty(item.Unit))
        //                //{
        //                //    oDept = _oDepartments.Find(x => x.Name == item.Unit);
        //                //}

        //                if (item.EmailAddress != "" && oEmp.EmailAddress == "")
        //                    oEmp.EmailAddress = item.EmailAddress;
        //                if (item.MobileNo != "" && oEmp.MobileNo == "")
        //                    oEmp.MobileNo = item.MobileNo;

        //                oEmp.EmpLifeCycle.Description = item.SALARY_CHANGE_TYPE;
        //                //Promotion
        //                EmployeeGradeSalary empgrd = new EmployeeGradeSalary();

        //                if (oEmp != null)
        //                {
        //                    oEmp.EmpLifeCycle.EmployeeGradeSalary = new EmployeeGradeSalary();
        //                    empgrd = new EmployeeGradeSalary();
        //                    oEmp.EmpLifeCycle.EmployeeGradeSalary = new EmployeeGradeSalary();
        //                    empgrd.GradeID = grd.ID;
        //                    empgrd.BasicSalary = Convert.ToDouble(item.BasicSalary);
        //                    oEmp.GradeID = grd.ID;
        //                    oEmp.BasicSalary = Convert.ToDouble(item.BasicSalary);
        //                    empgrd.EffectDate = Convert.ToDateTime(item.BasicSalaryEffectDate);
        //                    empgrd.GradeSalaryTypeID = GetGradeChangeType2(item.SALARY_CHANGE_TYPE);
        //                    oEmp.EmpLifeCycle.Description = item.SALARY_CHANGE_TYPE;
        //                    oEmp.EmpLifeCycle.StatusDetailID = GetGradeChangeType(item.SALARY_CHANGE_TYPE);
        //                    oEmp.EmpLifeCycle.GradeID = grd.ID;
        //                    oEmp.EmpLifeCycle.EffectDate = empgrd.EffectDate;
        //                    oEmp.EmpLifeCycle.BasicSalary = empgrd.BasicSalary;
        //                    oEmp.EmpLifeCycle.EmployeeGradeSalary = empgrd;
        //                }
        //                if (oEmp.GradeID != grd.ID || oEmp.BasicSalary != Convert.ToDouble(item.BasicSalary))
        //                {
        //                    oEmp.EmpLifeCycle.EmployeeGradeSalary = new EmployeeGradeSalary();
        //                    empgrd = new EmployeeGradeSalary();
        //                    if (empgrd.GradeID != grd.ID && empgrd.BasicSalary != Convert.ToDouble(item.BasicSalary))
        //                    {
        //                        oEmp.EmpLifeCycle.EmployeeGradeSalary = new EmployeeGradeSalary();
        //                        empgrd.GradeID = grd.ID;
        //                        empgrd.BasicSalary = Convert.ToDouble(item.BasicSalary);
        //                        empgrd.EffectDate = Convert.ToDateTime(item.BasicSalaryEffectDate);
        //                        empgrd.GradeSalaryTypeID = GetGradeChangeType2(item.SALARY_CHANGE_TYPE);
        //                        oEmp.EmpLifeCycle.Description = item.SALARY_CHANGE_TYPE;
        //                        oEmp.EmpLifeCycle.StatusDetailID = GetGradeChangeType(item.SALARY_CHANGE_TYPE);
        //                        oEmp.EmpLifeCycle.GradeID = grd.ID;
        //                        oEmp.EmpLifeCycle.EffectDate = empgrd.EffectDate;
        //                        oEmp.EmpLifeCycle.BasicSalary = empgrd.BasicSalary;
        //                        oEmp.EmpLifeCycle.EmployeeGradeSalary = empgrd;
        //                        oEmp.GradeID = grd.ID;
        //                        oEmp.BasicSalary = Convert.ToDouble(item.BasicSalary);
        //                    }
        //                    else if (emp.GradeID != grd.ID && emp.BasicSalary == Convert.ToDouble(item.BasicSalary))
        //                    {
        //                        oEmp.EmpLifeCycle.EmployeeGradeSalary = new EmployeeGradeSalary();
        //                        empgrd.GradeID = grd.ID;
        //                        empgrd.EffectDate = Convert.ToDateTime(item.AssignmentChangeDate);
        //                        empgrd.GradeSalaryTypeID = GetGradeChangeType2(item.SALARY_CHANGE_TYPE);
        //                        oEmp.EmpLifeCycle.Description = item.SALARY_CHANGE_TYPE;
        //                        oEmp.EmpLifeCycle.StatusDetailID = GetGradeChangeType(item.SALARY_CHANGE_TYPE);
        //                        oEmp.EmpLifeCycle.GradeID = grd.ID;
        //                        oEmp.EmpLifeCycle.EffectDate = empgrd.EffectDate;
        //                        oEmp.EmpLifeCycle.EmployeeGradeSalary = empgrd;
        //                        oEmp.GradeID = grd.ID;
        //                    }
        //                    else if (emp.GradeID == grd.ID && empgrd.BasicSalary != emp.BasicSalary)
        //                    {
        //                        oEmp.EmpLifeCycle.EmployeeGradeSalary = new EmployeeGradeSalary();
        //                        empgrd.BasicSalary = Convert.ToDouble(item.BasicSalary);
        //                        empgrd.EffectDate = Convert.ToDateTime(item.BasicSalaryEffectDate);
        //                        empgrd.GradeSalaryTypeID = GetGradeChangeType2(item.SALARY_CHANGE_TYPE);
        //                        oEmp.EmpLifeCycle.Description = item.SALARY_CHANGE_TYPE;
        //                        oEmp.EmpLifeCycle.StatusDetailID = GetGradeChangeType(item.SALARY_CHANGE_TYPE);
        //                        oEmp.EmpLifeCycle.EffectDate = empgrd.EffectDate;
        //                        oEmp.EmpLifeCycle.BasicSalary = empgrd.BasicSalary;
        //                        oEmp.EmpLifeCycle.EmployeeGradeSalary = empgrd;

        //                        oEmp.BasicSalary = Convert.ToDouble(item.BasicSalary);
        //                    }
        //                }

        //                //Bank Account History

        //                //if (item.SalaryBankCode != ""||item.SalaryBranchCode != "" || item.SalaryAccountNumber != "")
        //                if (item.SalaryAccountNumber != "")
        //                {
        //                    oEmp.EmployeeBankAccount = new EmployeeBankAccount();
        //                    if (oEmp.AccountNo != item.SalaryAccountNumber)
        //                    {
        //                        if (item.SalaryBranch != "")
        //                        {
        //                            Branch oBranch = _oBranchs.Find(x => x.Name == item.SalaryBranch);
        //                            if (oBranch == null)
        //                            {
        //                                AddStatus(nCount, oEmp.EmployeeNo, "Salary branch not found", EnumSAPProcessStatus.Error);
        //                            }
        //                            else
        //                            {
        //                                oEmp.EmployeeBankAccount.BranchID = oBranch.ID;
        //                                if (oEmp.BranchID != oEmp.EmployeeBankAccount.BranchID)
        //                                    oEmp.BranchID = oEmp.EmployeeBankAccount.BranchID;
        //                            }
        //                        }
        //                        if (item.SalaryAccountNumber == "")
        //                            AddStatus(nCount, oEmp.EmployeeNo, "Salary account not found", EnumSAPProcessStatus.Error);
        //                        else
        //                        {
        //                            oEmp.EmployeeBankAccount.AccountNo = item.SalaryAccountNumber;
        //                            oEmp.AccountNo = item.SalaryAccountNumber;
        //                        }

        //                        if (item.SALARY_ACCOUNT_EFFECT_DATE != null)
        //                        {
        //                            oEmp.EmployeeBankAccount.EffectDate = Convert.ToDateTime(item.SALARY_ACCOUNT_EFFECT_DATE);
        //                        }
        //                        else
        //                            AddStatus(nCount, oEmp.EmployeeNo, "Salary account effect date not found", EnumSAPProcessStatus.Error);

        //                        oEmp.EmployeeBankAccount.AccountType = EnumBankAccountType.SalaryAccount;
        //                    }
        //                }



        //                if (oEmp.EmpLifeCycle.EffectDate == DateTime.MinValue)
        //                    oEmp.EmpLifeCycle.EffectDate = DateTime.Today;

        //                _oEmployeeCollection.Add(oEmp);
        //                nCount++;
        //            }
        //        }
        //        catch (Exception exp)
        //        {
        //            throw new Exception(exp.Message);
        //        }
        //        if (_oErrorList.Count > 0)
        //        {
        //            List<SuccessorErrorList> list = _oErrorList.FindAll(x => x.Status == EnumSAPProcessStatus.Error);
        //            if (list != null && list.Count > 0)
        //            {
        //                BulkSave(list);
        //                var response = new
        //                {
        //                    Message = "Please see error list.Failed to validate",
        //                    Errors = _oErrorList
        //                };

        //                new Exception(response.ToString());
        //            }
        //            else
        //            {
        //                Save();
        //            }
        //        }
        //        else
        //        {
        //            Save();

        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        #region Handle Exception

        //        //if (tc != null)
        //        //    tc.HandleError();
        //        ExceptionLog.Write(e);
        //        throw new ServiceException(e.Message, e);

        //        #endregion
        //    }
        //}


        //private void CheckFieldValidation()
        //{
        //    _oErrorList = new List<SuccessorErrorList>();
        //    SuccessorErrorList oItem = new SuccessorErrorList();
        //    int nCount = 1;
        //    List<Branch> branches = new BranchService().Get(EnumStatus.Regardless, 1);
        //    List<Bank> banks = new BankService().Get();
        //    foreach (DataIntegration item in _oHRDataUploads)
        //    {
        //        if (string.IsNullOrEmpty(item.EmployeeNo))
        //            AddStatus(nCount, item.EmployeeNo, "EmployeeNo is not found", EnumSAPProcessStatus.Error);
        //        else
        //        {
        //            if (item.EmployeeNo.Length > 6)
        //                AddStatus(nCount, item.EmployeeNo, "EmployeeNo exceeds 6-digits", EnumSAPProcessStatus.Error);
        //        }

        //        if (string.IsNullOrEmpty(item.EmployeeName))
        //            AddStatus(nCount, item.EmployeeNo, "EmployeeName is not found", EnumSAPProcessStatus.Error);
        //        else
        //        {
        //            if (item.EmployeeName.Length > 150)
        //                AddStatus(nCount, item.EmployeeNo, "EmployeeName exceeds 150-digits", EnumSAPProcessStatus.Error);
        //        }

        //        if (!string.IsNullOrEmpty(item.FathersName))
        //        {
        //            if (item.FathersName.Length > 150)
        //                AddStatus(nCount, item.EmployeeNo, "FathersName exceeds 150-digits", EnumSAPProcessStatus.Error);
        //        }

        //        if (string.IsNullOrEmpty(item.Designation))
        //            AddStatus(nCount, item.EmployeeNo, "Designation is not found", EnumSAPProcessStatus.Error);
        //        else
        //        {
        //            if (item.Designation.Length > 200)
        //                AddStatus(nCount, item.EmployeeNo, "Designation exceeds 200-digits", EnumSAPProcessStatus.Error);
        //        }

        //        if (item.GlobalID.Length > 20)
        //            AddStatus(nCount, item.EmployeeNo, "Global ID's length is greater then 20 characters.", EnumSAPProcessStatus.Error);

        //        if (!string.IsNullOrEmpty(item.PreviousEmployeeNo))
        //        {
        //            if (item.PreviousEmployeeNo.Length > 6)
        //                AddStatus(nCount, item.EmployeeNo, "PreviousEmployeeNo is not in 6-digits", EnumSAPProcessStatus.Error);
        //        }

        //        if (item.ContractChangeEndDate != null && Convert.ToDateTime(item.ContractChangeEndDate) == DateTime.MinValue)
        //            AddStatus(nCount, item.EmployeeNo, "ContractChangeEndDate is not valid date.", EnumSAPProcessStatus.Error);

        //        if (item.DateOfBirth == null)
        //            AddStatus(nCount, item.EmployeeNo, "DateOfBirth is not found", EnumSAPProcessStatus.Error);
        //        if (Convert.ToDateTime(item.DateOfBirth) == DateTime.MinValue)
        //            AddStatus(nCount, item.EmployeeNo, "DateOfBirth is not valid date.", EnumSAPProcessStatus.Error);

        //        if (item.DateOfJoining != null)
        //        { //AddStatus(nCount, item.EmployeeNo, "DateOfJoining is not found", EnumSAPProcessStatus.Error);
        //            if (Convert.ToDateTime(item.DateOfJoining) == DateTime.MinValue)
        //                AddStatus(nCount, item.EmployeeNo, "DateOfJoining is not valid date.", EnumSAPProcessStatus.Error);
        //        }

        //        if (string.IsNullOrEmpty(item.EmailAddress))
        //        {
        //            AddStatus(nCount, item.EmployeeNo, "Email Address is Missing.", EnumSAPProcessStatus.Error);
        //        }
        //        if (string.IsNullOrEmpty(item.Category))
        //        {
        //            AddStatus(nCount, item.EmployeeNo, "Category is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        else
        //        {
        //            Category oObj = _oCategories.Find(x => x.Name == item.Category);
        //            if (oObj == null)
        //                AddStatus(nCount, item.EmployeeNo, "Category is not valid.", EnumSAPProcessStatus.Error);
        //        }
        //        if (string.IsNullOrEmpty(item.Religion))
        //        {
        //            AddStatus(nCount, item.EmployeeNo, "Religion is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        else
        //        {
        //            Religion oObj = _oReligions.Find(x => x.Name == item.Religion);
        //            if (oObj == null)
        //                AddStatus(nCount, item.EmployeeNo, "Religion is not valid.", EnumSAPProcessStatus.Error);
        //        }
        //        if (string.IsNullOrEmpty(item.Gender))
        //            AddStatus(nCount, item.EmployeeNo, "Gender is not found.", EnumSAPProcessStatus.Error);
        //        else
        //        {
        //            if (item.Gender == "M" || item.Gender == "F") { }
        //            else
        //                AddStatus(nCount, item.EmployeeNo, "Gender is not valid. It should be M or F", EnumSAPProcessStatus.Error);

        //        }
        //        if (item.TIN.Length > 50)
        //            AddStatus(nCount, item.EmployeeNo, "TIN exceeds 50 character.", EnumSAPProcessStatus.Error);

        //        if (string.IsNullOrEmpty(item.IsForeignExpatriate))
        //            item.IsForeignExpatriate = "FALSE";
        //        else
        //        {
        //            if (item.IsForeignExpatriate.ToUpper() == "TRUE" || item.IsForeignExpatriate.ToUpper() == "FALSE") { }
        //            else
        //                AddStatus(nCount, item.EmployeeNo, "IsForeignExpatriate is not valid.", EnumSAPProcessStatus.Error);
        //        }
        //        if (string.IsNullOrEmpty(item.Grade))
        //        {
        //            AddStatus(nCount, item.EmployeeNo, "Grade is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        else
        //        {
        //            Grade oObj = _oGrades.Find(x => x.Name == item.Grade);
        //            if (oObj == null)
        //                AddStatus(nCount, item.EmployeeNo, "Grade is not valid.", EnumSAPProcessStatus.Error);
        //        }
        //        if (Convert.ToDouble(item.BasicSalary) <= 0)
        //            AddStatus(nCount, item.EmployeeNo, "Basic salary should greater than 0.", EnumSAPProcessStatus.Error);

        //        if (item.BasicSalaryEffectDate == null)
        //            AddStatus(nCount, item.EmployeeNo, "BasicSalaryEffectDate is not found", EnumSAPProcessStatus.Error);
        //        if (Convert.ToDateTime(item.BasicSalaryEffectDate) == DateTime.MinValue)
        //            AddStatus(nCount, item.EmployeeNo, "BasicSalaryEffectDate is not valid date.", EnumSAPProcessStatus.Error);


        //        if (string.IsNullOrEmpty(item.SALARY_CHANGE_TYPE))
        //        {
        //            AddStatus(nCount, item.EmployeeNo, "Salary Change Type is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        else
        //        {
        //            if (item.SALARY_CHANGE_TYPE != "Joining" && item.SALARY_CHANGE_TYPE != "Promotion"
        //             && item.SALARY_CHANGE_TYPE != "Confirmation" && item.SALARY_CHANGE_TYPE != "Annual Increment"
        //             && item.SALARY_CHANGE_TYPE != "Salary Revised" && item.SALARY_CHANGE_TYPE != "Other")
        //                AddStatus(nCount, item.EmployeeNo, "Salary Change Type is not recognized.It must be like (Joining,Promotion,Confirmation,Annual Increment,Salary Revised,Other)", EnumSAPProcessStatus.Error);
        //        }


        //        if (!string.IsNullOrEmpty(item.SubUnit))
        //        {
        //            if (!string.IsNullOrEmpty(item.Unit))
        //            {
        //                if (!string.IsNullOrEmpty(item.SubSection))
        //                {
        //                    if (!string.IsNullOrEmpty(item.Section))
        //                    {
        //                        if (!string.IsNullOrEmpty(item.Department))
        //                        {
        //                            if (!string.IsNullOrEmpty(item.Division))
        //                            {

        //                            }
        //                            else
        //                                AddStatus(nCount, item.EmployeeNo, "Division is not found.", EnumSAPProcessStatus.Error);
        //                        }
        //                        else
        //                            AddStatus(nCount, item.EmployeeNo, "Department is not found.", EnumSAPProcessStatus.Error);
        //                    }
        //                    else
        //                        AddStatus(nCount, item.EmployeeNo, "Section is not found.", EnumSAPProcessStatus.Error);
        //                }
        //                else
        //                    AddStatus(nCount, item.EmployeeNo, "Sub Section is not found.", EnumSAPProcessStatus.Error);
        //            }
        //            else
        //                AddStatus(nCount, item.EmployeeNo, "Unit is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        else if (!string.IsNullOrEmpty(item.Unit))
        //        {
        //            if (!string.IsNullOrEmpty(item.SubSection))
        //            {
        //                if (!string.IsNullOrEmpty(item.Section))
        //                {
        //                    if (!string.IsNullOrEmpty(item.Department))
        //                    {
        //                        if (!string.IsNullOrEmpty(item.Division))
        //                        {

        //                        }
        //                        else
        //                            AddStatus(nCount, item.EmployeeNo, "Division is not found.", EnumSAPProcessStatus.Error);
        //                    }
        //                    else
        //                        AddStatus(nCount, item.EmployeeNo, "Department is not found.", EnumSAPProcessStatus.Error);
        //                }
        //                else
        //                    AddStatus(nCount, item.EmployeeNo, "Section is not found.", EnumSAPProcessStatus.Error);
        //            }
        //            else
        //                AddStatus(nCount, item.EmployeeNo, "Sub Section is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        else if (!string.IsNullOrEmpty(item.SubSection))
        //        {
        //            if (!string.IsNullOrEmpty(item.Section))
        //            {
        //                if (!string.IsNullOrEmpty(item.Department))
        //                {
        //                    if (!string.IsNullOrEmpty(item.Division))
        //                    {

        //                    }
        //                    else
        //                        AddStatus(nCount, item.EmployeeNo, "Division is not found.", EnumSAPProcessStatus.Error);
        //                }
        //                else
        //                    AddStatus(nCount, item.EmployeeNo, "Department is not found.", EnumSAPProcessStatus.Error);
        //            }
        //            else
        //                AddStatus(nCount, item.EmployeeNo, "Section is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        else if (!string.IsNullOrEmpty(item.Section))
        //        {
        //            if (!string.IsNullOrEmpty(item.Department))
        //            {
        //                if (!string.IsNullOrEmpty(item.Division))
        //                {

        //                }
        //                else
        //                    AddStatus(nCount, item.EmployeeNo, "Division is not found.", EnumSAPProcessStatus.Error);
        //            }
        //            else
        //                AddStatus(nCount, item.EmployeeNo, "Department is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        else if (!string.IsNullOrEmpty(item.Department))
        //        {
        //            if (!string.IsNullOrEmpty(item.Division))
        //            {

        //            }
        //            else
        //                AddStatus(nCount, item.EmployeeNo, "Division is not found.", EnumSAPProcessStatus.Error);
        //        }


        //        if (string.IsNullOrEmpty(item.Division))
        //            AddStatus(nCount, item.EmployeeNo, "Division Name is not found.", EnumSAPProcessStatus.Error);
        //        else
        //        {
        //            if (item.Division.Length > 100)
        //                AddStatus(nCount, item.EmployeeNo, "Division Name is greater then 100 characters.", EnumSAPProcessStatus.Error);
        //            if (item.Division.Length == 0)
        //                AddStatus(nCount, item.EmployeeNo, "Empty Division is not allowed.", EnumSAPProcessStatus.Error);
        //        }
        //        if (!string.IsNullOrEmpty(item.Department))
        //        {
        //            //    AddStatus(nCount, item.EmployeeNo, "Department Name is not found.", EnumSAPProcessStatus.Error);
        //            //else
        //            //{
        //            if (item.Department.Length > 100)
        //                AddStatus(nCount, item.EmployeeNo, "Department Name is greater then 100 characters.", EnumSAPProcessStatus.Error);
        //            if (item.Department.Length == 0)
        //                AddStatus(nCount, item.EmployeeNo, "Empty Department is not allowed.", EnumSAPProcessStatus.Error);
        //        }
        //        if (!string.IsNullOrEmpty(item.Section))
        //        //    AddStatus(nCount, item.EmployeeNo, "Section Name is not found.", EnumSAPProcessStatus.Error);
        //        //else
        //        {
        //            if (item.Section.Length > 100)
        //                AddStatus(nCount, item.EmployeeNo, "Section Name is greater then 100 characters.", EnumSAPProcessStatus.Error);
        //            if (item.Section.Length == 0)
        //                AddStatus(nCount, item.EmployeeNo, "Empty Section is not allowed.", EnumSAPProcessStatus.Error);
        //        }
        //        if (!string.IsNullOrEmpty(item.SubSection))
        //        //    AddStatus(nCount, item.EmployeeNo, "SubSection Name is not found.", EnumSAPProcessStatus.Error);
        //        //else
        //        {
        //            if (item.SubSection.Length > 100)
        //                AddStatus(nCount, item.EmployeeNo, "SubSection Name is greater then 100 characters.", EnumSAPProcessStatus.Error);
        //            if (item.SubSection.Length == 0)
        //                AddStatus(nCount, item.EmployeeNo, "Empty SubSection is not allowed.", EnumSAPProcessStatus.Error);
        //        }
        //        if (!string.IsNullOrEmpty(item.Unit))
        //        //    AddStatus(nCount, item.EmployeeNo, "Unit Name is not found.", EnumSAPProcessStatus.Error);
        //        //else
        //        {
        //            if (item.Unit.Length > 100)
        //                AddStatus(nCount, item.EmployeeNo, "Unit Name is greater then 100 characters.", EnumSAPProcessStatus.Error);
        //            if (item.Unit.Length == 0)
        //                AddStatus(nCount, item.EmployeeNo, "Empty Unit is not allowed.", EnumSAPProcessStatus.Error);
        //        }
        //        if (!string.IsNullOrEmpty(item.SubUnit))
        //        //    AddStatus(nCount, item.EmployeeNo, "SubUnit Name is not found.", EnumSAPProcessStatus.Error);
        //        //else
        //        {
        //            if (item.SubUnit.Length > 100)
        //                AddStatus(nCount, item.EmployeeNo, "SubUnit Name is greater then 100 characters.", EnumSAPProcessStatus.Error);
        //            if (item.SubUnit.Length == 0)
        //                AddStatus(nCount, item.EmployeeNo, "Empty SubUnit is not allowed.", EnumSAPProcessStatus.Error);
        //        }
        //        if (string.IsNullOrEmpty(item.Zone))
        //            AddStatus(nCount, item.EmployeeNo, "Zone Name is not found.", EnumSAPProcessStatus.Error);
        //        else
        //        {
        //            if (item.Zone.Length > 100)
        //                AddStatus(nCount, item.EmployeeNo, "Zone Name is greater then 100 characters.", EnumSAPProcessStatus.Error);
        //            if (item.Zone.Length == 0)
        //                AddStatus(nCount, item.EmployeeNo, "Empty Zone is not allowed.", EnumSAPProcessStatus.Error);
        //        }
        //        if (string.IsNullOrEmpty(item.Location))
        //            AddStatus(nCount, item.EmployeeNo, "Location Name is not found.", EnumSAPProcessStatus.Error);
        //        else
        //        {
        //            if (item.Location.Length > 100)
        //                AddStatus(nCount, item.EmployeeNo, "Location Name is greater then 100 characters.", EnumSAPProcessStatus.Error);
        //            if (item.Location.Length == 0)
        //                AddStatus(nCount, item.EmployeeNo, "Empty Location is not allowed.", EnumSAPProcessStatus.Error);
        //        }
        //        try
        //        {
        //            Convert.ToDateTime(item.AssignmentChangeDate);
        //        }
        //        catch
        //        {
        //            AddStatus(nCount, item.EmployeeNo, "Assignment Change Date is not found.", EnumSAPProcessStatus.Error);
        //        }
        //        if (item.SalaryAccountNumber != "")
        //        {
        //            if (item.SalaryBank == "" || item.SalaryBranch == "")
        //            {
        //                AddStatus(nCount, item.EmployeeNo, "Bank or branch cannot empty", EnumSAPProcessStatus.Error);
        //            }
        //            else
        //            {
        //                Branch oBranch = branches.Where(x => x.Name.Trim() == item.SalaryBranch.Trim()).FirstOrDefault();
        //                if (oBranch != null)
        //                {
        //                    if (oBranch.Code.Trim() == item.SalaryBranchCode.Trim())
        //                    {
        //                        Bank oBank = banks.Where(x => x.ID == oBranch.BankID).FirstOrDefault();
        //                        if (oBank != null)
        //                        {
        //                            if (item.SalaryBank.Trim() != oBank.Name.Trim())
        //                            {
        //                                AddStatus(nCount, item.EmployeeNo, "Bank name doesn't match for the branch \'" + item.SalaryBranch + "\'", EnumSAPProcessStatus.Error);
        //                            }
        //                        }
        //                        else
        //                        {
        //                            AddStatus(nCount, item.EmployeeNo, "Bank is not found for the branch \'" + item.SalaryBranch + "\'", EnumSAPProcessStatus.Error);
        //                        }
        //                    }
        //                    else
        //                    {
        //                        AddStatus(nCount, item.EmployeeNo, "Salary Branch Code doesn't match with the Salary Branch.", EnumSAPProcessStatus.Error);
        //                    }
        //                }
        //                else
        //                {
        //                    AddStatus(nCount, item.EmployeeNo, "Salary Branch Name doesn't match with the system branch name.", EnumSAPProcessStatus.Error);
        //                }
        //            }
        //        }

        //        nCount++;
        //    }

        //}

        private void AddStatus(int nCount, string sEmployeeNo, string sMessege, EnumSAPProcessStatus eStstus, EnumDataIntegrationType type)
        {
            SuccessorErrorList item = new SuccessorErrorList();
            item.RowNo = nCount;
            item.EmployeeNo = sEmployeeNo;
            item.Message = sMessege;
            item.Status = eStstus;
            item.UploadDate = DateTime.Now;
            item.Type = type;
            _oSuccessOrErrorList.Add(item);
        }


        #endregion
        public string SaveBulkRequest(List<DataIntegration> datas)
        {
            TransactionContext tc = null;
            var builder = new StringBuilder();
            string getYear = DateTime.Now.Year.ToString("00");
            string getMonth = DateTime.Now.Month.ToString("00");
            string getDate = DateTime.Now.Day.ToString("00");
            string getHour = DateTime.Now.Hour.ToString("00");
            string getMin = DateTime.Now.Minute.ToString("00"); //last two digit
            string getSec = DateTime.Now.Second.ToString("00");
            string batchId = builder.Append(getYear).Append(getMonth).Append(getDate).Append("-").Append(getHour).Append(getMin).Append(getSec).ToString();
            try
            {
                DataTable processTable = new DataTable("DataIntegrationRequest");
                processTable.Columns.Add(new DataColumn("BatchID", typeof(string)));
                processTable.Columns.Add(new DataColumn("UploadDate", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeNo", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeName", typeof(string)));
                processTable.Columns.Add(new DataColumn("DiscontinueDateRegion", typeof(string)));
                processTable.Columns.Add(new DataColumn("DesignationCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("DesignationName", typeof(string)));
                processTable.Columns.Add(new DataColumn("DateOfBirth", typeof(string)));
                processTable.Columns.Add(new DataColumn("DateOfJoining", typeof(string)));
                processTable.Columns.Add(new DataColumn("ConfirmationDate", typeof(string)));
                processTable.Columns.Add(new DataColumn("CategoryCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("CategoryName", typeof(string)));
                processTable.Columns.Add(new DataColumn("ReligionCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("ReligionName", typeof(string)));
                processTable.Columns.Add(new DataColumn("MaritalStatus", typeof(string)));
                processTable.Columns.Add(new DataColumn("Gender", typeof(string)));
                processTable.Columns.Add(new DataColumn("TIN", typeof(string)));
                processTable.Columns.Add(new DataColumn("GradeCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("GradeName", typeof(string)));
                processTable.Columns.Add(new DataColumn("PayScaleLevelCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("PayScaleLevel", typeof(string)));
                processTable.Columns.Add(new DataColumn("IsForeignExpatriate", typeof(string)));
                processTable.Columns.Add(new DataColumn("IsPFMember", typeof(string)));
                processTable.Columns.Add(new DataColumn("BusinessUnitCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("BusinessUnitName", typeof(string)));
                processTable.Columns.Add(new DataColumn("DivisionCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("DivisionName", typeof(string)));
                processTable.Columns.Add(new DataColumn("DepartmentCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("DepartmentName", typeof(string)));
                processTable.Columns.Add(new DataColumn("SubDepartmentCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("SubDepartmentName", typeof(string)));
                processTable.Columns.Add(new DataColumn("ZoneCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("ZoneName", typeof(string)));
                processTable.Columns.Add(new DataColumn("RegionCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("RegionName", typeof(string)));
                processTable.Columns.Add(new DataColumn("CostCenterCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("CostCenterName", typeof(string)));
                processTable.Columns.Add(new DataColumn("LifeCycleEffectDate", typeof(string)));
                processTable.Columns.Add(new DataColumn("LifeCycleEvent", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeBankCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeBankName", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeBranchCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeBranchName", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeAccountNumber", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeAccountEffectDate", typeof(string)));
                processTable.Columns.Add(new DataColumn("BasicSalary", typeof(string)));
                processTable.Columns.Add(new DataColumn("GrossSalary", typeof(string)));
                processTable.Columns.Add(new DataColumn("payrolltypeid", typeof(int)));

                tc = TransactionContext.Begin();
                int id = tc.GenerateID("DataIntegrationRequest", "DataIntegrationRequestID");
                foreach (DataIntegration oItem in datas)
                {
                    oItem.BatchID = batchId;
                    processTable.Rows.Add(oItem.BatchID, oItem.UploadDate, oItem.EmployeeNo, oItem.EmployeeName, oItem.DiscontinueDateRegion, oItem.DesignationCode,
                    oItem.Designation, oItem.DateOfBirth, oItem.DateOfJoining, oItem.ConfirmationDate, oItem.CategoryCode, oItem.Category, oItem.ReligionCode, oItem.Religion, oItem.MaritalStatus, oItem.Gender, oItem.TIN, oItem.GradeCode, oItem.Grade, oItem.PayScaleLevelCode, oItem.PayScaleLevel, oItem.IsForeignExpatriate, oItem.PFMembership, oItem.BusinessUnitCode, oItem.BusinessUnitName, oItem.DivisionCode,
                    oItem.Division, oItem.DepartmentCode, oItem.Department, oItem.SubDepartmentCode, oItem.SubDepartment, oItem.ZoneCode, oItem.Zone, oItem.RegionCode, oItem.RegionName, oItem.CostCenterCode, oItem.CostCenterName, oItem.AssignmentChangeDate, oItem.LIFE_CYCLE_EVENT, oItem.SalaryBankCode, oItem.SalaryBank, oItem.SalaryBranchCode, oItem.SalaryBranch, oItem.SalaryAccountNumber, oItem.SALARY_ACCOUNT_EFFECT_DATE, oItem.BasicSalary,
                    oItem.GrossSalary,oItem.payrolltypeid);
                }
                using (SqlBulkCopy sqlBulk = new SqlBulkCopy((SqlConnection)tc.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)tc.Transaction))
                {
                    sqlBulk.BulkCopyTimeout = 6000; // in seconds

                    var mapping = new SqlBulkCopyColumnMapping("BatchID", "BatchID");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("UploadDate", "UploadDate");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("EmployeeNo", "EmployeeNo");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("EmployeeName", "EmployeeName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DiscontinueDateRegion", "DiscontinueDateRegion");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DesignationCode", "DesignationCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DesignationName", "DesignationName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DateOfBirth", "DateOfBirth");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DateOfJoining", "DateOfJoining");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("ConfirmationDate", "ConfirmationDate");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("CategoryCode", "CategoryCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("CategoryName", "CategoryName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("ReligionCode", "ReligionCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("ReligionName", "ReligionName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("MaritalStatus", "MaritalStatus");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("Gender", "Gender");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("TIN", "TIN");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("GradeCode", "GradeCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("GradeName", "GradeName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("PayScaleLevelCode", "PayScaleLevelCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("PayScaleLevel", "PayScaleLevel");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("IsForeignExpatriate", "IsForeignExpatriate");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("IsPFMember", "IsPFMember");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("BusinessUnitCode", "BusinessUnitCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("BusinessUnitName", "BusinessUnitName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DivisionCode", "DivisionCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DivisionName", "DivisionName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DepartmentCode", "DepartmentCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("DepartmentName", "DepartmentName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("SubDepartmentCode", "SubDepartmentCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("SubDepartmentName", "SubDepartmentName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("ZoneCode", "ZoneCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("ZoneName", "ZoneName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("RegionCode", "RegionCode");
                    sqlBulk.ColumnMappings.Add(mapping);
                    mapping = new SqlBulkCopyColumnMapping("RegionName", "RegionName");
                    sqlBulk.ColumnMappings.Add(mapping);
                    mapping = new SqlBulkCopyColumnMapping("CostCenterCode", "CostCenterCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("CostCenterName", "CostCenterName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("LifeCycleEffectDate", "LifeCycleEffectDate");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("LifeCycleEvent", "LifeCycleEvent");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("EmployeeBankCode", "EmployeeBankCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("EmployeeBankName", "EmployeeBankName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("EmployeeBranchCode", "EmployeeBranchCode");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("EmployeeBranchName", "EmployeeBranchName");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("EmployeeAccountNumber", "EmployeeAccountNumber");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("EmployeeAccountEffectDate", "EmployeeAccountEffectDate");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("BasicSalary", "BasicSalary");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("GrossSalary", "GrossSalary");
                    sqlBulk.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("payrolltypeid", "payrolltypeid");
                    sqlBulk.ColumnMappings.Add(mapping);


                    sqlBulk.DestinationTableName = "DataIntegrationRequest";
                    sqlBulk.WriteToServer(processTable);
                }

                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }

            return batchId;
        }

        public void BulkSave(List<SuccessorErrorList> items)
        {
            try
            {
                TransactionContext tc = null;
                tc = TransactionContext.Begin();
                DataTable processTable = new DataTable("SuccessorErrorList");
                processTable.Columns.Add(new DataColumn("RowNo", typeof(Int32)));
                processTable.Columns.Add(new DataColumn("EmployeeNo", typeof(string)));
                processTable.Columns.Add(new DataColumn("Message", typeof(string)));
                processTable.Columns.Add(new DataColumn("Status", typeof(string)));
                processTable.Columns.Add(new DataColumn("UploadDate", typeof(DateTime)));
                processTable.Columns.Add(new DataColumn("Type", typeof(Int32)));
                processTable.Columns.Add(new DataColumn("BatchId", typeof(string)));

                foreach (SuccessorErrorList item in items)
                {
                    processTable.Rows.Add(item.RowNo, item.EmployeeNo, item.Message, item.Status.ToString(), DateTime.Now, item.Type, item.BatchId);
                }

                using (SqlBulkCopy bulkCopy = new SqlBulkCopy((SqlConnection)tc.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)tc.Transaction))
                {
                    bulkCopy.BulkCopyTimeout = 6000; // in seconds
                    bulkCopy.DestinationTableName = "SuccessorErrorList";
                    bulkCopy.WriteToServer(processTable);
                }
                tc.End();

            }
            catch (Exception e)
            {
                throw new ServiceException(e.Message, e);
            }
        }

        public string BulkSaveIndividualAllowance(List<DataIntergrationIndividualAllowance> items)
        {
            string batchId = "";
            try
            {
                var builder = new StringBuilder();
                string getYear = DateTime.Now.Year.ToString("00");
                string getMonth = DateTime.Now.Month.ToString("00");
                string getDate = DateTime.Now.Day.ToString("00");
                string getHour = DateTime.Now.Hour.ToString("00");
                string getMin = DateTime.Now.Minute.ToString("00"); //last two digit
                string getSec = DateTime.Now.Second.ToString("00");
                batchId = builder.Append(getYear).Append(getMonth).Append(getDate).Append("-").Append(getHour).
                    Append(getMin).Append(getSec).ToString();
                TransactionContext tc = null;
                tc = TransactionContext.Begin();

                DataTable processTable = new DataTable("DIBenefitAndDeduction");
                processTable.Columns.Add(new DataColumn("BatchID", typeof(string)));
                processTable.Columns.Add(new DataColumn("EmployeeNo", typeof(string)));
                processTable.Columns.Add(new DataColumn("BenifitCode", typeof(string)));
                processTable.Columns.Add(new DataColumn("ItemName", typeof(string)));
                processTable.Columns.Add(new DataColumn("FromDate", typeof(string)));
                processTable.Columns.Add(new DataColumn("ToDate", typeof(string)));
                processTable.Columns.Add(new DataColumn("Amount", typeof(string)));
                processTable.Columns.Add(new DataColumn("payrolltypeid", typeof(int)));

                foreach (DataIntergrationIndividualAllowance item in items)
                {
                    if (item.Items != null)
                    {
                        foreach (ComnpData row in item.Items)
                        {
                            processTable.Rows.Add(batchId, item.EmployeeNo, row.BenifitCode,
                                row.ItemName, row.FromDate, row.ToDate, row.Amount, item.payrolltypeid);
                        }

                    }
                    else
                    {
                        processTable.Rows.Add(batchId, item.EmployeeNo, null, null, null, null, null,item.payrolltypeid);
                    }
                }

                using (SqlBulkCopy bulkCopy = new SqlBulkCopy((SqlConnection)tc.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)tc.Transaction))
                {
                    bulkCopy.BulkCopyTimeout = 6000; // in seconds
                    bulkCopy.DestinationTableName = "DIBenefitAndDeduction";
                    var mapping = new SqlBulkCopyColumnMapping("EmployeeNo", "EmployeeNo");
                    bulkCopy.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("BenifitCode", "BenifitCode");
                    bulkCopy.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("ItemName", "ItemName");
                    bulkCopy.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("FromDate", "FromDate");
                    bulkCopy.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("ToDate", "ToDate");
                    bulkCopy.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("Amount", "Amount");
                    bulkCopy.ColumnMappings.Add(mapping);

                    mapping = new SqlBulkCopyColumnMapping("BatchID", "BatchID");
                    bulkCopy.ColumnMappings.Add(mapping);
                    mapping = new SqlBulkCopyColumnMapping("payrolltypeid", "payrolltypeid");
                    bulkCopy.ColumnMappings.Add(mapping);

                    bulkCopy.WriteToServer(processTable);
                }
                tc.End();

            }
            catch (Exception e)
            {
                throw new ServiceException(e.Message, e);
            }
            return batchId;
        }


        public DataSet GetBudgetDataAllowance(int payrolltypeid)
        {
            DataSet ds = new DataSet();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                ds = DataIntegrationRequestDA.GetBudgetDataAllowance(tc, payrolltypeid);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }

            return ds;
        }
        public DataSet GetBudgetData(int payrolltypeid)
        {
            DataSet ds = new DataSet();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                ds = DataIntegrationRequestDA.GetBudgetData(tc, payrolltypeid);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }

            return ds;
        }

        public DataSet GetSuccessorErrorData(string batchId)
        {
            DataSet ds = new DataSet();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                ds = DataIntegrationRequestDA.GetSuccessListbyBatchID(tc, batchId);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }

            return ds;
        }

        #region ImportEmpIndividualAllowanceDeduction
        public void ImportEmpIndividualAllowanceDeduction(int payrollTypeID, EnumAllowOrDeduct type,
            List<DataIntergrationIndividualAllowance> odataTable, string selectedEmployees)
        {
            _payrollTypeID = payrollTypeID;
            List<ADParameterEmployee> oadparamemployees = new List<ADParameterEmployee>();
            PayrollType ptype = new PayrollTypeService().Get(this._payrollTypeID);
            List<Employee> oemployees = new EmployeeService().GetAllEmps(this._payrollTypeID);
            List<ADParameter> oadparameters = new ADParameterService().GetWithDetail(EnumStatus.Active, _payrollTypeID);
            Employee oemployee = null;
            ADParameterEmployee oadparamemp = null;
            List<AllowanceDeduction> allows = new AllowanceDeductionService().Get(EnumStatus.Regardless, 
                this._payrollTypeID);

            _errorOrSuccessList = new List<UploadErrorOrSuccess>();
            List<ADParameterEmployee> adempsall = new ADParameterEmployeeService().Get(EnumADEmpType.AppliedToIndividual, 
                EnumAllowOrDeduct.Allowance);
            adempsall = adempsall.FindAll(x => x.Arreartype == EnumArrearType.NotPresent  );

            if (selectedEmployees.Length > 0)
            {
                string[] emps = selectedEmployees.Split(',');
                List<ADParameterEmployee> newitems = new List<ADParameterEmployee>();
                foreach (var ep in emps)
                {
                    var emp = oemployees.FirstOrDefault(x => x.EmployeeNo == ep);
                    if (emp != null)
                    {
                        if(adempsall.Any(y => y.EmployeeID == emp.ID))
                            newitems.AddRange(adempsall.FindAll(y => y.EmployeeID == emp.ID));
                    }

                }
                adempsall = newitems;
            }


            List<ADParameterEmployee> deletedItems = new List<ADParameterEmployee>();
             //List<AllowanceDeduction> types = new List<AllowanceDeduction>();
             //types = types = new AllowanceDeductionService().Get(payrollTypeID, EnumStatus.Active, 
             //    EnumAllowOrDeduct.Allowance, EnumPeriodicity.OneOff);
             //Dictionary<int, string> ItemOneComboData = new Dictionary<int, string>();
             //foreach (AllowanceDeduction ADitem in types)
             //{
             //    ItemOneComboData.Add(ADitem.ID, ADitem.Name);
             //}
             int nRow = 0;
            try
            {
                DateTime updatedTime = DateTime.Now;
                DateTime createdDate = DateTime.Today;

                foreach (DataIntergrationIndividualAllowance dr in odataTable)
                {
                    nRow = nRow + 1;
                    oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr.EmployeeNo; });
                    if (oemployee != null)
                    {
                        if (dr.Items != null && dr.Items.Count > 0)
                        {
                            foreach (ComnpData comdata in dr.Items)
                            {
                                if (comdata.ItemName.ToLower() == "basic salary") continue;
                                if (comdata.ItemName == "Monthly Gross") continue;

                                oadparamemp = new ADParameterEmployee();
                                oadparamemp.EmployeeID = oemployee.ID;


                                var allow = allows.FirstOrDefault(x => x.Code == comdata.BenifitCode);
                                if (allow == null)
                                {
                                    AddStatus(nRow, oemployee.EmployeeNo,  "Allowance/Deduction head not found. Item Code :"
                                        + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Error, 
                                        EnumDataIntegrationType.IndividualAllowance);
                                    continue;
                                }

                                if (comdata.Amount == string.Empty)
                                {
                                    AddStatus(nRow, oemployee.EmployeeNo, "Amount can not be Empty. Item Code :"
                                 + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Error,
                                            EnumDataIntegrationType.IndividualAllowance);
                                    continue;
                                }
                                double mAmount = Convert.ToDouble(comdata.Amount);


                                oadparamemp.AllowDeductID = allow.ID;
                                oadparamemp = adempsall.FirstOrDefault(x => x.EmployeeID == oemployee.ID &&
                                        x.AllowDeductID == allow.ID);

                                DateTime fromDate = Convert.ToDateTime(comdata.FromDate);

                                if (oadparamemp == null)
                                {
                                    oadparamemp = new ADParameterEmployee();
                                    oadparamemp.EmployeeID = oemployee.ID;
                                    oadparamemp.AllowDeductID = allow.ID;
                                    oadparamemp.MonthlyAmount = mAmount;
                                    oadparamemp.FormDate = fromDate;
                                    oadparamemp.CreatedDate = createdDate;
                                    oadparamemp.CreatedBy = _userID;
                                    AddStatus(nRow, oemployee.EmployeeNo, "New Benifit/Deduction added. Item Code :"
                                 + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Success,
                                 EnumDataIntegrationType.IndividualAllowance);
                                }
                                else
                                {
                                    DateTime? tdate = comdata.ToDate.ToString() == "" ? null :
                                        Convert.ToDateTime(comdata.ToDate);

                                    if (oadparamemp.MonthlyAmount == mAmount )
                                    {
                                        oadparamemp.ModifiedDate = updatedTime;
                                        oadparamemployees.Add(oadparamemp);
                                        continue;
                                    }

                               
                                    // for Arrear 
                                    if (oadparamemp.FormDate != fromDate && fromDate <= ptype.LastPayProcessDate)
                                    {
                                        var dItem = oadparamemp.GetClone();
                                        dItem.ID = oadparamemp.ID;
                                        deletedItems.Add(dItem);
                                        oadparamemp.ID = 0;

                                        AddStatus(nRow, oemployee.EmployeeNo, "Arrear Modified Benifits/Deduction. Item Code :"
                                                   + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Success,
                                                   EnumDataIntegrationType.IndividualAllowance);
                                    }
                                    else
                                    {
                                        AddStatus(nRow, oemployee.EmployeeNo, "Modified Benifits/Deduction. Item Code :"
                                                + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Success,
                                                EnumDataIntegrationType.IndividualAllowance);
                                    }
                                    oadparamemp.MonthlyAmount = mAmount;
                                    oadparamemp.FormDate = fromDate;
                                    oadparamemp.ModifiedBy = this._userID;
                                    oadparamemp.ModifiedDate = updatedTime;
                                    oadparamemp.TillDate = comdata.ToDate.ToString() == "" ? null :
                                                Convert.ToDateTime(comdata.ToDate);
                                    oadparamemployees.Add(oadparamemp);
                                    continue;
                                }

                                if (oemployee.GradeID == null)
                                {
                                    AddStatus(nRow, oemployee.EmployeeNo, "Grade Id not found :"
                                        + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Error,
                                        EnumDataIntegrationType.IndividualAllowance);
                                    continue;
                                }

                                List<ADParameter> oparamters = oadparameters.FindAll(x => x.AllowDeductID == 
                                oadparamemp.AllowDeductID);
                                ADParameter oparamter = new ADParameterService().GetApplicableParameter(oemployee,
                                    (int)oemployee.GradeID, oadparameters, oadparamemp.AllowDeductID);
                                if (oparamter == null)
                                {
                                    AddStatus(nRow, oemployee.EmployeeNo, "Employee benifit/deduction parameter not found :"
                                        + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Error,
                                        EnumDataIntegrationType.IndividualAllowance);
                                    continue;
                                }

                                oadparamemp.ADParameterID = oparamter.ID;
                                oadparamemp.Periodicity = oparamter.Periodicity;
                                if (oadparamemp.Periodicity == EnumPeriodicity.OneOff)
                                {
                                    oadparamemp.FormDate = GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate);
                                    oadparamemp.TillDate = ptype.NextPayProcessDate;
                                }
                                else if (oadparamemp.Periodicity == EnumPeriodicity.Monthly 
                                    && oparamter.EntitleType == EnumEntitleType.Individual)
                                {
                                    if (comdata.ToDate.ToString() != "" && Convert.ToDateTime(comdata.ToDate) <
                                        Convert.ToDateTime(comdata.FromDate))
                                    {

                                        AddStatus(nRow, oemployee.EmployeeNo, "Till date can not be less than From date :"
                                            + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Error,
                                        EnumDataIntegrationType.IndividualAllowance);
                                        continue;
                                    }
                                    oadparamemp.FormDate = comdata.FromDate.ToString() != "" ? Convert.ToDateTime(comdata.FromDate) :
                                        GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate);
                                    if (comdata.ToDate != "")
                                        oadparamemp.TillDate = Convert.ToDateTime(comdata.ToDate);
                                }
                                else
                                {
                                    AddStatus(nRow, oemployee.EmployeeNo, "Employee applicable parameter is defined greade wise :"
                                        + comdata.BenifitCode + " :" + comdata.ItemName, EnumSAPProcessStatus.Error,
                                    EnumDataIntegrationType.IndividualAllowance);
                                    continue;
                                }

                                if (oparamter.MaxAmount != 0 && oparamter.MaxAmount < oadparamemp.MonthlyAmount)
                                    oadparamemp.MonthlyAmount = oparamter.MaxAmount;
                                if (oparamter.MinAmount != 0 && oparamter.MinAmount > oadparamemp.MonthlyAmount)
                                    oadparamemp.MonthlyAmount = oparamter.MinAmount;

                                oadparamemp.ADEmpType = EnumADEmpType.AppliedToIndividual;
                                oadparamemp.Arreartype = EnumArrearType.NotPresent;
                                oadparamemp.ValueType = EnumValueType.Amount;
                                oadparamemployees.Add(oadparamemp);
                            }
                        }

                    }
                    else
                    {
                        AddStatus(nRow, oemployee.EmployeeNo, "(" + dr.EmployeeNo + ")" + "Employee not found for in the existing data"
                            , EnumSAPProcessStatus.Error, EnumDataIntegrationType.IndividualAllowance);

                    }
                }

                if (_oSuccessOrErrorList.Any(x=>x.Status == EnumSAPProcessStatus.Error)==false)
                {
                    foreach (AllowanceDeduction al in allows)
                    {
                        //bool alexist = oadparamemployees.Any(x => x.AllowDeductID == al.ID);
                        //if (alexist == true)
                        //{
                            var existempal = adempsall.FindAll(x => x.AllowDeductID == al.ID);
                            foreach (ADParameterEmployee item in existempal)
                            {
                                if (item.ModifiedDate != updatedTime)
                                {
                                    var emp = oemployees.FirstOrDefault(x => x.ID == item.EmployeeID);
                                    deletedItems.Add(item);
                                    AddStatus(nRow, emp.EmployeeNo, "deleted benifit/deduction :"
                                                + al.Code + " :" + al.Name, EnumSAPProcessStatus.Success,
                                                EnumDataIntegrationType.IndividualAllowance);
                                }
                            }
                      //  }
                    }
                    if(_oSuccessOrErrorList.Any(x => x.Status == EnumSAPProcessStatus.Success) == false)
                    {
                        AddStatus(0, "", "System didn't find any difference, so nothing to update/integrate:", 
                            EnumSAPProcessStatus.Success, EnumDataIntegrationType.IndividualAllowance);

                    }
                    new ADParameterEmployeeService().IntegrationSave(oadparamemployees,
                        ptype.LastPayProcessDate, deletedItems);
                }
            }
            catch (Exception ex)
            {
                //if (_errorOrSuccessList.Count > 0)
                //{
                //    var errorMessages = _errorOrSuccessList.Select(item =>
                //       $"sl: {item.SL}, row: {item.RowNo}, employeeNo: {item.EmployeeNo}, message: {item.Message}").ToList();

                //    string errorString = string.Join("; ", errorMessages);

                //    throw new ServiceException("ErrorList: " + errorString);
                //}
                throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message);
            }
        }
        #endregion

    }
}