using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.App_Start;
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
{
    [OutActionFilter]
    public class CountyTelController : BaseController
    {
        // GET: CountyTel

        /// <summary>
        /// 平台展示
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetAreaTodayTelShowReport(DateTime? date)
        {
            if (date == null)
            {
                date = DateTime.Now;
            }

            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@date", date.Value.ToString("yyyy-MM-dd"));
            var obj = DbHelperSQL.RunProcedure("P_AreaTodayTelShowReport", paras, "AreaTodayTelShowReport");

            return Success("成功", obj.Tables[0]);
        }

        /// <summary>
        /// 获取通话记录列表
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="usercode"></param>
        /// <returns></returns>
        public ActionResult GetAreaTelList(int isall = 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;

            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 (isall > 0)
            {
                string allsql = "select CallNumber,case calltype when 1 then '呼出' else '呼入' end CallType,"
                    + "case callstate when 0 then '未接通' when 1 then '已接通' when 2 then '黑名单拒接' else '-' end CallState,"
                    + "dbo.GetDictionaryName(F_CallInType) TypeName,UserCode,dbo.GetUserName(UserCode) UserName,"
                    + "BeginTime,TalkStartTime,TalkEndTime,TalkLongTime,RingLongTime,LongTime"
                    + " from  T_Call_CallRecords where 1=1 " + sql + " ORDER BY CallRecordsId desc";

                var dtall = DbHelperSQL.Query(allsql).Tables[0];
                return Content(dtall.ToJson());
            }

            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);
                    }
                    string lujing = path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                    string wlpath = ym + lujing;

                    //if (!CommonHelper.FileIsExist(wlpath))
                    //{
                    //    wlpath = lujing;
                    //}
                    dr["FilePath"] = wlpath;
                }
                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());
        }

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

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


            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");

            return Success("成功", obj.Tables[0]);
        }

        /// <summary>
        /// 话务时日周月报
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAreaHDWMTelReport(string start, string end, int dateType = 1)
        {
            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;
                }
            }

            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");

            return Success("成功", obj.Tables[0]);

        }

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

            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;
                }
            }

            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");

            return Success("成功", obj.Tables[0]);

        }

        /// <summary>
        /// 队列统计报表时日周月报
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAreaHDWMQueueTelReport(string start, string end, int dateType = 1)
        {
            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;
                }
            }

            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");

            return Success("成功", obj.Tables[0]);
        }

        /// <summary>
        /// 队列排队等待时长报表时日周月报
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAreaHDWMQueueWaitReport(string start, string end, int dateType = 1)
        {
            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;
                }
            }

            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_AreaHDWMQueueWaitReport", paras, "AreaHDWMQueueWaitReport");

            return Success("成功", obj.Tables[0]);
        }

        /// <summary>
        /// 网点今日话务量数据收集
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetAreaTodayTelReport(DateTime? date)
        {
            if (date == null)
            {
                date = DateTime.Now;
            }

            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@date", date.Value.ToString("yyyy-MM-dd"));
            var obj = DbHelperSQL.RunProcedure("P_AreaTodayTelReport", paras, "AreaTodayTelReport");

            return Success("成功", obj.Tables[0]);
        }

        /// <summary>
        /// 座席列表
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetAreaSeatList()
        {
            Dictionary<string, string> paras = new Dictionary<string, string>();
            var obj = DbHelperSQL.RunProcedure("P_AreaSeatListReport", paras, "AreaSeatListReport");

            return Success("成功", obj.Tables[0]);
        }

    }
}