using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer;
using DTO;
using Helper;
using Telerik.Web.UI;

namespace NikaiDSR.Executive
{
    public partial class AddVisit : PageBase
    {
        #region Declaration
        VisitManager VM = new VisitManager();
        CommonManager CM = new CommonManager();
        DSRManager DSRM = new DSRManager();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Page.Title = "NIKAI - ADD VISIT";
                FillObjectiveComboBox();
                Session["ContactCustomerLocation"] = null;

                dpDate.SelectedDate = Convert.ToDateTime(Request.QueryString["Dt"]);
                if (!string.IsNullOrEmpty(Request.QueryString["DSRId"]))
                {
                    dpDate.Enabled = true;
                    LoadData();
                }
            }
        }

        void FillObjectiveComboBox()
        {
            IList<ParameterDTO> Objectives = CM.GetVisitObjective();
            Helper.Validation.FillTelerikDropdown(cmbObjective, Objectives, (LanguageId != 27) ? "Description" : "DescriptionBL", "ParameterDetId", "Select", "0");
        }

        void LoadData()
        {
            DSRDTO DSR = DSRM.GetDSR(Convert.ToInt32(Request.QueryString["DSRId"]));
            FillCustomerComboBox("");
            ActiveContactCustomerLocationDTO ContactCustomer = ((IList<ActiveContactCustomerLocationDTO>)Session["ContactCustomerLocation"]).Where(c => c.Contact_Id == DSR.Contact_Id).FirstOrDefault();
            cmbCustomers.Text = ContactCustomer.Customer_Name;
            FillContactComboBox();
            cmbContact.SelectedValue = ContactCustomer.Contact_Id.ToString();
            txtDepartment.Text = (LanguageId != 27) ? ContactCustomer.Department : ContactCustomer.Department_BL;
            txtMobile.Text = ContactCustomer.Mobile;
            cmbObjective.SelectedValue = DSR.Objective;
            tpTimeIn.SelectedDate = DateTime.Now.Date.Add(DSR.Time_In.Value);
            tpTimeOut.SelectedDate = DateTime.Now.Date.Add(DSR.Time_Out.Value);
            txtTimeMerchandiser.Text = DSR.Time_w_Merchandiser.ToString();
            txtCollection.Text = DSR.Collection.ToString();
            txtSecondarySales.Text = DSR.Secondary_Sales.ToString();
            txtLPO.Text = DSR.Sales_LPO_Received.ToString();
            txtDiscount.Text = DSR.Discount.ToString();
            txtSalesReturn.Text = DSR.Sales_Return.ToString();
            txtRemarks.Text = DSR.Remarks;
        }

        protected void cmbCustomers_ItemsRequested(object sender, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
        {
            FillCustomerComboBox(e.Text);
        }

        void FillCustomerComboBox(string SearchText)
        {
            IList<ActiveContactCustomerLocationDTO> ContactCustomerLocation;

            ContactCustomerLocation = VM.GetActiveContactCustomerLocation(Convert.ToInt32(Request.QueryString["UID"]), null);
            if (LanguageId == 27)
            {
                string temp;
                foreach (ActiveContactCustomerLocationDTO Customer in ContactCustomerLocation)
                {
                    temp = Customer.Customer_Name;
                    Customer.Customer_Name = Customer.Customer_Name_BL;
                    Customer.Customer_Name_BL = temp;

                    temp = Customer.Contact_Name;
                    Customer.Contact_Name = Customer.Contact_Name_BL;
                    Customer.Contact_Name_BL = temp;
                }
            }

            Session["ContactCustomerLocation"] = ContactCustomerLocation;

            cmbCustomers.DataSource = null;
            if (!string.IsNullOrEmpty(SearchText))
            {
                cmbCustomers.DataSource = ContactCustomerLocation.Where(c => !string.IsNullOrEmpty(c.Customer_Name) && c.Customer_Name.ToLower().Contains(SearchText.ToLower())).GroupBy(c => c.Customer_Name);
            }
            else
            {
                cmbCustomers.DataSource = ContactCustomerLocation.Where(c => !string.IsNullOrEmpty(c.Customer_Name)).GroupBy(c => c.Customer_Name);
            }
            cmbCustomers.DataBind();
        }

        protected void cmbCustomers_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            FillContactComboBox();
        }

        void FillContactComboBox()
        {
            IList<ActiveContactCustomerLocationDTO> ContactCustomerLocation;

            if (Session["ContactCustomerLocation"] != null)
            {
                ContactCustomerLocation = (IList<ActiveContactCustomerLocationDTO>)Session["ContactCustomerLocation"];
                ContactCustomerLocation = ContactCustomerLocation.Where(c => !string.IsNullOrEmpty(c.Customer_Name) && c.Customer_Name == cmbCustomers.Text).ToList();
                cmbContact.Text = "";
                cmbContact.DataSource = ContactCustomerLocation;
                cmbContact.DataBind();

                if (ContactCustomerLocation.Count > 0)
                {
                    string dept = "";
                    if (LanguageId != 27)
                        dept = ContactCustomerLocation.Select(c => c.Department).FirstOrDefault();
                    else
                        dept = ContactCustomerLocation.Select(c => c.Department_BL).FirstOrDefault();

                    txtDepartment.Text = dept;
                    txtMobile.Text = ContactCustomerLocation.Select(c => c.Mobile).FirstOrDefault();
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string Error = "";
            if (Validate(ref Error))
            {
                VisitDTO Visit = new VisitDTO();

                if (!string.IsNullOrEmpty(cmbCustomers.SelectedValue.Trim()))
                    Visit.Customer_Id = Convert.ToInt32(cmbCustomers.SelectedValue);
                else
                {
                    if (LanguageId != 27)
                        Visit.Customer_Name = cmbCustomers.Text.Trim();
                    else
                        Visit.Customer_Name_BL = cmbCustomers.Text.Trim();

                    Visit.Location_Id = LocationId;
                }

                if (!string.IsNullOrEmpty(cmbContact.SelectedValue.Trim()) && cmbContact.SelectedValue != "0")
                    Visit.Contact_Id = Convert.ToInt32(cmbContact.SelectedValue);

                IList<ActiveContactCustomerLocationDTO> ContactCustomerLocation = (IList<ActiveContactCustomerLocationDTO>)Session["ContactCustomerLocation"];

                if (LanguageId != 27)
                {
                    Visit.Contact_Name = cmbContact.Text.Trim();
                    Visit.Department = txtDepartment.Text;

                    if (Visit.Contact_Id != null)
                    {
                        Visit.Contact_Name_BL = ContactCustomerLocation.Where(c => c.Contact_Id == Visit.Contact_Id).Select(c => c.Contact_Name_BL).FirstOrDefault();
                        Visit.Department_BL = ContactCustomerLocation.Where(c => c.Contact_Id == Visit.Contact_Id).Select(c => c.Department_BL).FirstOrDefault();
                    }
                    else
                    {
                        Visit.Contact_Name_BL = cmbContact.Text.Trim();
                        Visit.Department_BL = txtDepartment.Text;
                    }
                }
                else
                {
                    Visit.Contact_Name_BL = cmbContact.Text.Trim();
                    Visit.Department_BL = txtDepartment.Text;

                    if (Visit.Contact_Id != null)
                    {
                        Visit.Contact_Name = ContactCustomerLocation.Where(c => c.Contact_Id == Visit.Contact_Id).Select(c => c.Contact_Name).FirstOrDefault();
                        Visit.Department = ContactCustomerLocation.Where(c => c.Contact_Id == Visit.Contact_Id).Select(c => c.Department).FirstOrDefault();
                    }
                    else
                    {
                        Visit.Contact_Name = cmbContact.Text.Trim();
                        Visit.Department = txtDepartment.Text;
                    }
                }

                Visit.Mobile = txtMobile.Text;
                Visit.Site_User_Id = Convert.ToInt32(Request.QueryString["UID"]);
                Visit.Date = dpDate.SelectedDate ?? DateTime.Now;
                Visit.Objective = Convert.ToInt32(cmbObjective.SelectedValue);
                Visit.Time_In = ((DateTime)tpTimeIn.SelectedDate).TimeOfDay;
                Visit.Time_Out = ((DateTime)tpTimeOut.SelectedDate).TimeOfDay;
                Visit.Time_w_Merchandiser = (string.IsNullOrEmpty(txtTimeMerchandiser.Text)) ? 0 : Convert.ToInt32(txtTimeMerchandiser.Text);
                Visit.Collection = (string.IsNullOrEmpty(txtCollection.Text)) ? 0 : Convert.ToInt32(txtCollection.Text);
                Visit.Secondary_Sales = (string.IsNullOrEmpty(txtSecondarySales.Text)) ? 0 : Convert.ToInt32(txtSecondarySales.Text);
                Visit.Sales_LPO_Received = (string.IsNullOrEmpty(txtLPO.Text)) ? 0 : Convert.ToInt32(txtLPO.Text);
                Visit.Discount = (string.IsNullOrEmpty(txtDiscount.Text)) ? 0 : Convert.ToInt32(txtDiscount.Text);
                Visit.Sales_Return = (string.IsNullOrEmpty(txtSalesReturn.Text)) ? 0 : Convert.ToInt32(txtSalesReturn.Text);
                Visit.Remarks = txtRemarks.Text;
                Visit.Updated_By = UserID;
                try
                {
                    if (string.IsNullOrEmpty(Request.QueryString["DSRId"]))
                    {
                        VM.InsertVisit(Visit);
                    }
                    else
                    {
                        Visit.DSR_Id = Convert.ToInt32(Request.QueryString["DSRId"]);
                        VM.UpdateVisit(Visit);
                    }
                }
                catch (Exception ex)
                { }
                RadAjaxManager2.ResponseScripts.Add(string.Format("RefreshParentPage();", DateTime.Now.ToLongTimeString()));
            }
            else
            {
                ShowErrorMessage(Error, errMsg, Common.ERROR_MESSAGE_TYPE.ERROR);
            }
        }

        bool Validate(ref string Error)
        {
            if (!(Helper.Validation.ComboBoxValidate(cmbCustomers)
                && Validation.ComboBoxValidate(cmbContact)
                //&& Validation.TextBoxValidate(txtMobile)
                && Validation.ComboBoxValidate(cmbObjective)
                && Validation.TimePickerValidate(tpTimeIn)
                && Validation.TimePickerValidate(tpTimeOut)
                //&& Validation.NumericTextBoxValidate(txtTimeMerchandiser)
                ))
            {
                Error = (string)GetGlobalResourceObject("Res", "Fill_all_mandatory_fields");
                return false;
            }
            else if (tpTimeIn.SelectedDate > tpTimeOut.SelectedDate)
            {
                Error = (string)GetGlobalResourceObject("Res", "OutTime_Intime");
                return false;
            }

            return true;
        }

        protected void cmbContact_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((ActiveContactCustomerLocationDTO)e.Item.DataItem).Contact_Name;
            e.Item.Value = ((ActiveContactCustomerLocationDTO)e.Item.DataItem).Contact_Id.ToString();

            string dept = "";
            if (LanguageId != 27)
                dept = ((ActiveContactCustomerLocationDTO)e.Item.DataItem).Department;
            else
                dept = ((ActiveContactCustomerLocationDTO)e.Item.DataItem).Department_BL;

            e.Item.Attributes["Department"] = dept;
            e.Item.Attributes["MobileNo"] = ((ActiveContactCustomerLocationDTO)e.Item.DataItem).Mobile;
        }
    }
}