using CallCenter.Utility;
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.report
{
    //[Authority]
    public class BusinessController : BaseController
    {
        /// <summary>
        /// 工单流程执行效率分析
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkEfficiency()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

                string sql = " IsDel=0 and State=2 ";

                if (strstarttime != null && strstarttime.Trim() != "")
                {
                    sql += " and CreateTime>='" + strstarttime + " 00:00:00' ";
                }
                if (strendtime != null && strendtime.Trim() != "")
                {
                    sql += " and CreateTime<='" + strendtime + " 23:59:59' ";
                }

                if (string.IsNullOrEmpty(strstarttime) && string.IsNullOrEmpty(strendtime))
                {
                    string strDate = DateTime.Now.ToString("yyyy-MM");
                    sql += " and CONVERT(varchar(7),CreateTime, 23)='" + strDate + "'";
                }

                var list = new BLL.T_Wo_WorkOrder().GetModelList(sql);
                var datelist = list.Select(p => p.CreateTime.Value.ToString("yyyy-MM-dd")).Distinct();

                DataTable dt = new DataTable();
                dt.Columns.Add("Date", typeof(string));
                dt.Columns.Add("Count", typeof(int));
                dt.Columns.Add("TotalTime", typeof(decimal));
                dt.Columns.Add("AvgTime", typeof(decimal));
                dt.Columns.Add("ZPTotalTime", typeof(decimal));
                dt.Columns.Add("ZPAvgTime", typeof(decimal));
                dt.Columns.Add("JDTotalTime", typeof(decimal));
                dt.Columns.Add("JDAvgTime", typeof(decimal));
                dt.Columns.Add("CLTotalTime", typeof(decimal));
                dt.Columns.Add("CLAvgTime", typeof(decimal));

                foreach (var date in datelist)
                {
                    var everylist = list.Where(p => p.CreateTime.Value.ToString("yyyy-MM-dd") == date);

                    string ids = string.Empty;
                    foreach (var l in everylist.Select(p => p.WorkOrderID))
                    {
                        if (string.IsNullOrEmpty(ids))
                        {
                            ids = l;
                        }
                        else
                        {
                            ids = ids + "','" + l;
                        }
                    }

                    var itemlist = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and WorkOrderID in ('" + ids + "')");

                    var TotalTimelist = everylist.Where(p => p.LastDealTime != null).Select(p => new { totaltime = p.LastDealTime.Value.Subtract(p.CreateTime.Value).TotalHours });
                    var ZPList = everylist.Where(p => p.AppointTime != null).Select(p => new { totaltime = p.AppointTime.Value.Subtract(p.CreateTime.Value).TotalHours });
                    var JDList = itemlist.Where(p => p.SureTime != null && p.DealTime != null).Select(p => new { totaltime = p.SureTime.Value.Subtract(p.CreateTime.Value).TotalHours });
                    var CLList = itemlist.Where(p => p.SureTime != null).Select(p => new { totaltime = p.DealTime.Value.Subtract(p.SureTime.Value).TotalHours });
                    DataRow dr = dt.NewRow();
                    dr["Date"] = date;
                    dr["Count"] = everylist.Count();
                    if (TotalTimelist.Count() > 0)
                    {
                        dr["TotalTime"] = TotalTimelist.Sum(p => p.totaltime).ToString("f2");
                        dr["AvgTime"] = TotalTimelist.Average(p => p.totaltime).ToString("f2");
                    }
                    if (ZPList.Count() > 0)
                    {
                        dr["ZPTotalTime"] = ZPList.Sum(p => p.totaltime).ToString("f2");
                        dr["ZPAvgTime"] = ZPList.Average(p => p.totaltime).ToString("f2");
                    }
                    if (JDList.Count() > 0)
                    {
                        dr["JDTotalTime"] = JDList.Sum(p => p.totaltime).ToString("f2");
                        dr["JDAvgTime"] = JDList.Average(p => p.totaltime).ToString("f2");
                    }
                    if (CLList.Count() > 0)
                    {
                        dr["CLTotalTime"] = CLList.Sum(p => p.totaltime).ToString("f2");
                        dr["CLAvgTime"] = CLList.Average(p => p.totaltime).ToString("f2");
                    }

                    dt.Rows.Add(dr);
                }
                res = Success("成功", dt);
            }

            return res;
        }

        /// <summary>
        /// 工单部门分布情况
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkDept()
        {
            ActionResult res = NoToken("未知错误，请重新登录");

            if (Request.IsAuthenticated)
            {
                string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

                string sql = " IsDel=0 and State=2 ";

                if (strstarttime != null && strstarttime.Trim() != "")
                {
                    sql += " and CreateTime>='" + strstarttime + " 00:00:00' ";
                }
                if (strendtime != null && strendtime.Trim() != "")
                {
                    sql += " and CreateTime<='" + strendtime + " 23:59:59' ";
                }

                if (string.IsNullOrEmpty(strstarttime) && string.IsNullOrEmpty(strendtime))
                {
                    string strDate = DateTime.Now.ToString("yyyy-MM");
                    sql += " and CONVERT(varchar(7),CreateTime, 23)='" + strDate + "'";
                }

                var list = new BLL.T_Wo_WorkOrder().GetModelList(sql).Select(p => p.WorkOrderID);

                string ids = string.Empty;
                foreach (var l in list)
                {
                    if (string.IsNullOrEmpty(ids))
                    {
                        ids = l;
                    }
                    else
                    {
                        ids = ids + "','" + l;
                    }
                }

                var itemlist = new BLL.T_Wo_WorkOrderItem().GetModelList(" isnull(ToDept,'')!='' and IsDel=0 and Type=1 and WorkOrderID in ('" + ids + "')");
                var bmlist = itemlist.Select(p => p.ToDept).Distinct();

                DataTable dt = new DataTable();
                dt.Columns.Add("DeptID", typeof(int));
                dt.Columns.Add("DeptName", typeof(string));
                dt.Columns.Add("WorkCount", typeof(int));
                dt.Columns.Add("CLTotalTime", typeof(decimal));
                dt.Columns.Add("XYAvgTime", typeof(decimal));
                dt.Columns.Add("CLAvgTime", typeof(decimal));

                foreach (var bm in bmlist)
                {
                    var bminfo = new BLL.T_Sys_Department().GetModel(bm.Value);
                    if (bminfo != null)
                    {
                        var bmcllist = itemlist.Where(p => p.ToDept == bm);
                        var cllist = bmcllist.Where(p => p.SureTime != null && p.DealTime != null).Select(p => new { totaltime = p.DealTime.Value.Subtract(p.SureTime.Value).TotalHours });
                        var xylist = bmcllist.Where(p => p.SureTime != null).Select(p => new { totaltime = p.SureTime.Value.Subtract(p.CreateTime.Value).TotalHours });
                        DataRow dr = dt.NewRow();
                        dr["DeptID"] = bminfo.F_DeptId;
                        dr["DeptName"] = bminfo.F_DeptName;
                        dr["WorkCount"] = bmcllist.Count();
                        if (cllist.Count() > 0)
                        {
                            dr["CLTotalTime"] = cllist.Sum(p => p.totaltime).ToString("f2");
                            dr["CLAvgTime"] = cllist.Average(p => p.totaltime).ToString("f2");
                        }
                        if (xylist.Count() > 0)
                        {
                            dr["CLAvgTime"] = xylist.Average(p => p.totaltime).ToString("f2");
                        }

                        dt.Rows.Add(dr);
                    }
                }

                res = Success("成功", dt);
            }

            return res;
        }

        /// <summary>
        /// 工单时间点分布情况
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkPeriod()
        {
            ActionResult res = NoToken("未知错误，请重新登录");

            if (Request.IsAuthenticated)
            {
                string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

                string sql = " IsDel=0 ";

                if (strstarttime != null && strstarttime.Trim() != "")
                {
                    sql += " and CreateTime>='" + strstarttime + " 00:00:00' ";
                }
                if (strendtime != null && strendtime.Trim() != "")
                {
                    sql += " and CreateTime<='" + strendtime + " 23:59:59' ";
                }

                if (string.IsNullOrEmpty(strstarttime) && string.IsNullOrEmpty(strendtime))
                {
                    string strDate = DateTime.Now.ToString("yyyy-MM");
                    sql += " and CONVERT(varchar(7),CreateTime, 23)='" + strDate + "'";
                }

                var list = new BLL.T_Wo_WorkOrder().GetModelList(sql);

                string[] strcols = { "08", "09", "10", "11", "12", "13", "14", "15", "16", "17" };
                int[] worktotal = new int[strcols.Count()];
                for (int i = 0; i < strcols.Count(); i++)
                {
                    var worklist = list.Where(p => p.CreateTime.Value.ToString("HH") == strcols[i]);
                    worktotal[i] = worklist.Count();
                }

                var obj = new
                {
                    col = strcols.Select(p => p + ":00"),
                    count = worktotal
                };

                res = Success("成功", obj);
            }

            return res;
        }
    }
}