using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.County
{
    public class CountyTelController : BaseController
    {
        // GET: CountyTel

        /// <summary>
        /// 获取通话记录列表
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="usercode"></param>
        /// <returns></returns>
        public ActionResult GetAreaTelList(string branchcode)
        {


            int roleid = Utils.StrToInt(User.UserData["F_RoleID"], 0);
            string phone = HttpUtility.UrlDecode(RequestString.GetQueryString("phone"));
            string usercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string callstate = HttpUtility.UrlDecode(RequestString.GetQueryString("callstate"));
            string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            int type = RequestString.GetInt("type", 0);

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            if (branchcode == "sqs12345")
            {
                string sql = "";
                DataTable dt = new DataTable();

                if (type != 0)
                {
                    sql += " and F_CallInType = '" + type + "' ";
                }
                if (usercode != null && usercode.Trim() != "")
                {
                    sql += " and UserCode='" + usercode + "'";
                }

                if (phone != null && phone.Trim() != "")
                {
                    sql += " and CallNumber like '%" + phone + "%'";
                }
                if (callstate.Trim() != "")
                {
                    if (callstate.Trim() == "0")
                    {
                        sql += " and CallState=0 and isnull(UserCode,'')!='' ";
                    }
                    else if (callstate.Trim() == "3")
                    {
                        sql += " and CallState=0 and CallType=0 and isnull(UserCode,'')='' ";
                    }
                    else
                    {
                        sql += " and CallState='" + callstate + "'";
                    }
                }
                if (calltype.Trim() != "")
                {
                    sql += " and CallType='" + calltype + "'";
                }
                if (starttime.Trim() != "")
                {
                    sql += " and datediff(day,BeginTime,'" + starttime + "')<=0 ";
                }
                if (endtime.Trim() != "")
                {
                    sql += " and datediff(day,BeginTime,'" + endtime + "')>=0 ";
                }

                if (strpageindex.Trim() != "")
                {
                    pageindex = Convert.ToInt32(strpageindex);
                }

                if (strpagesize.Trim() != "")
                {
                    pagesize = Convert.ToInt32(strpagesize);
                }
                int recordCount = 0;
                dt = BLL.PagerBLL.GetListPager(
                    "T_Call_CallRecords",
                    "CallRecordsId",
                    "*",
                    sql,
                    "ORDER BY CallRecordsId desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

                var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
                var users = new BLL.T_Sys_UserAccount().GetModelList("");
                dt.Columns.Add("TypeName", typeof(string));
                dt.Columns.Add("WorkOrderId", typeof(string));
                foreach (DataRow dr in dt.Rows)
                {
                    string path = dr["FilePath"] != null ? dr["FilePath"].ToString() : "";
                    if (path != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                    {
                        var ym = config.F_ParamValue;
                        if (ym.Substring(ym.Length - 1) == "/")
                        {
                            ym = ym.Substring(0, ym.Length - 1);
                        }
                        dr["FilePath"] = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                    }
                    string ucode = dr["UserCode"] != null ? dr["UserCode"].ToString() : "";
                    if (ucode != "")
                    {
                        var uu = users.Where(u => u.F_UserCode.Equals(ucode)).FirstOrDefault();
                        if (uu != null)
                            dr["UserName"] = uu.F_UserName;
                    }

                    if (dr["F_CallInType"] != null && dr["F_CallInType"].ToString() != "")
                    {
                        int tid = Int32.Parse(dr["F_CallInType"].ToString());
                        var tn = new BLL.T_Sys_DictionaryValue().GetModel(tid);
                        if (tn != null)
                        {
                            dr["TypeName"] = tn.F_Value;
                        }
                    }

                    var wo = new BLL.T_Bus_WorkOrder().GetModelList(" F_CallRecordId='" + dr["CallRecordsId"].ToString() + "' ").FirstOrDefault();
                    if (wo != null)
                    {
                        dr["WorkOrderId"] = wo.F_WorkOrderId;
                    }
                }

                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = dt,
                    total = recordCount
                };

                return Content(obj.ToJson());
            }
            else
            {
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = "",
                    total = 0
                };

                return Content(obj.ToJson());
            }
        }

        /// <summary>
        /// 座席话务量
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetAreaSeatTel(string branchcode, DateTime? start, DateTime? end, int isdc = 0)
        {

            if (start == null)
            {
                start = DateTime.Now;
                start = new DateTime(start.Value.Year, start.Value.Month, 1);
            }
            if (end == null)
            {
                end = DateTime.Now;
            }

            if (branchcode == "sqs12345")
            {
                Dictionary<string, string> paras = new Dictionary<string, string>();
                paras.Add("@sdate", start.Value.ToString("yyyy-MM-dd"));
                paras.Add("@edate", end.Value.ToString("yyyy-MM-dd"));
                var obj = DbHelperSQL.RunProcedure("P_AreaSeatTelReport", paras, "AreaSeatTelReport");
                if (isdc > 0)
                {
                    string[] cols = new string[] { "名称", "工号", "呼入量", "呼入接听量", "呼入接听率", "呼入接听时长", "平均呼入接听时长", "呼入呼损量", "呼入呼损率",
                    "呼出量", "呼出接听量", "呼出接听率", "呼出接听时长", "平均呼出接听时长", "呼出呼损量", "呼出呼损率" };
                    NPOIHelper npoi = new NPOIHelper();
                    if (npoi.ExportToExcel("座席话务量报表", obj.Tables[0], cols) == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Success("成功", obj);
            }
            else
            {
                var obj = new
                {
                    AreaSeatTelReport=""
                };
                return Success("成功", obj);
            }
        }

        /// <summary>
        /// 话务时日周月报
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAreaHDWMTelReport(string branchcode, string start, string end, int dateType = 1, int isdc = 0)
        {
            if (string.IsNullOrEmpty(start))
            {
                switch (dateType)
                {
                    case 1: start = DateTime.Now.ToString("yyyy-MM"); break;
                    case 2:
                        GregorianCalendar gc = new GregorianCalendar();
                        int weeks = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
                        start = DateTime.Now.ToString("yyyy") + "-w" + (weeks < 10 ? "0" + weeks.ToString() : weeks.ToString());
                        break;
                    case 3: start = DateTime.Now.ToString("yyyy-MM-dd"); break;
                    case 4: start = DateTime.Now.ToString("yyyy-MM-dd") + " 00"; break;
                }
            }
            if (string.IsNullOrEmpty(end))
            {
                switch (dateType)
                {
                    case 1: end = DateTime.Now.ToString("yyyy-MM"); break;
                    case 2:
                        GregorianCalendar gc = new GregorianCalendar();
                        int weeks = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
                        end = DateTime.Now.ToString("yyyy") + "-w" + (weeks < 10 ? "0" + weeks.ToString() : weeks.ToString());
                        break;
                    case 3: end = DateTime.Now.ToString("yyyy-MM-dd"); break;
                    case 4: end = DateTime.Now.ToString("yyyy-MM-dd HH"); break;
                }
            }
            if (branchcode == "sqs12345")
            {
                Dictionary<string, string> paras = new Dictionary<string, string>();
                paras.Add("@sdate", start);
                paras.Add("@edate", end);
                paras.Add("@datetype", dateType.ToString());
                var obj = DbHelperSQL.RunProcedure("P_AreaHDWMTelReport", paras, "AreaHDWMTelReport");
                if (isdc > 0)
                {
                    string[] cols = new string[] { "名称", "时间", "呼入量", "呼入接听量", "呼入接听率","呼入通话时长", "平均呼入通话时长", "呼入呼损量", "呼入呼损率",
                    "呼出量", "呼出接听量", "呼出接听率", "呼出通话时长", "平均呼出通话时长","呼出呼损量", "呼出呼损率" };
                    NPOIHelper npoi = new NPOIHelper();
                    if (npoi.ExportToExcel("话务量报表", obj.Tables[0], cols) == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Success("成功", obj);
            }
            else
            {
                var obj = new
                {
                    AreaHDWMTelReport = ""
                };
                return Success("成功", obj);
            }
        }

        /// <summary>
        /// 运营指标时日周月报
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAreaHDWMOpeTelReport(string branchcode, string start, string end, int dateType = 1, int isdc = 0)
        {

            if (string.IsNullOrEmpty(start))
            {
                switch (dateType)
                {
                    case 1: start = DateTime.Now.ToString("yyyy-MM"); break;
                    case 2:
                        GregorianCalendar gc = new GregorianCalendar();
                        int weeks = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
                        start = DateTime.Now.Date.ToString("yyyy") + "-w" + (weeks < 10 ? "0" + weeks.ToString() : weeks.ToString());
                        break;
                    case 3: start = DateTime.Now.ToString("yyyy-MM-dd"); break;
                    case 4: start = DateTime.Now.ToString("yyyy-MM-dd") + " 00"; break;
                }
            }

            if (string.IsNullOrEmpty(end))
            {
                switch (dateType)
                {
                    case 1: end = DateTime.Now.ToString("yyyy-MM"); break;
                    case 2:
                        GregorianCalendar gc = new GregorianCalendar();
                        int weeks = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
                        end = DateTime.Now.Date.ToString("yyyy") + "-w" + (weeks < 10 ? "0" + weeks.ToString() : weeks.ToString());
                        break;
                    case 3: end = DateTime.Now.ToString("yyyy-MM-dd"); break;
                    case 4: end = DateTime.Now.ToString("yyyy-MM-dd HH"); break;
                }
            }
            if (branchcode == "sqs12345")
            {
                Dictionary<string, string> paras = new Dictionary<string, string>();
                paras.Add("@sdate", start);
                paras.Add("@edate", end);
                paras.Add("@datetype", dateType.ToString());
                var obj = DbHelperSQL.RunProcedure("P_AreaHDWMOpeTelReport", paras, "AreaHDWMOpeTelReport");
                if (isdc > 0)
                {
                    string[] cols = new string[] { "名称", "时间", "呼入量", "呼入接听量", "呼入接听率", "20s接听量", "20s接听率", "呼入通话时长", "平均呼入通话时长",
                    "呼入振铃时长", "平均呼入振铃时长", "呼入呼损量", "呼入呼损率" };
                    NPOIHelper npoi = new NPOIHelper();
                    if (npoi.ExportToExcel("运营话务量报表", obj.Tables[0], cols) == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Success("成功", obj);
            }
            else
            {
                var obj = new
                {
                    AreaHDWMOpeTelReport = ""
                };
                return Success("成功", obj);
            }
        }

        /// <summary>
        /// 队列统计报表时日周月报
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAreaHDWMQueueTelReport(string branchcode, string start, string end, int dateType = 1, int isdc = 0)
        {
            if (string.IsNullOrEmpty(start))
            {
                switch (dateType)
                {
                    case 1: start = DateTime.Now.ToString("yyyy-MM"); break;
                    case 2:
                        GregorianCalendar gc = new GregorianCalendar();
                        int weeks = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
                        start = DateTime.Now.Date.ToString("yyyy") + "-w" + (weeks < 10 ? "0" + weeks.ToString() : weeks.ToString());
                        break;
                    case 3: start = DateTime.Now.ToString("yyyy-MM-dd"); break;
                    case 4: start = DateTime.Now.ToString("yyyy-MM-dd") + " 00"; break;
                }
            }
            if (string.IsNullOrEmpty(end))
            {
                switch (dateType)
                {
                    case 1: end = DateTime.Now.ToString("yyyy-MM"); break;
                    case 2:
                        GregorianCalendar gc = new GregorianCalendar();
                        int weeks = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
                        end = DateTime.Now.Date.ToString("yyyy") + "-w" + (weeks < 10 ? "0" + weeks.ToString() : weeks.ToString());
                        break;
                    case 3: end = DateTime.Now.ToString("yyyy-MM-dd"); break;
                    case 4: end = DateTime.Now.ToString("yyyy-MM-dd HH"); break;
                }
            }

            if (branchcode == "sqs12345")
            {
                Dictionary<string, string> paras = new Dictionary<string, string>();
                paras.Add("@sdate", start);
                paras.Add("@edate", end);
                paras.Add("@datetype", dateType.ToString());
                var obj = DbHelperSQL.RunProcedure("P_AreaHDWMQueueTelReport", paras, "AreaHDWMQueueTelReport");
                if (isdc > 0)
                {
                    string[] cols = new string[] { "名称", "时间", "呼入量", "呼入接听量", "呼入接听率",  "呼入通话时长", "平均呼入通话时长","最长通话时长", "最短呼入通话时长",
                    "呼入振铃时长", "平均呼入振铃时长", "呼入呼损量", "呼入呼损率" };
                    NPOIHelper npoi = new NPOIHelper();
                    if (npoi.ExportToExcel("队列统计报表", obj.Tables[0], cols) == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Success("成功", obj);
            }
            else
            {
                var obj = new
                {
                    AreaHDWMQueueTelReport = ""
                };
                return Success("成功", obj);
            }
        }

    }
}