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.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    public class IndexController : BaseController
    {
        private BLL.T_Sys_ModuleInfo moduleInfoBLL = new BLL.T_Sys_ModuleInfo();
        private BLL.T_Sys_RoleFunction roleFunctionBLL = new BLL.T_Sys_RoleFunction();

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMenu()
        {
            var roleId = CurrentUser.UserData.F_RoleId;
            var functionIdList = roleFunctionBLL.DataTableToList(roleFunctionBLL.GetList(" F_RoleId=" + roleId).Tables[0]).Select(x => x.F_FunctionId);
            var moduleInfoList = moduleInfoBLL.DataTableToList(moduleInfoBLL.GetList(" F_StateFlag=1 ").Tables[0]);
            moduleInfoList.Sort((x, y) => x.F_Sort - y.F_Sort);
            var authModuleFunctionList = moduleInfoList.Where(x => functionIdList.Contains(x.F_ModuleId)).ToList();
            return Success("获取符合权限的菜单", TreeRecursion(authModuleFunctionList));

        }

        private List<Model.T_Sys_ModuleInfo> TreeRecursion(List<Model.T_Sys_ModuleInfo> data, string parentId = "0")
        {
            List<Model.T_Sys_ModuleInfo> newList = new List<Model.T_Sys_ModuleInfo>();
            List<Model.T_Sys_ModuleInfo> item = data.FindAll(t => t.F_ParentID.ToString() == parentId);//data建议在调用此扩展方法前已经排序过
            if (item.Count > 0)
            {
                foreach (Model.T_Sys_ModuleInfo entity in item)
                {
                    entity.ChildNodes = TreeRecursion(data, entity.F_ModuleId.ToString());
                    newList.Add(entity);
                }
            }

            return newList;
        }

        /// <summary>
        /// 上传用户图片
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadTX()
        {
            int userId = CurrentUser.UserData.F_UserId;

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            string path = string.Empty;
            HttpPostedFile _upfile = RequestString.GetFile("upFile");
            if (_upfile != null)
            {
                //byte[] buffer = new Byte[(int)_upfile.InputStream.Length]; //声明文件长度的二进制类型
                //_upfile.InputStream.Read(buffer, 0, buffer.Length); //将文件转成二进制

                ImageUpload iu = new ImageUpload();
                iu.SavePath = "/Upload/ZXTX/";
                iu.PostFile = _upfile;
                iu.Upload();
                path = "/Upload/ZXTX/" + iu.OutFileName;

                userModel.F_See = path;
                new BLL.T_Sys_UserAccount().Update(userModel);

                return Success("成功", path);
            }
            else
            {
                return Error("请选择要上传的文件");
            }
        }

        /// <summary>
        /// 上传用户图片
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadTX64()
        {
            int userId = CurrentUser.UserData.F_UserId;
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            string path = string.Empty;

            string dataurl = HttpUtility.UrlDecode(RequestString.GetFormString("dataurl"));
            if (!string.IsNullOrEmpty(dataurl))
            {
                ImageUpload iu = new ImageUpload();
                iu.SavePath = "/Upload/ZXTX/";
                iu.DataUrl = dataurl;
                iu.Upload64();

                int n = iu.Error;
                if (n == 0)
                {
                    path = "/Upload/ZXTX/" + iu.OutFileName;

                    userModel.F_See = path;
                    new BLL.T_Sys_UserAccount().Update(userModel);

                    return Success("成功", path);
                }
                else
                {
                    string msg = string.Empty;
                    switch (n)
                    {
                        case 1: msg = "请选择要上传的文件"; break;
                        case 2: msg = "上传的文件类型不支持"; break;
                        case 3: msg = "上传的文件过大"; break;
                        case 4: msg = "未知错误"; break;
                    }
                    return Error(msg);
                }
            }
            else
            {
                return Error("请选择要上传的文件");
            }

        }

        /// <summary>
        /// 通话记录数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTelRecordsTotal()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            int roleid = CurrentUser.UserData.F_RoleId;

            var date = DateTime.Now;
            string strDate = date.ToString("yyyy-MM-dd");
            string strMonth = date.ToString("yyyy-MM");

            string uwhere = " 1=1 ";
            if (roleid != 17)
            {
                uwhere += " and UserCode='" + usercode + "' ";
            }

            BLL.T_Call_CallRecords bll = new BLL.T_Call_CallRecords();
            var dayinlist = bll.GetModelList(uwhere + " and CallType='0' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' and CallState='1' ");
            var dayoutlist = bll.GetModelList(uwhere + " and CallType='1' and CONVERT(varchar(10),BeginTime, 23)='" + strDate + "' and CallState='1' ");
            var moninlist = bll.GetModelList(uwhere + " and CallType='0' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' and CallState='1' ");
            var monoutlist = bll.GetModelList(uwhere + " and CallType='1' and CONVERT(char(7),BeginTime,20)='" + strMonth + "' and CallState='1' ");

            int daynocon = bll.GetList("CallType='0' and CONVERT(varchar(100),BeginTime, 23)='" + strDate + "' and CallState='0' ").Tables[0].Rows.Count;

            var obj = new
            {
                //dayin = new { count = dayinlist.Count, totaltime = dayinlist.Select(p => p.TalkLongTime).Sum() },
                //dayout = new { count = dayoutlist.Count, totaltime = dayoutlist.Select(p => p.TalkLongTime).Sum() },
                //monin = new { count = moninlist.Count, totaltime = moninlist.Select(p => p.TalkLongTime).Sum() },
                //monout = new { count = monoutlist.Count, totaltime = monoutlist.Select(p => p.TalkLongTime).Sum() },
                dayin = new { count = dayinlist.Count, totaltime = DateTimeConvert.parseTimeSeconds(int.Parse(dayinlist.Select(p => p.TalkLongTime).Sum().ToString()), 0) },
                dayout = new { count = dayoutlist.Count, totaltime = DateTimeConvert.parseTimeSeconds(int.Parse(dayoutlist.Select(p => p.TalkLongTime).Sum().ToString()), 0) },
                monin = new { count = moninlist.Count, totaltime = DateTimeConvert.parseTimeSeconds(int.Parse(moninlist.Select(p => p.TalkLongTime).Sum().ToString()), 0) },
                monout = new { count = monoutlist.Count, totaltime = DateTimeConvert.parseTimeSeconds(int.Parse(monoutlist.Select(p => p.TalkLongTime).Sum().ToString()), 0) },
                daynocon = daynocon
            };
            return Success("成功", obj);
        }
        /// <summary>
        /// 获取当月/当天的工单量(已完成，未完成)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkTotal()
        {
            int roleid = CurrentUser.UserData.F_RoleId;
            string usercode = CurrentUser.UserData.F_UserCode;

            var date = DateTime.Now;//DateTime.Parse("2015-04-14"); //
            string strDate = date.ToString("yyyy-MM-dd");
            string strMonth = date.ToString("yyyy-MM");

            //BLL.T_Wo_WorkOrderBase bll = new BLL.T_Wo_WorkOrderBase();
            //var list1 = bll.GetList(" F_USERID='" + userId + "' and CONVERT(varchar(10),F_CREATEDATE, 23)='" + strDate + "' and F_WORKORDERSTATEID in (0,8) ").Tables[0];
            //var list2 = bll.GetList(" F_USERID='" + userId + "' and CONVERT(varchar(10),F_CREATEDATE, 23)='" + strDate + "' and F_WORKORDERSTATEID in (4,5,6,7,9,12,13) ").Tables[0];
            //var list3 = bll.GetList(" F_USERID='" + userId + "' and CONVERT(char(7),F_CREATEDATE,20)='" + strMonth + "' and F_WORKORDERSTATEID in (0,8) ").Tables[0];
            //var list4 = bll.GetList(" F_USERID='" + userId + "' and CONVERT(char(7),F_CREATEDATE,20)='" + strMonth + "' and F_WORKORDERSTATEID in (4,5,6,7,9,12,13) ").Tables[0];

            string uwhere = " 1=1 ";
            if (roleid != 17)
            {
                uwhere += " and CreateUser='" + usercode + "' ";
            }

            BLL.T_Wo_WorkOrder bll = new BLL.T_Wo_WorkOrder();
            var list1 = bll.GetList(uwhere + " and CONVERT(varchar(10),CreateTime, 23)='" + strDate + "' and State =2 and IsDel=0 ").Tables[0];
            var list2 = bll.GetList(uwhere + " and CONVERT(varchar(10),CreateTime, 23)='" + strDate + "' and State in (0,1) and IsDel=0 ").Tables[0];
            var list3 = bll.GetList(uwhere + " and CONVERT(char(7),CreateTime,20)='" + strMonth + "' and State =2 and IsDel=0 ").Tables[0];
            var list4 = bll.GetList(uwhere + " and CONVERT(char(7),CreateTime,20)='" + strMonth + "' and State in (0,1) and IsDel=0 ").Tables[0];

            var obj = new
            {
                daywc = list1.Rows.Count,
                daywwc = list2.Rows.Count,
                monwc = list3.Rows.Count,
                monwwc = list4.Rows.Count
            };
            return Success("成功", obj);
        }

        /// <summary>
        /// 当天每小时的总通话量和接通量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTelRecordsByHour()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            int roleid = CurrentUser.UserData.F_RoleId;

            var date = DateTime.Now;//DateTime.Parse("2014-05-05"); //
            string strDate = date.ToString("yyyy-MM-dd");

            string[] cols = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" };

            string uwhere = " 1=1 ";
            if (roleid != 17)
            {
                uwhere += " and UserCode='" + usercode + "' ";
            }

            BLL.T_Call_CallRecords bll = new BLL.T_Call_CallRecords();
            int[] total = new int[24];
            int[] count = new int[24];
            for (int i = 0; i < cols.Length; i++)
            {
                var list = bll.GetModelList(uwhere + " and CONVERT(varchar(13),BeginTime, 120)='" + (strDate + " " + cols[i]) + "' ");
                var conlist = list.Where(p => p.CallState == 1);
                total[i] = list.Count;
                count[i] = conlist.Count();
            }

            var obj = new
            {
                col = cols,
                total = total,
                count = count
            };
            return Success("成功", obj);

        }

        /// <summary>
        /// 获取当月每天的工单量和话务量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkTelByDay()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            int roleid = CurrentUser.UserData.F_RoleId;

            var date = DateTime.Now;//DateTime.Parse("2015-04-05"); //
            string strDate = date.ToString("yyyy-MM");

            int days = DateTime.DaysInMonth(date.Year, date.Month);

            string[] strcols = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
                                  "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
                                  "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
            int newcount = 0;
            List<string> cols = strcols.Take(days).ToList();
            BLL.T_Call_CallRecords telbll = new BLL.T_Call_CallRecords();
            //BLL.T_Wo_WorkOrderBase workbll = new BLL.T_Wo_WorkOrderBase();
            BLL.T_Wo_WorkOrder workbll = new BLL.T_Wo_WorkOrder();
            int[] teltotal = new int[days];
            int[] worktotal = new int[days];

            string uwhere = " 1=1 ";
            string u1where = " 1=1 ";
            if (roleid != 17)
            {
                uwhere += " and CreateUser='" + usercode + "' ";
                u1where += " and UserCode='" + usercode + "' ";
            }

            for (int i = 0; i < cols.Count; i++)
            {
                //var tellist = telbll.GetModelList(" UserId='" + userId + "' and CONVERT(varchar(10),BeginTime, 23)='" + (strDate + "-" + cols[i]) + "' ");
                var tellist = telbll.GetModelList(u1where + " and CONVERT(varchar(10),BeginTime, 23)='" + (strDate + "-" + cols[i]) + "' ");
                teltotal[i] = tellist.Count;
                newcount = newcount + tellist.Count;
                //var worklist = workbll.GetList(" F_USERID='" + userId + "' and CONVERT(varchar(10),F_CREATEDATE, 23)='" + (strDate + "-" + cols[i]) + "' ").Tables[0];
                var worklist = workbll.GetList(uwhere + " and CONVERT(varchar(10),CreateTime, 23)='" + (strDate + "-" + cols[i]) + "' ").Tables[0];
                worktotal[i] = worklist.Rows.Count;
            }

            var olddate = date.AddYears(-1);
            string strold1 = olddate.ToString("yyyy-MM") + "-1";
            string strold2 = olddate.ToString("yyyy-MM-dd");

            string bl = string.Empty;
            var oldcount = telbll.GetModelList(u1where + " and CONVERT(varchar(10),BeginTime, 23)>='" + strold1 + "' and CONVERT(varchar(10),BeginTime, 23)<='" + strold2 + "' ").Count;

            if (oldcount == newcount)
            {
                bl = " 持平";
            }
            else
            {
                if (newcount != 0)
                {
                    if (oldcount > newcount)
                    {
                        bl = " ↓ " + (Convert.ToDouble(oldcount - newcount) / Convert.ToDouble(newcount)).ToString("0.0%");
                    }
                    else if (oldcount < newcount)
                    {
                        bl = " ↑ " + (Convert.ToDouble(newcount - oldcount) / Convert.ToDouble(newcount)).ToString("0.0%");
                    }
                }
                else
                {
                    bl = " --";
                }
            }

            var obj = new
            {
                bl = bl,
                col = cols.Select(p => p + "日"),
                worktotal = worktotal,
                teltotal = teltotal
            };

            return Success("成功", obj);

        }

        /// <summary>
        /// 获取当前用户待派单、待接单、待处理工单数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrderCount()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            int roleid = CurrentUser.UserData.F_RoleId;

            BLL.T_Wo_WorkOrder bll = new BLL.T_Wo_WorkOrder();

            string uwhere = " 1=1  ";
            if (roleid != 17)
            {
                uwhere += " and CreateUser='" + usercode + "' ";
            }

            var obj = new
            {
                dpd = bll.GetList(uwhere + " and IsDel=0 and State=0 ").Tables[0].Rows.Count,
                djd = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and (state='0' and ','+ToUser+',' like '%," + usercode + ",%')  ").Select(p => p.WorkOrderID).Distinct().Count(),
                dcl = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and (state='1' and SureUser='" + usercode + "')  ").Select(p => p.WorkOrderID).Distinct().Count()
            };
            return Success("成功", obj);

        }

        /// <summary>
        /// 最近通话记录
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLastCallList()
        {
            string usercode = CurrentUser.UserData.F_UserCode;

            DataTable dt = new DataTable();

            string strnum = HttpUtility.UrlDecode(RequestString.GetQueryString("num"));

            int n = 0;
            if (strnum.Trim() != "")
            {
                n = Convert.ToInt32(strnum);
            }

            dt = new BLL.T_Call_CallRecords().GetList(n, " UserCode='" + usercode + "' ", "CallRecordsId desc").Tables[0];
            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            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('\\', '/');
                }
            }
            return Success("成功", dt);

        }

        /// <summary>
        /// 最近消息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLastMsgList()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            DataTable dt = new DataTable();

            string strnum = HttpUtility.UrlDecode(RequestString.GetQueryString("num"));

            int n = 0;
            if (strnum.Trim() != "")
            {
                n = Convert.ToInt32(strnum);
            }

            dt = new BLL.T_Msg_List().GetList(n, " ToUser='" + usercode + "' and IsDel=0 ", "ID desc").Tables[0];

            return Success("成功", dt);
        }

        //本月话务量及工单量折现统计（改成本月话务统计圆柱体：呼入量、呼出量）

        public ActionResult GetCallTypecCount()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            string wheresql = "";
            string sdate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.ToString();
            string edate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1).ToString();
            wheresql += "   datediff(day,BeginTime,'" + sdate + "')<=0 ";
            wheresql += " and datediff(day,BeginTime,'" + edate + "')>=0   ";
            string sql = "SELECT   CallType,COUNT(1) num  FROM  T_Call_CallRecords   where " + wheresql + "  group by CallType ";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];
            return Success("本月话务统计呼入量呼出量0是呼入1是呼出", dt);


        }

        //工单信息改成问题分类：移网质量、渠道服务、光网质量、装维服务、套餐资费 （统计数量及占比）

        public ActionResult getWTFL()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            string wheresql = "";
            string sdate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.ToString();
            string edate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1).ToString();
            wheresql += "  and datediff(day,CreateTime,'" + sdate + "')<=0 ";
            wheresql += " and datediff(day,CreateTime,'" + edate + "')>=0   ";
            string sql = "  select InfoTypeID dicid,COUNT(1) num,dbo.GetDictionaryName(InfoTypeID) dicname from   T_Wo_WorkOrder where    WorkOrderID in (select WorkOrderID from T_Wo_WorkOrderItem where  IsDel=0 and  ','+ToUser+',' like '%," + usercode + ",%' "+ wheresql + " )    group by  InfoTypeID";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            string sql2= "  select  count(1) sumnum from   T_Wo_WorkOrder where    WorkOrderID in (select WorkOrderID from T_Wo_WorkOrderItem where  IsDel=0 and  ','+ToUser+',' like '%," + usercode + ",%' " + wheresql + " )   ";
          string sumnum=  DbHelperSQL.GetSingle(sql2).ToString();
            dt.Columns.Add("per");
            foreach (DataRow item in dt.Rows)
            {
                if (sumnum == "0")
                {
                    item["per"] = "0";
                }
                else
                {
                    item["per"] = string.Format("{0:F2}%", (double.Parse(item["num"].ToString()) / double.Parse(sumnum)) * 100);

                }
            }


            return Success("本月问题分类统计数量", dt);

        }

        //增加公告显示
        //Index

    }
}