using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Model;
using BLL;
namespace ComResProSystem
{
    public partial class SendMessage:BasePage
    {
        UserBll userbll = new UserBll();
        BaseBLL bll = new BaseBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTvPerson();
            }
        }

        protected void Tv_Person_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (Tv_Person.SelectedNode.Depth == 0)
            {
                string Part = Tv_Person.SelectedValue;
                DataTable dt = userbll.gettable("SELECT UserName FROM dbo.Users WHERE Part='" + Part + "'");
                TreeNode node = Tv_Person.SelectedNode;
                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    node.ChildNodes.Add(new TreeNode(dt.Rows[i]["UserName"].ToString(), dt.Rows[i]["UserName"].ToString()));
                }
            }
            if ((Tv_Person.SelectedNode.Depth == 1))
            {
                string value = Tv_Person.SelectedValue;
                Tb_Recipients.Text = Tb_Recipients.Text + value + ";";

            }
        }
        protected void BindTvPerson()
        {
            DataTable dt = userbll.gettable("SELECT DISTINCT  Part FROM Users");
            for (int i = 0; i < dt.Rows.Count; i++)
            {

                Tv_Person.Nodes.Add(new TreeNode(dt.Rows[i]["Part"].ToString(), dt.Rows[i]["Part"].ToString()));
            }
        }

        protected void Ibt_Submit_Click(object sender, ImageClickEventArgs e)
        {
            List<Dictionary<string, string>> list = baseinfo();
            for (int i = 0; i < list.Count; i++)
            {
                object obj=bll.CreateObject(typeof(mail),list[i]);
                bll.SaveObject(obj, "mail");
            }
            Tb_MailContents.Text = "";
            Tb_Recipients.Text = "";
            Tb_Theme.Text = "";
        }
        protected List<Dictionary<string, string>> baseinfo()
        {
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            string[] Recipients = Tb_Recipients.Text.Split(';');
            for (int i = 0; i < Recipients.Length; i++)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                if (Recipients[i] != "")
                {
                    dic.Add("Recipients", Recipients[i]);
                    dic.Add("Theme", Tb_Theme.Text);
                    dic.Add("Senduser", Session["UserName"].ToString());
                    dic.Add("MailContents", Tb_MailContents.Text);
                    list.Add(dic);
                }
            }
            return list;
        }
    }
}