using CommonFunc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EnvigoHiring.Models.Position
{
    public class PositionModel : BaseClass
    {
        public int PositionID { get; set; }
        [Required(ErrorMessage ="Alert! Select desgination")]
        public string ddlDesignation { get; set; }
       
        [Required(ErrorMessage = "Alert! Select department")]
        public string ddlDepartment { get; set; }
        [Required(ErrorMessage = "Alert! Select unit")]
        public string ddlUnit { get; set; }
        [Required(ErrorMessage = "Alert! Select priority")]
        public string ddlPriority { get; set; }
        public string TAT { get; set; }
        [Required(ErrorMessage = "Alert! Request Date should not be blank")]
        [DataType(DataType.DateTime,ErrorMessage ="Invalid Request date")]
        public string RequestDate { get; set; }
        [Required(ErrorMessage = "Alert! ClosedBy Date should not be blank")]
        public string ClosedByDate { get; set; }
        [Required(ErrorMessage = "Alert! Experience should not be blank")]
        public double Experience { get; set; }
        [Required(ErrorMessage = "Alert! Yearly Salary Budget should not be blank")]
        [RegularExpression(@"^[0-9.]+$", ErrorMessage = "Alert! Yearly Salary Budget Should be numeric")]
        public double YearlySalaryBudget { get; set; }
        public string Status { get; set; }
        public List<SelectListItem> Designation { get; set; }
        public List<SelectListItem> Department { get; set; }
        public DataTable dtPosition { get; set; }
        
        DataLayer obj = DataLayer.Instance;

        public bool Filldata()
        {
            bool result = true;
            string query = string.Format("select * from tblPositions where PositionID={0}", PositionID);
            DataTable dt = obj.SelectDatatable(query);
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                ddlDesignation = BasicFunc.SetParamValue(row, "DesignationID");
                ddlDepartment = BasicFunc.SetParamValue(row, "Department");
                Experience = Convert.ToDouble(BasicFunc.SetParamValue(row, "Experience"));
                ddlUnit = BasicFunc.SetParamValue(row, "Unit");
                ddlPriority = BasicFunc.SetParamValue(row, "Priority");
                TAT = Convert.ToDateTime(BasicFunc.SetParamValue(row, "TAT")).ToString("MM/dd/yyyy");
                ClosedByDate = Convert.ToDateTime(BasicFunc.SetParamValue(row, "ClosedByDate")).ToString("MM/dd/yyyy");
                YearlySalaryBudget = Convert.ToDouble(BasicFunc.SetParamValue(row, "YearlySalaryBudget"));
                //chkActive = (BasicFunc.SetParamValue(row, "Status")=="1")?true:false;
                Status= BasicFunc.SetParamValue(row, "Status");
                
            }
            else
            {
                result = false;
                reset();
            }
            return result;
        }
        public void reset()
        {
            ddlDesignation = "0";
            Experience = 0;
            ddlDepartment = "0";
            ddlUnit = "0";
            ddlPriority = "0";
            TAT = "";
            ClosedByDate = "";
            YearlySalaryBudget = 0;
        }
        public int JobDescriptionStatus(string PosID)
        {
            int JDStatus = 0;
            string query = "Select ApproveStatus from tblJobDescription where PositionID=" + PosID;
            DataTable dt = obj.SelectDatatable(query);
            if (dt != null && dt.Rows.Count > 0)
            {
                JDStatus = BasicFunc.SetParamValue(dt.Rows[0], "ApproveStatus").ToInt32();
            }
            return JDStatus;
        }
        public void SaveData()
        {
            FilePath = ConfigurationManager.AppSettings["ResumePath"].ToString().Trim();
            var vl = ValidationFunc.ValidateModelData<PositionModel>(this, "ddlDesignation", "ddlRequester", "Experience","ddlDepartment", "ddlUnit", "ddlPriority", "YearlySalaryBudget");
            if (vl.isValid == false)
            {
                alert(vl.Message, vl.isValid);
                return;
            }
            if (!CheckFunc.IsDate(ClosedByDate))
            {
                alert("Alert! Closed By Date is not Valid date time", false);
            }
           
            var sv = Save();
            alert(sv.Message, sv.isSuccess);
        }
        //public validate ValidateData()
        //{
        //    validate vm = new validate();
        //    vm.isValid = true;
        //    /* Check Duplicate Page */
        //    string qryChkExist1 = "select EmailID from tblMasterCandidatePool where EmailID = '" + HttpUtility.HtmlEncode(EmailID.ToString().Trim()) + "'";
        //    if (PositionID != 0)
        //    {
        //        qryChkExist1 = "select EmailID from tblMasterCandidatePool where EmailID = '" + HttpUtility.HtmlEncode(EmailID.ToString().Trim()) + "' and CandidateID<>" + CandidateID;
        //    }
        //    string ChkRecord1 = obj.GetDatafromQuery(qryChkExist1)[0];
        //    if (ChkRecord1 != null)
        //    {
        //        if (ChkRecord1 != "")
        //        {
        //            vm.isValid = false;
        //            vm.Message = "Email  already exist! Please choose diffrent";
        //            return vm;
        //        }
        //    }


        //    return vm;
        //}
        public SaveData Save()
        {
            SaveData sv = new SaveData();

            //var vl = ValidateData();
            //sv.isSuccess = vl.isValid;
            //if (vl.isValid == false)
            //{
            //    sv.Message = vl.Message;
            //    return sv;
            //}
            Status=(PositionID > 0)? Status : "Open";
            SqlParameter[] perm1 = new SqlParameter[11];
            perm1[0] = new SqlParameter("@PositionID", PositionID);
            perm1[1] = new SqlParameter("@DesignationID", ddlDesignation.ToInt32());
            perm1[2] = new SqlParameter("@RequesterID", UserID.ToInt32());
            perm1[3] = new SqlParameter("@Department", ddlDepartment.ToInt32());
            perm1[4] = new SqlParameter("@Unit", ddlUnit.ToInt32());
            perm1[5] = new SqlParameter("@Priority", ddlPriority.HtmlEncode());
            perm1[6] = new SqlParameter("@TAT", GetTAT().ToString("MM/dd/yyyy"));
            perm1[8] = new SqlParameter("@ClosedByDate", ClosedByDate.ToString().Trim());
            perm1[9] = new SqlParameter("@Experience", Experience);
            perm1[10] = new SqlParameter("@YearlySalaryBudget", YearlySalaryBudget);
            perm1[7] = new SqlParameter("@Status", Status);
            DataTable success1 = obj.ExecuteStoreProcedure("proc_tblPositions", perm1);
            //CandidateID = Int32.Parse(perm1[19].Value.ToString().Trim());'@LastCompany', 
            if (success1 != null)
            {
                if (PositionID == 0)
                {
                    sv.isSuccess = true;
                    sv.Message = "<b>Success :</b> Page added successfully.";
                    return sv;
                }
                else
                {
                    sv.isSuccess = true;
                    sv.Message = "<b>Success :</b> Page updated successfully.";

                    return sv;
                }
            }
            return sv;
        }
        public DateTime GetTAT()
        {
            DateTime TATdate= DateTime.Now.AddDays(30);
            if (ddlPriority == "High")
            {
                TATdate= DateTime.Now.AddDays(7);
            }
            else if (ddlPriority == "Medium")
            {
                TATdate= DateTime.Now.AddDays(15);
            }
            else if (ddlPriority == "Low")
            {
                TATdate= DateTime.Now.AddDays(30);
            }
            return TATdate;
        }
        public DataTable viewPosition()
        {
            string subquery = (Users.LoginDetail().Roles == "User") ? "and t.RequesterID=" + UserID.ToInt32() : "";
            string query = string.Format(@"select PositionID,DepartmentName,DesignationName,UnitName,Priority,TAT,ClosedByDate, t.status ,t.Experience,t.YearlySalaryBudget
                            ,(select count(1) from tblSuggestedApplicants where  positionid=t.positionid) as Tcount
							,(select count(1) from tblSuggestedApplicants where currentstatus='Approve' and positionid=t.positionid) as TApprvcount  from tblPositions t 
                            inner join  tblMasterDepartment dept on (t.Department=dept.DepartmentID) inner join tblMasterDesignation desg on (t.DesignationID=desg.DesignationID)
                            inner join tblMasterUnit unt on (t.Unit=unt.unitID) where (t.status='Open' or t.status='ReOpen') {0} order by t.RequestDate desc", subquery);
            return obj.SelectDatatable(query);
        }
        public DataTable viewInActivePosition()
        {
            string subquery =(Users.LoginDetail().Roles=="User")? "and t.RequesterID="+UserID.ToInt32():"";
            string query = string.Format(@"select PositionID,DepartmentName,DesignationName,UnitName,Priority,TAT,ClosedByDate, t.status ,t.Experience,t.YearlySalaryBudget
                            ,(select count(1) from tblSuggestedApplicants where currentstatus='selected' and positionid=t.positionid) as Tcount
							,(select count(1) from tblSuggestedApplicants where currentstatus='Approve' and positionid=t.positionid) as TApprvcount  from tblPositions t 
                            inner join  tblMasterDepartment dept on (t.Department=dept.DepartmentID) inner join tblMasterDesignation desg on (t.DesignationID=desg.DesignationID)
                            inner join tblMasterUnit unt on (t.Unit=unt.unitID) where (t.status!='Open' and t.status!='ReOpen') {0} order by t.RequestDate desc", subquery);
            return obj.SelectDatatable(query);
        }
        public List<SelectListItem> DesignationList(string DepartmentID)
        {
            DepartmentID = (DepartmentID == null || DepartmentID == "") ? "0" : DepartmentID;
            string query = string.Format("Select distinct DesignationID,DesignationName from tblMasterDesignation where departmentID={0} order by DesignationName asc", DepartmentID);
            return Common.FillSelectList(query, "DesignationName", "DesignationID");
        }

        public List<SelectListItem> DepartmentList()
        {
            string query = "Select distinct DepartmentID,DepartmentName from tblMasterDepartment order by DepartmentName asc";
            return Common.FillSelectList(query, "DepartmentName", "DepartmentID");
        }
        public List<SelectListItem> UnitList()
        {
            string query = "Select distinct unitID,UnitName from tblMasterUnit order by UnitName asc";
            return Common.FillSelectList(query, "UnitName", "unitID");
        }
       
        public List<SelectListItem> PriorityList()
        {
            return Common.FillSelectListManual("High","Medium","Low");
        }
        public List<SelectListItem> StatusList()
        {
            if (Status == "OnHold")
            {
                return Common.FillSelectListManual("OnHold","ReOpen");
            }
            else
            {
                return Common.FillSelectListManual("Open", "OnHold");
            }
        }
    }
}