using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
using CRM.BLL;
using CRM.Model;
using CRM.Common;
using CRM.DBUtility;
using System.Data.SqlClient;
using System.IO;
using System.Text;

public partial class Pages_Client_Default : CRM.Common.Login
{
    private string _ClientID;
    private string _CommandName;
    private string _ClientName;
    private int _GridViewSelectedIndex;

    public event EventHandler SelectedIndexChanged;
    public event GridViewCommandEventHandler RowCommand;
    public event EventHandler RowDataBound;

    public string ClientID
    {
        get
        {
            if (GridView1.SelectedIndex > -1)
            {
                return GridView1.DataKeys[GridView1.SelectedIndex].Values["id"].ToString();
            }
            return "";
        }
    }
    public int GridviewSelectedIndex
    {
        get { return GridView1.SelectedIndex; }
    }
    public string ClientName
    {
        get { return _ClientName; }
        set { _ClientName = value; }
    }
    public string CommandName
    {
        get { return _CommandName; }
    }
    protected void Init_Data()
    {
        ddlProvince.Items.Clear();
        ddlProvince.Items.Add(new ListItem("省份", "-1"));
        System.Data.DataTable dtProvince = CRM.Common.InitData.GetProvinceByCid(Session["CID"].ToString());
        if (dtProvince.Rows.Count > 0)
        {
            for (int i = 0; i < dtProvince.Rows.Count; i++)
            {
                ddlProvince.Items.Add(new ListItem(dtProvince.Rows[i]["名称"].ToString(), dtProvince.Rows[i]["id"].ToString()));
            }
        }

        ddlCity.Items.Clear();
        ddlCity.Items.Add(new ListItem("地区", "-1"));
        System.Data.DataTable dtCity = CRM.Common.InitData.GetCityByProvince(ddlProvince.SelectedValue.ToString());
        if (dtCity.Rows.Count > 0)
        {
            for (int i = 0; i < dtCity.Rows.Count; i++)
            {
                ddlCity.Items.Add(new ListItem(dtCity.Rows[i]["名称"].ToString(), dtCity.Rows[i]["id"].ToString()));
            }
        }

        ddlSales.Items.Clear();
        ddlSales.Items.Add(new ListItem("业务员", "-1"));
        System.Data.DataTable dtSales = CRM.Common.InitData.GetSalesByCid(Session["CID"].ToString());
        if (dtSales.Rows.Count > 0)
        {
            for (int i = 0; i < dtSales.Rows.Count; i++)
            {
                ddlSales.Items.Add(new ListItem(dtSales.Rows[i]["姓名"].ToString(), dtSales.Rows[i]["eid"].ToString()));
            }
        }

        ddlClientType.Items.Clear();
        ddlClientType.Items.Add(new ListItem("客户类型", "-1"));
        System.Data.DataTable dtClientType = CRM.Common.InitData.InitData_ClientType(Session["CID"].ToString());
        if (dtClientType.Rows.Count > 0)
        {
            for (int i = 0; i < dtClientType.Rows.Count; i++)
            {
                ddlClientType.Items.Add(new ListItem(dtClientType.Rows[i]["客户类型"].ToString(), dtClientType.Rows[i]["id"].ToString()));
            }
        }


        ddlClientPhase.Items.Clear();
        ddlClientPhase.Items.Add(new ListItem("客户阶段", "-1"));
        System.Data.DataTable dtClientPhase = CRM.Common.InitData.InitData_ClientPhase(Session["CID"].ToString());
        if (dtClientPhase.Rows.Count > 0)
        {
            for (int i = 0; i < dtClientPhase.Rows.Count; i++)
            {
                ddlClientPhase.Items.Add(new ListItem(dtClientPhase.Rows[i]["客户阶段"].ToString(), dtClientPhase.Rows[i]["id"].ToString()));

            }
        }

        ddlClientStatus.Items.Clear();
        ddlClientStatus.Items.Add(new ListItem("客户状态", "-1"));
        System.Data.DataTable dtClientStatus = CRM.Common.InitData.InitData_ClientStatus(Session["CID"].ToString());
        if (dtClientStatus.Rows.Count > 0)
        {
            for (int i = 0; i < dtClientStatus.Rows.Count; i++)
            {
                ddlClientStatus.Items.Add(new ListItem(dtClientStatus.Rows[i]["客户状态"].ToString(), dtClientStatus.Rows[i]["id"].ToString()));
            }
        }

        ddlClientRank.Items.Clear();
        ddlClientRank.Items.Add(new ListItem("客户级别", "-1"));
        System.Data.DataTable dtClientRank = CRM.Common.InitData.InitData_ClientRank(Session["CID"].ToString());
        if (dtClientRank.Rows.Count > 0)
        {
            for (int i = 0; i < dtClientRank.Rows.Count; i++)
            {
                ddlClientRank.Items.Add(new ListItem(dtClientRank.Rows[i]["客户级别"].ToString(), dtClientRank.Rows[i]["id"].ToString()));
            }
        }

        ddlClientIndustry.Items.Clear();
        ddlClientIndustry.Items.Add(new ListItem("行业", "-1"));
        System.Data.DataTable dtClientIndustry = CRM.Common.InitData.InitData_ClientIndustry(Session["CID"].ToString());
        if (dtClientIndustry.Rows.Count > 0)
        {
            for (int i = 0; i < dtClientIndustry.Rows.Count; i++)
            {
                ddlClientIndustry.Items.Add(new ListItem(dtClientIndustry.Rows[i]["客户行业"].ToString(), dtClientIndustry.Rows[i]["id"].ToString()));
            }
        }
    }

    protected void ddlProvince_TextChanged(object sender, EventArgs e)
    {
        ddlCity.Items.Clear();
        ddlCity.Items.Add(new ListItem("请选择", "-1"));
        System.Data.DataTable dtCity = CRM.Common.InitData.GetCityByProvince(ddlProvince.SelectedValue.ToString());
        if (dtCity.Rows.Count > 0)
        {
            for (int i = 0; i < dtCity.Rows.Count; i++)
            {
                ddlCity.Items.Add(new ListItem(dtCity.Rows[i]["名称"].ToString(), dtCity.Rows[i]["id"].ToString()));
            }
        }
    }
    public void Bind()
    {
        string[] eids = CRM.Common.InitData.GetEmployeesLookRightEids(Session["LoginID"].ToString(), Session["CID"].ToString());
        ClientBasic clientBasic = new ClientBasic();

        GridView1.DataSource = clientBasic.GetClientBasicByConditions(eids, txtClientName.Text.Trim(), txtCantactName.Text.Trim(), ddlProvince.SelectedValue.ToString(), ddlCity.SelectedValue.ToString(), ddlSales.SelectedValue.ToString(), ddlClientType.SelectedValue.ToString(), ddlClientPhase.SelectedValue.ToString(), ddlClientStatus.SelectedValue.ToString(), ddlClientRank.SelectedValue.ToString(), ddlClientIndustry.SelectedValue.ToString());
        GridView1.DataKeyNames = new string[] { "id", "客户阶段", "客户类型" };
        GridView1.DataBind();
    }
    public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (null != RowCommand)
        {
            _ClientID = GridView1.SelectedIndex.ToString();
            _CommandName = e.CommandName;
            RowCommand(this, e);
        }
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridViewRow rowHeader = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
            rowHeader.BackColor = System.Drawing.Color.FromName("#C1D9F3");
            rowHeader.Font.Bold = true;


            TableCellCollection cells = e.Row.Cells;
            TableCell headerCell = new TableCell();
            headerCell.ColumnSpan = cells.Count;
            headerCell.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Left;
            rowHeader.Cells.Add(headerCell);
            rowHeader.Visible = true;

            //Button btnDel = new Button();
            //btnDel.Text = "删除客户";
            //btnDel.CommandName = "DEL";
            //rowHeader.Cells[0].Controls.Add(btnDel);

            //Button btnAdd = new Button();
            //btnAdd.Text = "增加客户";
            //btnAdd.CommandName = "ADD";
            //rowHeader.Cells[0].Controls.Add(btnAdd);

            //HyperLink Import = new HyperLink();
            //Import.NavigateUrl = "../../Pages/Client/ClientUpload.aspx";
            //Import.Text = "批量导入";
            //rowHeader.Cells[0].Controls.Add(Import);

            GridView1.Controls[0].Controls.AddAt(0, rowHeader);
            //GridView1.Controls[0].Controls.RemoveAt(0);
        }
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        Bind();
    }
    public void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (null != SelectedIndexChanged)
        {
            //_ClientID = GridView1.SelectedIndex.ToString();
            _ClientName = GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text;
            SelectedIndexChanged(this, e);
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex > -1)
        {
            string tmp = e.Row.Cells[2].Text;
            if (tmp.Length > 10)
                e.Row.Cells[1].Text = tmp.Substring(0, 10) + "...";
        }
    }

    public void GridView1_DataBound(object sender, EventArgs e)
    {
        //((CheckBox)headerRow.FindControl("CheckBox1")).Text = GridView1.Controls[0].Controls[0].Controls[0].Visible.ToString();
        //((Button)GridView1.Controls[0].FindControl("DEL")).Visible = false;
        //GridView1.Controls[0].Controls[0].Controls[0].Controls[0].Visible=false;
        //GridView1.Controls[0].Controls[0].Visible = false;
        //if (null != RowDataBound)
        //{
        //    RowDataBound(this, e);
        //}
        GridView gridview = (GridView)sender;
        if (gridview.Rows.Count > 0)
        {
            for (int j = 0; j < gridview.Rows.Count; j++)
            {
                DropDownList ddl1 = (DropDownList)gridview.Rows[j].FindControl("DropDownList1");

                ddl1.Items.Clear();
                ddl1.Items.Add(new ListItem("请选择", "-1"));
                System.Data.DataTable dtClientPhase = CRM.Common.InitData.InitData_ClientPhase(Session["CID"].ToString());
                if (dtClientPhase.Rows.Count > 0)
                {
                    for (int i = 0; i < dtClientPhase.Rows.Count; i++)
                    {
                        ddl1.Items.Add(new ListItem(dtClientPhase.Rows[i]["客户阶段"].ToString(), dtClientPhase.Rows[i]["id"].ToString()));
                    }
                }
                ddl1.SelectedValue = gridview.DataKeys[j].Values["客户阶段"].ToString();

                DropDownList ddl2 = (DropDownList)gridview.Rows[j].FindControl("DropDownList2");
                ddl2.Items.Clear();
                ddl2.Items.Add(new ListItem("请选择", "-1"));
                System.Data.DataTable dtClientType = CRM.Common.InitData.InitData_ClientType(Session["CID"].ToString());
                if (dtClientType.Rows.Count > 0)
                {
                    for (int i = 0; i < dtClientType.Rows.Count; i++)
                    {
                        ddl2.Items.Add(new ListItem(dtClientType.Rows[i]["客户类型"].ToString(), dtClientType.Rows[i]["id"].ToString()));
                    }
                }

                ddl2.SelectedValue = gridview.DataKeys[j].Values["客户类型"].ToString();
            }
        }

    }

    //public void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) {
    //    if (null != SelectedIndexChanging) {
    //        SelectedIndexChanging(this,e);
    //    }
    //}
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = e.RowIndex;
        ClientBasic clientBasic = new ClientBasic();
        clientBasic.ClientBasicDeleteById(GridView1.DataKeys[index].Values["id"].ToString());

        Bind();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Bind();
    }
    protected void ClientList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //string id = ClientList1.ClientID;
        //RegisterClientScriptBlock("ClientInfo", "<script language=javascript>location.href='/Pages/Client/ClientInfo.aspx?ClientID=" + id + "';</script>");
    }
    protected void ClientList1_RowCommand(object sender, EventArgs e)
    {

        //新增客户
        //if (ClientList1.CommandName == "ADD")
        //{
        //    RegisterClientScriptBlock("ADD", "<script language=javascript>location.href='/Pages/Client/ClientInfo.aspx';</script>");
        //}
        //#region 删除客户 只有本人才可以删除客户资料
        //if (ClientList1.CommandName == "DEL") {
        //    for (int i = 0; i < ((GridView)ClientList1.FindControl("GridView1")).Rows.Count; i++) {
        //        CheckBox cb=(CheckBox)(((GridView)ClientList1.FindControl("GridView1")).Rows[i].FindControl("CheckBox2"));
        //        if(cb.Checked==true){
        //            string id = ((GridView)ClientList1.FindControl("GridView1")).DataKeys[i].Values["id"].ToString();
        //            IList<ClientBasicInfo> clientbasicinfo = new List<ClientBasicInfo>();

        //            ClientBasic clientBasic = new ClientBasic();
        //            clientbasicinfo = clientBasic.GetClientBasicById(id);

        //            if (clientbasicinfo.Count > 0)
        //            {
        //                if (clientbasicinfo[0].业务员.ToString() == Session["LoginID"].ToString())
        //                {
        //                    //ClientBasic clientBasic = new ClientBasic();
        //                    clientBasic.ClientBasicDeleteById(id);
        //                }                        
        //            }

        //        }
        //    }
        //    ClientList1.Bind();

        //}
        //#endregion
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        CRM.Common.Login.IsLogin();
        if (!IsPostBack)
        {
            Init_Data();//注意顺序
            Bind();
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
            string[] eids = CRM.Common.InitData.GetEmployeesLookRightEids(Session["LoginID"].ToString(), Session["CID"].ToString());
            ClientBasic clientBasic = new ClientBasic();

            IList<ClientBasicInfo> clientbasicinfos = clientBasic.GetClientBasicByConditions(eids, txtClientName.Text.Trim(), txtCantactName.Text.Trim(), ddlProvince.SelectedValue.ToString(), ddlCity.SelectedValue.ToString(), ddlSales.SelectedValue.ToString(), ddlClientType.SelectedValue.ToString(), ddlClientPhase.SelectedValue.ToString(), ddlClientStatus.SelectedValue.ToString(), ddlClientRank.SelectedValue.ToString(), ddlClientIndustry.SelectedValue.ToString());
            
            //查询帐户余额
            string price="select top 1 price from 短信价格表";
            string sql2 = "select top 1 * from 客户余额表 where 充值状态=1 and eid=" + Session["LoginID"].ToString()+" order by id desc";
            System.Data.DataTable dt = SqlHelper.ExecuteDataSet(SqlHelper.connstr,CommandType.Text,sql2,null).Tables[0];
            if (dt.Rows.Count > 0)
            {
                if (decimal.Parse(dt.Rows[0]["可用余额"].ToString()) < clientbasicinfos.Count * decimal.Parse(SqlHelper.ExecuteScalar(SqlHelper.connstr, CommandType.Text, price, null).ToString()))
                {
                    RegisterClientScriptBlock("", "<script language=javascript>alert('帐户可用余额不足，请充值!');</script>");
                    return;
                }
            }
            else {
                RegisterClientScriptBlock("", "<script language=javascript>alert('帐户可用余额不足，请充值!');</script>");
                return;
            }


            if (TextBox1.Text.Trim().Length > 70 || TextBox2.Text.Trim().Length > 70) {
                RegisterClientScriptBlock("", "<script language=javascript>alert('短信文本与语音文本长度限定在70个字符内!');</script>");
                return;
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int j = 0; j < clientbasicinfos.Count; j++)
            {
                sb = sb.Append(clientbasicinfos[j].客户名称.ToString() + " ");
                sb = sb.Append(clientbasicinfos[j].主联系人.ToString() + " ");
                sb = sb.Append(clientbasicinfos[j].客户电话.ToString());
                sb = sb.Append("\r\n");
            }

            string filename = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + DateTime.Now.Millisecond + "-" + Session["LoginID"].ToString() + ".txt";

            string filePath = Server.MapPath("../../Files/") + filename;
            //System.IO.FileStream fr = new FileStream(filePath, FileMode.OpenOrCreate);
            System.IO.StreamWriter sr = new StreamWriter(filePath,false,Encoding.Default);
            sr.Write(sb.ToString());
            sr.Close();
            //fr.Close();

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


            //Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
            try
            {
                //object missing = System.Reflection.Missing.Value;
                //Microsoft.Office.Interop.Excel._Workbook xBk;      //工作薄 
                //Microsoft.Office.Interop.Excel._Worksheet xSt;      //工作Sheet   

                //xBk = myExcel.Workbooks.Add(true);
                //xSt = (Microsoft.Office.Interop.Excel._Worksheet)myExcel.ActiveSheet;
                //xSt.Name = "Sheet1";

                //myExcel.Cells[1, 1] = "客户编号";
                //myExcel.Cells[1, 2] = "联系手机";
                //for (int i = 0; i < clientbasicinfos.Count; i++)
                //{
                //    myExcel.Cells[i + 2, 1] = Session["LoginID"].ToString();
                //    myExcel.Cells[i + 2, 2] = clientbasicinfos[i].联系手机.ToString();
                //}

                //myExcel.Sheets.Add(missing, missing, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);

                //filename = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + DateTime.Now.Millisecond + "-" + Session["LoginID"].ToString() + ".xls";

                //string SaveUml = filePath;
                //myExcel.Visible = false;
                //if (File.Exists(SaveUml))
                //    System.IO.File.Delete(SaveUml);
                ////xBk.SaveAs(SaveUml, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared,                 missing, missing, missing, missing, missing);
                ////myExcel.Save(@"d:cms.xls");
                //myExcel.Quit();
                //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
                //GC.Collect();

                //提交
                string sql = "insert into 呼叫表(eid,语音文本,短信文本,语音文件,呼叫号码,未发送) values(@eid,@语音文本,@短信文本,@语音文件,@呼叫号码,@未发送)";
                SqlParameter[] paras = new SqlParameter[6];
                paras[0] = new SqlParameter("eid", Session["LoginID"].ToString());
                paras[1] = new SqlParameter("语音文本",TextBox1.Text.Trim());
                paras[2] = new SqlParameter("短信文本",TextBox2.Text.Trim());
                paras[5] = new SqlParameter("语音文件", "Files/audio/"+filename2);
                paras[3] = new SqlParameter("呼叫号码", "Files/" + filename);
                paras[4] = new SqlParameter("未发送",clientbasicinfos.Count);
                SqlHelper.ExecuteNonQuery(SqlHelper.connstr,CommandType.Text,sql,paras);

                //修改可用余额，绑定金额
                

                string sql3 = "update 客户余额表 set 可用余额=(可用余额-" + clientbasicinfos.Count * decimal.Parse(SqlHelper.ExecuteScalar(SqlHelper.connstr, CommandType.Text, price, null).ToString())+") where id=(select top 1 id from 客户余额表 where eid="+Session["LoginID"].ToString()+" order by id desc)";
                SqlHelper.ExecuteNonQuery(SqlHelper.connstr, CommandType.Text, sql3, null);


                RegisterClientScriptBlock("", "<script language=javascript>alert('提交成功，请注意处理过程!');</script>");

            }
            catch
            {
                //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
                //GC.Collect();
                RegisterClientScriptBlock("", "<script language=javascript>alert('错误!');</script>");
            }
            finally
            {
                //释放ExcelCOM资源，必须执行，否则EXECL进程不会自动释放
                //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
                //GC.Collect();
            }

            Bind();

    }

    private void ExeclOut(System.Data.DataTable dt, string filePath)
    {
        Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
        try
        {
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel._Workbook xBk;      //工作薄 
            Microsoft.Office.Interop.Excel._Worksheet xSt;      //工作Sheet   

            xBk = myExcel.Workbooks.Add(true);

            xSt = (Microsoft.Office.Interop.Excel._Worksheet)xBk.ActiveSheet;
            xSt.Name = "Sheet1";

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 1; j < dt.Columns.Count; j++)
                {
                    myExcel.Cells[i + 2, j] = dt.Rows[i][j];
                }
            }

            myExcel.Sheets.Add(missing, missing, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);

            string SaveUml = filePath;
            myExcel.Visible = true;
            if (File.Exists(SaveUml))
                System.IO.File.Delete(SaveUml);
            xBk.SaveAs(SaveUml, missing, missing,
             missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared,
             missing, missing, missing, missing, missing);
            //myExcel.Save(@"d:cms.xls");
            myExcel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
            GC.Collect();
        }
        catch
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
            GC.Collect();
            RegisterClientScriptBlock("", "<script language=javascript>alert('错误!');</script>");
        }
        finally
        {
            //释放ExcelCOM资源，必须执行，否则EXECL进程不会自动释放
            System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
            GC.Collect();
        }
    }

}
