using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CRM.BLL;
using CRM.Model;
using CRM.Common;
using CRM.DBUtility;
using System.Data.SqlClient;


public partial class Pages_sxt_Sends : System.Web.UI.Page
{
    protected void Bind()
    {
        string[] eids = CRM.Common.InitData.GetEmployeesLookRightEids(Session["LoginID"].ToString(), Session["CID"].ToString());
        string sql_eids = "";
        if (eids.Length == 1)
        {
            sql_eids = " and eid=@eid";
            SqlParameter para = new SqlParameter("eid", eids[0]);
            string sql = "select * from 呼叫表 where eid=" + Session["LoginID"].ToString() + " and 处理状态!=1 order by id desc";
            GridView1.DataSource = SqlHelper.ExecuteDataSet(SqlHelper.connstr, CommandType.Text, sql, null);
            GridView1.DataKeyNames = new string[] { "id", "eid", "处理状态" };
            GridView1.DataBind();
        }
        else {
            SqlParameter[] paras = new SqlParameter[eids.Length];

            sql_eids = " and (eid=@eid";
            paras[0] = new SqlParameter("eid", eids[0]);

            for (int i = 1; i < eids.Length - 1; i++)
            {
                sql_eids = sql_eids + " or eid=@eid" + i;
                string paraName = "eid" + i;
                paras[i] = new SqlParameter(paraName, eids[i]);
            }

            sql_eids = sql_eids + " or eid=@eid" + eids.Length + ")";
            paras[eids.Length - 1] = new SqlParameter("eid" + eids.Length, eids[eids.Length - 1]);

            string sql = "select * from 呼叫表 where 1=1" + sql_eids + " and 处理状态!=1 order by id desc";

            GridView1.DataSource = SqlHelper.ExecuteDataSet(SqlHelper.connstr, CommandType.Text, sql, paras);
            GridView1.DataKeyNames = new string[] { "id", "eid", "处理状态" };
            GridView1.DataBind();
        }


        //string sql = "select * from 呼叫表 where eid=" + Session["LoginID"].ToString() + " and 处理状态!=1 order by id desc";
        //GridView1.DataSource = SqlHelper.ExecuteDataSet(SqlHelper.connstr, CommandType.Text, sql, null);
        //GridView1.DataKeyNames = new string[] { "id","eid", "处理状态" };
        //GridView1.DataBind();
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        Bind();
    }
    protected void Gridview1_RowDeleting(object o, GridViewDeleteEventArgs e)
    {
        if (e.RowIndex > -1)
        {
            if (GridView1.DataKeys[e.RowIndex].Values["处理状态"].ToString().Equals("-1"))
            {
                string sql = "delete from 呼叫表 where id=" + GridView1.DataKeys[e.RowIndex].Values["id"].ToString();
                SqlHelper.ExecuteNonQuery(SqlHelper.connstr, CommandType.Text, sql, null);
                Bind();
                RegisterClientScriptBlock("", "<script language=javascript>alert('删除成功!');</script>");
            }
            else
            {
                RegisterClientScriptBlock("", "<script language=javascript>alert('正在处理中，不能删除!');</script>");
            }
        }

    }

    protected void GridView1_RowCommand(object o, GridViewCommandEventArgs e)
    {
        if (GridView1.SelectedIndex > -1)
        {
            if (e.CommandName == "Select")
            {
                Panel2.Visible = true;
                string id = GridView1.DataKeys[GridView1.SelectedIndex].Values["id"].ToString();
                string sql = "select * from 呼叫表 where id=" + id;
                DataTable dt = SqlHelper.ExecuteDataSet(SqlHelper.connstr, CommandType.Text, sql, null).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    TextBox1.Text = dt.Rows[0]["语音文本"].ToString();
                    TextBox2.Text = dt.Rows[0]["短信文本"].ToString();
                    Label1.Text = dt.Rows[0]["呼叫号码"].ToString();
                    HyperLink1.NavigateUrl = "../../" + dt.Rows[0]["呼叫号码"].ToString();
                    HyperLink2.NavigateUrl = "../../" + dt.Rows[0]["语音文件"].ToString();
                    TextBox3.Text = dt.Rows[0]["已发送"].ToString();
                    TextBox4.Text = dt.Rows[0]["未发送"].ToString();
                    Label2.Text = dt.Rows[0]["未发送"].ToString();
                    rbl1.SelectedValue = dt.Rows[0]["处理状态"].ToString();
                    if (rbl1.SelectedValue == "1") {
                        Panel1.Visible = true;
                        Button2.Enabled = false;
                    }

                    //更新处理状态
                    string sql2 = "update 呼叫表 set 处理状态=0 where id=" + GridView1.DataKeys[GridView1.SelectedIndex].Values["id"].ToString();
                    SqlHelper.ExecuteNonQuery(SqlHelper.connstr, CommandType.Text, sql2, null);
                }

                //RegisterClientScriptBlock("", "<script language=javascript>alert('正在处理中，不能删除!');</script>");
            }
        }
    }

    protected void rbl_TextChanged(object sender, EventArgs e) {
        if (rbl1.SelectedValue == "1") {
            Panel1.Visible = true;
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        if(decimal.Parse(Label2.Text.Trim())!=decimal.Parse(TextBox4.Text.Trim())+decimal.Parse(TextBox3.Text.Trim())){
            RegisterClientScriptBlock("", "<script language=javascript>alert('输入数据有误，请检查。发送与未发送之和应等于总发送条数!');</script>");
            return;
        }

        //上传呼叫详单
        #region
        string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName.ToString().ToLower());
        if (IsXls != ".xls")
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script type='text/javascript' language='javascript'>alert('请选择呼叫详单，只可以选择Excel文件')</script>");
            return;//当选择的不是Excel文件时,返回
        }
        string error = null;

        //string strpath = FileUpload1.PostedFile.FileName.ToString();         //获取Execle文件路径
        ////string filename = FileUpload1.FileName;        //获取Execle文件名
        //string filename = string.Format("yyyyMMdd-HH-MM",DateTime.Now.ToString())+strpath.Substring(strpath.LastIndexOf("\\") + 1);
        //string serverpath = Server.MapPath("Files/") +filename;   //这里设置文件的保存路径

        //FileUpload1.PostedFile.SaveAs(serverpath);

        string filepath = FileUpload1.PostedFile.FileName;
        string filename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString() + filepath.Substring(filepath.LastIndexOf("\\") + 1);
        string serverpath = Server.MapPath("../../Files/") + filename;   //这里设置文件的保存路径 
        FileUpload1.PostedFile.SaveAs(serverpath);
        #endregion


        string sql = "update 呼叫表 set 处理状态='1',已发送=@已发送,未发送=@未发送,呼叫详单=@呼叫详单 where id="+GridView1.DataKeys[GridView1.SelectedIndex].Values["id"].ToString();
        SqlParameter[] paras = new SqlParameter[3];
        paras[0] = new SqlParameter("已发送",TextBox3.Text.Trim());
        paras[1] = new SqlParameter("未发送",TextBox4.Text.Trim());
        paras[2] = new SqlParameter("呼叫详单","Files/"+filename);
        SqlHelper.ExecuteNonQuery(SqlHelper.connstr, CommandType.Text, sql, paras);

        string price = SqlHelper.ExecuteScalar(SqlHelper.connstr, CommandType.Text, "select price from 短信价格表", null).ToString();
        string sql3 = "update 客户余额表 set 可用余额=(可用余额+" + decimal.Parse(TextBox4.Text.Trim()) * decimal.Parse(price) +"),余额=(余额-" + decimal.Parse(TextBox3.Text.Trim()) * decimal.Parse(price) + "),消费=(消费+" + decimal.Parse(TextBox3.Text.Trim()) * decimal.Parse(price) + ") where id=(select top 1 id from 客户余额表 where 充值状态=1 and eid=" + GridView1.DataKeys[GridView1.SelectedIndex].Values["eid"].ToString() + " order by id desc)";
        SqlHelper.ExecuteNonQuery(SqlHelper.connstr, CommandType.Text, sql3, null);


        RegisterClientScriptBlock("", "<script language=javascript>alert('处理完成!');</script>");
        Bind();
    }
    protected void Button3_Click(object sender,EventArgs e) {
        string sql = "update 呼叫表 set 处理状态=0 where id=" + GridView1.DataKeys[GridView1.SelectedIndex].Values["id"].ToString();
        SqlHelper.ExecuteNonQuery(SqlHelper.connstr,CommandType.Text,sql,null);
        
        //Response.Redirect("../../" + Label1.Text.Trim());
        //Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode("../../"+Label1.Text.Trim()));
        //Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流，必须被下载 
        //Response.WriteFile("../../"+Label1.Text.Trim()); // 把文件流发送到客户端 
        //Response.End();

    }

    protected void rbl2_TextChanged(object sender,EventArgs e) {
        string sql = "";
        switch(rbl2.SelectedItem.Value) {
            case "0":
                sql = "select * from 呼叫表 where 处理状态!=1 order by id desc";
                break;
            case "1":
                sql = "select * from 呼叫表 where 处理状态=1 order by id desc";
                break;
            default:
                sql = "select * from 呼叫表 order by id desc";
                break;            
        }
        GridView1.DataSource = SqlHelper.ExecuteDataSet(SqlHelper.connstr, CommandType.Text, sql, null);
        GridView1.DataKeyNames = new string[] { "id", "处理状态" };
        GridView1.DataBind();
    }

    public string GetClientMobile(string eid) {
        string sql = "select 手机 from 员工表 where eid="+eid;
        return SqlHelper.ExecuteScalar(SqlHelper.connstr,CommandType.Text,sql,null).ToString();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        CRM.Common.Login.IsLogin();
        if (!IsPostBack)
        {
            Bind();
            Panel1.Visible = false;
            Panel2.Visible = false;
        }
    }
}
