using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;

namespace HySoft.BaseCallCenter.Web.reportmanage.callreports
{
    public partial class teletraffic : System.Web.UI.Page
    {
        protected string TableHtml = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            OutputTable();
        }
        private void OutputTable()
        {
            //查询条件
            string starttime = txtStartTime.Text.Trim();
            string endtime = txtEndTime.Text.Trim();
            if (string.IsNullOrWhiteSpace(starttime)) { starttime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd"); txtStartTime.Text = starttime; }
            if (string.IsNullOrWhiteSpace(endtime)) { endtime = DateTime.Today.ToString("yyyy-MM-dd"); txtEndTime.Text = endtime; }

            string tabletitle = "话务KPI数据分析报表";
            string[] tablehead = new string[] { "分类", "数量", "占有率" };
            TableHtml = createTable(tabletitle, tablehead, starttime, endtime);
        }
        private string createTable(string title, string[] head, string starttime, string endtime)
        {
            StringBuilder sb = new StringBuilder();
            //表名称
            sb.Append(createTableTitle(title));
            //表列名
            sb.Append("<table border='0' cellpadding='0' cellspacing='0' width='100%' align='center'>");
            sb.Append(createTableHead(head));
            //表内容
            sb.Append(createTableBody(starttime, endtime));
            sb.Append("</table>");
            return sb.ToString();
        }
        /// <summary>
        /// 表名称
        /// </summary>
        /// <param name="title">表名</param>
        /// <returns></returns>
        protected string createTableTitle(string title)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<h1 style='font-size: 18px; font-weight: bold; color: #333333; text-align: center;width: 100%;'><b>" + title + "</b></h1>");
            return sb.ToString();
        }
        /// <summary>
        /// 表头（表列名）
        /// </summary>
        /// <param name="head"></param>
        /// <returns></returns>
        protected string createTableHead(string[] head)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<tr class=\"formtabletitle1\" style=\"height: 25px;background-color: #D5EDFE;border-left: 1px solid #CCCCCC;border-right: 1px solid #CCCCCC;border-top: 1px solid #CCCCCC;border-bottom: 1px solid #CCCCCC;padding: 3px 3px 3px 3px;text-align:center;\">");
            for (int i = 0; i < head.Length; i++)
            {
                if (i == 0) sb.Append("<td colspan=\"2\" class=\"formtabletitle1\" style=\"height: 25px;background-color: #D5EDFE;border-left: 1px solid #CCCCCC;border-right: 1px solid #CCCCCC;border-top: 1px solid #CCCCCC;border-bottom: 1px solid #CCCCCC;padding: 3px 3px 3px 3px;text-align:center;\">" + head[i] + "</td>");
                else sb.Append("<td class=\"formtabletitle1\" style=\"height: 25px;background-color: #D5EDFE;border-left: 1px solid #CCCCCC;border-right: 1px solid #CCCCCC;border-top: 1px solid #CCCCCC;border-bottom: 1px solid #CCCCCC;padding: 3px 3px 3px 3px;text-align:center;\">" + head[i] + "</td>");
            }
            sb.Append("</tr>");
            return sb.ToString();
        }
        /// <summary>
        /// 表体（内容）
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        private string createTableBody(string starttime, string endtime)
        {
            //存储数据
            Dictionary<string, List<List<string>>> body = new Dictionary<string, List<List<string>>>();
            //string sqlwhere = string.Format("UserId={0} AND CallState=1 AND CallType=0 AND EndTime>='{1}' AND EndTime<'{2}'", userid, starttime, endtime);//接通的呼入电话
            //这段时间的电话记录
            string sqlwhere = string.Format("EndTime>='{0}' AND EndTime<'{1}'", starttime + " 00:00:00", endtime + " 23:59:59");
            DataTable dtable = new BLL.T_Call_CallRecords().GetList(sqlwhere).Tables[0];
            int allcount = dtable.Rows.Count;
            #region 业务电话量
            string[] CP1 = getCountAndPercent(dtable, -1, 0);
            string[] CP2 = getCountAndPercent(dtable, -1, 1);
            string[] CP3 = getCountAndPercent(dtable, 1, 0);
            string[] CP4 = getCountAndPercent(dtable, 0, 0);
            if (CP1[0] != "" && CP1[0] != "0")
            {
                body.Add("业务电话量", new List<List<string>>() { 
                new List<string>() { "呼入项目占有率", CP1[0], CP1[1] } ,
            new List<string>() { "呼出项目占有率", CP2[0], CP2[1] },
            new List<string>() { "呼入接通率", CP3[0],(Convert.ToDouble( CP3[0])/Convert.ToDouble(CP1[0])*100).ToString("f2")+"%"},
            new List<string>() { "呼入未接通率", CP4[0], (Convert.ToDouble( CP4[0])/Convert.ToDouble(CP1[0])*100).ToString("f2")+"%" },
            new List<string>() { "合计(总电话量)：", allcount.ToString(), "100.00%" }
            }
               );
            }
            else
            {
                body.Add("业务电话量", new List<List<string>>() { 
                new List<string>() { "呼入项目占有率", CP1[0], CP1[1] } ,
            new List<string>() { "呼出项目占有率", CP2[0], CP2[1] },
            new List<string>() { "呼入接通率", CP3[0], "0.00%" },
            new List<string>() { "呼入未接通率", CP4[0], "0.00%" },
            new List<string>() { "合计(总电话量)：", allcount.ToString(), "100.00%" }
            }
                );
            }
            #endregion
            
            #region 回访满意度
            //这段时间已完成的报修工单
            string sql = string.Format("SELECT F_INSTANCEID FROM T_Wo_WorkOrderBase WHERE F_WORKORDERSTATEID=0 and F_WORKORDERTYPEID={0}", 16);//16为报修
            if (starttime != "")
            {
                sql += " AND F_STARTTIME>='" + starttime + " 00:00:00'";
            }
            if (endtime != "")
            {
                sql += " AND F_ENDTIME<='" + endtime + " 23:59:59'";
            }
            int HFallcount = DBUtility.DbHelperSQL.Query("SELECT * FROM T_Wo_WorkOrderHistory INNER JOIN T_Wo_WorkOrderHistoryInfo ON T_Wo_WorkOrderHistory.F_HISTORYID = T_Wo_WorkOrderHistoryInfo.F_HISTORYID WHERE T_Wo_WorkOrderHistory.F_WORKORDERSTATEID=8 and T_Wo_WorkOrderHistory.F_INSTANCEID in (" + sql + ") ").Tables[0].Rows.Count;
            List<List<string>> bodyvalues = new List<List<string>>();
            double counts = 0;
            for (int i = 0; i < 4; i++)
            {
                string[] MYD = { "非常满意", "满意", "不满意", "未评价" };
                string[] MYDCP = getHFMYDCountAndPercent(HFallcount, sql, i + 1);
                if (i == 3)
                {
                    bodyvalues.Add(new List<string>() { MYD[i], (HFallcount - counts).ToString(), ((Convert.ToDouble(HFallcount) - counts) / Convert.ToDouble(HFallcount)*100).ToString("f2")+"%" });
                }
                else
                {
                    counts += Convert.ToDouble(MYDCP[0]);
                    bodyvalues.Add(new List<string>() { MYD[i], MYDCP[0], MYDCP[1] });
                }
            }
            bodyvalues.Add(new List<string>() { "合计(总回访数)：", HFallcount.ToString(), "100.00%" });
            body.Add("回访满意度", bodyvalues);
            #endregion

            #region 服务水平
            string time = "20";
            string sqltime = "select * from T_Sys_DictionaryValue where F_DictionaryFlag='fwsp'";
            DataTable dttime = DBUtility.DbHelperSQL.Query(sqltime).Tables[0];
            if (dttime.Rows.Count > 0)
            {
                time = dttime.Rows[0]["F_Name"].ToString();
            }
            string[] CP20s1 = get20sCountAndPercent(dtable, true,time);
            string[] CP20s2 = get20sCountAndPercent(dtable, false, time);
            body.Add("服务水平", new List<List<string>>() { new List<string>() { time+"秒内应答",CP20s1[0],CP20s1[1] },
            new List<string>() { "非"+time+"秒内应答",CP20s2[0],CP20s2[1] },new List<string>() { "合计(总服务量)：",CP20s1[2],CP20s1[3] }}); 
            #endregion

            #region 话务平均时间
            body.Add("话务平均时间", new List<List<string>>() { new List<string>() { "平均排队时间(秒)", getAverageTime(allcount, "WaitLongTime", starttime, endtime),"" },
            new List<string>() { "平均振铃时间(秒)", getAverageTime(allcount, "RingLongTime", starttime, endtime),"" },
            new List<string>() { "平均通话时间(秒)", getAverageTime(allcount, "TalkLongTime", starttime, endtime),"" }}); 
            #endregion

            body.Add("工单平均时间", new List<List<string>>() { new List<string>() { "平均处理时间(小时)", getSumCountAndAverage(starttime, endtime, 16)[3], "" } });

            #region 一次解决率
            body.Add("一次解决率", new List<List<string>>() { new List<string>() { "已关闭并已解决工单数/已关闭工单数*100%", "", getDealWithPercent(HFallcount, sql) } });
            #endregion

            StringBuilder sb = new StringBuilder();
            #region 打印表格
            foreach (var key in body.Keys)
            {
                int count = body[key].Count;
                bool bb = true;
                foreach (var values in body[key])
                {
                    sb.Append("<tr style=\"text-align: center;\" onmouseover=\"this.style.backgroundColor='#F6F6F6'\" onmouseout=\"this.style.backgroundColor='#ffffff'\">");
                    if (bb)
                    {
                        sb.Append("<td rowspan=\"" + count + "\" class=\"formtabletitle1\"style=\"height: 25px;background-color: #fff;border-left: 1px solid #CCCCCC;border-right: 1px solid #CCCCCC;border-top: 1px solid #CCCCCC;border-bottom: 1px solid #CCCCCC;padding: 3px 3px 3px 3px;text-align:center;\">" + key + "</td>");
                        bb = false;
                    }
                    if (key == "平均时间" || key == "解决率")
                    {
                        int c = values.Count;
                        for (int i = 0; i < c; i++)
                        {
                            sb.Append("<td class=\"formtabletitle1\"style=\"height: 25px;background-color: #fff;border-left: 1px solid #CCCCCC;border-right: 1px solid #CCCCCC;border-top: 1px solid #CCCCCC;border-bottom: 1px solid #CCCCCC;padding: 3px 3px 3px 3px;text-align:center;\">" + values[i] + "</td>");
                        }
                    }
                    else
                    {
                        foreach (var value in values)
                        {
                            sb.Append("<td class=\"formtabletitle1\"style=\"height: 25px;background-color: #fff;border-left: 1px solid #CCCCCC;border-right: 1px solid #CCCCCC;border-top: 1px solid #CCCCCC;border-bottom: 1px solid #CCCCCC;padding: 3px 3px 3px 3px;text-align:center;\">" + value + "</td>");
                        }
                    }
                    sb.Append("</tr>");
                }
            } 
            #endregion
            return sb.ToString();
        }
        /// <summary>
        /// 业务电话量   每种类型的数量和百分比
        /// </summary>
        /// <param name="dtable"></param>
        /// <param name="state"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private string[] getCountAndPercent(DataTable dtable, int state, int type)
        {
            string sqlwhere = "";
            if (type < 0 && state >= 0) sqlwhere = "CallState=" + state;
            if (type >= 0 && state < 0) sqlwhere = "CallType=" + type;
            if (type >= 0 && state >= 0) sqlwhere = string.Format("CallState={0} AND CallType={1}", state, type);
            int allcount = dtable.Rows.Count;
            int count = dtable.Select(sqlwhere).Count();
            string percent = "0.00%";
            if (allcount > 0) percent = (count * 100.0 / allcount).ToString("0.00") + "%";
            string[] resarr = new string[2];
            resarr[0] = count.ToString();
            resarr[1] = percent;
            return resarr; 
        }
        /// <summary>
        /// 满意度    每种类型的数量和百分比
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private string[] getMYDCountAndPercent(DataTable dt, int type)
        {
            int allcount = dt.Rows.Count;
            int typecount = 0;
            if (type == 4) typecount = dt.Select("MYD IS NULL").Count();
            else typecount = dt.Select("MYD=" + type).Count();
            string percent = "0.00%";
            if (allcount > 0) percent = (typecount * 100.0 / allcount).ToString("0.00") + "%";
            return new string[] { typecount.ToString(), percent };
        }
        /// <summary>
        /// 回访满意度
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private string[] getHFMYDCountAndPercent(int allcount, string sql, int type)
        {
            int typecount = 0;
            string percent = "0.00%";
            //F_WORKORDERSTATEID状态为8 待回访    //F_INSTANCEID 工单实例ID
            //string sqlwhere = string.Format("F_WORKORDERSTATEID=8 AND F_INSTANCEID={0}",dt.Rows)
            string sqlcount = "SELECT COUNT(*) FROM T_Wo_WorkOrderHistory INNER JOIN T_Wo_WorkOrderHistoryInfo ON T_Wo_WorkOrderHistory.F_HISTORYID = T_Wo_WorkOrderHistoryInfo.F_HISTORYID WHERE T_Wo_WorkOrderHistory.F_WORKORDERSTATEID=8 and T_Wo_WorkOrderHistory.F_INSTANCEID in (" + sql + ") ";
            switch (type)
            {
                case 1:
                    sqlcount += "AND T_Wo_WorkOrderHistoryInfo.F_CUSTOMERSCORE IN ('9','10','100')";
                    break;
                case 2:
                    sqlcount += "AND T_Wo_WorkOrderHistoryInfo.F_CUSTOMERSCORE IN ('7','8')";
                    break;
                case 3:
                    sqlcount += "AND T_Wo_WorkOrderHistoryInfo.F_CUSTOMERSCORE IN ('0','1','2','3','4','5','6')";
                    break;
                default:
                    sqlcount += "AND T_Wo_WorkOrderHistoryInfo.F_CUSTOMERSCORE NOT IN ('0','1','2','3','4','5','6','7','8','9','10','100')";
                    break;
            }
            DataTable dt = DBUtility.DbHelperSQL.Query(sqlcount).Tables[0];
            int.TryParse(dt.Rows[0][0].ToString(), out typecount);
            if (allcount > 0) percent = (typecount * 100.0 / allcount).ToString("0.00") + "%";
            return new string[] { typecount.ToString(), percent };
        }
        /// <summary>
        /// 服务水平   20秒之内接通的数量和百分比
        /// </summary>
        /// <param name="dtable"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        private string[] get20sCountAndPercent(DataTable dtable, bool b,string time)
        {
            DataRow[] drarr = dtable.Select("CallState=1 AND CallType=0");
            int count = 0;
            int s20 = 0;
            string percent = "0.00%";
            if (drarr.Count() > 0)
            {
                DataTable dt = drarr.CopyToDataTable();
                count = dt.Rows.Count;
                s20 = 0;
                if (b) s20 = dt.Select("RingLongTime<=" + time).Count();
                else s20 = dt.Select("RingLongTime>"+time).Count();
                if (count > 0) percent = (s20 * 100.0 / count).ToString("0.00") + "%";
                return new string[] { s20.ToString(), percent, count.ToString(), "100%" };
            }
            else return new string[] { s20.ToString(), percent, count.ToString(), "100%" };
        }
        /// <summary>
        /// 平均时间  每种平均时间
        /// </summary>
        /// <param name="count"></param>
        /// <param name="type"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        private string getAverageTime(int count, string type, string starttime, string endtime)
        {
            string sqlwhere = string.Format("SELECT SUM([{0}]) FROM [T_Call_CallRecords] WHERE EndTime>='{1}' AND EndTime<'{2}'", type, starttime + " 00:00:00", endtime + " 23:59:59");
            DataTable dt = DBUtility.DbHelperSQL.Query(sqlwhere).Tables[0];
            int time = 0;
            int.TryParse(dt.Rows[0][0].ToString(), out time);
            string average = "0.00"; if (count > 0) average = (time / count).ToString("0.00");
            return average;
        }
        private string getDealWithPercent(int allcount, string sql)
        {
            int typecount = 0;
            string percent = "0.00%";
            string sqlcount = "SELECT COUNT(*) FROM T_Wo_WorkOrderHistory INNER JOIN T_Wo_WorkOrderHistoryInfo ON T_Wo_WorkOrderHistory.F_HISTORYID = T_Wo_WorkOrderHistoryInfo.F_HISTORYID WHERE T_Wo_WorkOrderHistory.F_WORKORDERSTATEID=8 AND T_Wo_WorkOrderHistory.F_INSTANCEID in (" + sql + ") ";

            sqlcount += "AND T_Wo_WorkOrderHistoryInfo.F_SOLVE='已解决'";

            DataTable dt = DBUtility.DbHelperSQL.Query(sqlcount).Tables[0];
            int.TryParse(dt.Rows[0][0].ToString(), out typecount);
            if (allcount > 0) percent = (typecount * 100.0 / allcount).ToString("0.00") + "%";
            return percent;
        }

        private List<string> getSumCountAndAverage(string starttime, string endtime, int type)
        {
            List<string> sum = new List<string>();
            sum.Add("合计：");
            string sql = string.Format("F_WORKORDERSTATEID=0 and F_WORKORDERTYPEID={0}", type);
            if (starttime != "")
            {
                sql += " AND F_STARTTIME>='" + starttime + " 00:00:00'";
            }
            if (endtime != "")
            {
                sql += " AND F_ENDTIME<='" + endtime + " 23:59:59'";
            }
            DataTable dtable = new BLL.T_Wo_WorkOrderBase().GetList(sql).Tables[0];
            //工单总数
            int allcount = dtable.Rows.Count;
            sum.Add(allcount.ToString());

            //工单总用时
            double alltime = 0.00;
            TimeSpan tstotal = new TimeSpan();
            for (int i = 0; i < dtable.Rows.Count; i++)
            {
                DateTime dtstart = new DateTime();
                DateTime dtend = new DateTime();
                if (DateTime.TryParse(dtable.Rows[i]["F_ENDTIME"].ToString(), out dtend) && DateTime.TryParse(dtable.Rows[i]["F_STARTTIME"].ToString(), out dtstart))
                {
                    TimeSpan ts = (TimeSpan)(dtend - dtstart);
                    tstotal += ts;
                }
            }
            alltime = tstotal.TotalSeconds;
            sum.Add(alltime.ToString("0.00"));
            //平均用时
            double average = 0.00;
            if (alltime > 0) average = alltime / allcount;
            sum.Add(average.ToString("0.00"));
            ////工单每个状态的总用时及平均用时
            //int[] state = new int[] { 4, 6, 7, 8, 9 };
            //for (int j = 0; j < state.Length; j++)
            //{
            //    double l = 0.00;
            //    double p = 0.00;
            //    for (int i = 0; i < dtable.Rows.Count; i++)
            //    {
            //        string sqlwhere = string.Format("SELECT SUM([F_ELAPSEDTIME]) FROM [XKP_CallCenter].[dbo].[T_Wo_WorkOrderHistory] WHERE [F_WORKORDERSTATEID]='{0}' AND [F_INSTANCEID]='{1}'", state[j], dtable.Rows[i]["F_INSTANCEID"].ToString());
            //        DataTable dtb = DBUtility.DbHelperSQL.Query(sqlwhere).Tables[0];
            //        double m = 0.00;
            //        double.TryParse(dtb.Rows[0][0].ToString(), out m);
            //        l += m;
            //    }
            //    if (allcount > 0) p = l / allcount;
            //    sum.Add(l.ToString("0.00"));
            //    sum.Add(p.ToString("0.00"));
            //}
            dtable.Dispose();
            for (int item = 0; item < sum.Count; item++)
            {
                if (item == 0 || item == 1) continue;
                else sum[item] = GetTimeInfo(sum[item]);
            }
            return sum;
        }
        /// <summary>
        /// 把秒转化成小时
        /// </summary>
        /// <param name="times">秒</param>
        /// <returns></returns>
        public string GetTimeInfo(string times)
        {
            string res = "";
            try
            {
                double d = Convert.ToDouble(times);
                res = (d / 3600).ToString("0.00");
            }
            catch
            { }
            return res;
        }
        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            OutputTable();
        }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            string fileName = "话务KPI数据分析报表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            Response.Clear();
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
            Response.ContentType = "application/ms-excel";
            Response.Write(TableHtml);
            Response.End();
        }
    }
}