using CallCenter.Utility;
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.report
{
    public class GDPosController : BaseController
    {
        // GET: GDPos
        //public ActionResult Index()
        //{
        //    return View();
        //}

        /// <summary>
        /// 获取工单地区报表
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public ActionResult GetDataList(string stime, string endtime)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            DataTable dtNew = new DataTable();
            dtNew = getData(stime, endtime);
            #region 获取表头
            DataTable dt = new DataTable();
            string sql = "select b.f_province from [dbo].[T_Wo_WorkOrder] a,T_Cus_CustomerBase b where a.CustomerID = b.F_CustomerId";
            dt = DbHelperSQL.Query(sql).Tables[0];
            List<string> colnames = new List<string>();
            colnames.Add("省份");

            DataTable dtnew = new DataTable();
            string sqlnew = "select * from T_Sys_UserAccount where 1=1 and F_DeleteFlag=0";
            dtnew = DbHelperSQL.Query(sqlnew).Tables[0];
            for (int j = 0; j < dtnew.Rows.Count; j++)
            {
                string f_ucode = "";
                if (dtnew.Rows[j]["F_UserCode"] != null)
                {
                    f_ucode = dtnew.Rows[j]["F_UserCode"].ToString();
                    colnames.Add(f_ucode);
                }
            }
            colnames.Add("总计");
            #endregion
            var obj = new
            {
                dt = dtNew,
                colname = colnames
            };
            res = Success("获取工单地区数据成功", obj);

            return res;
        }

        private DataTable getData(string stime, string endtime)
        {
            DataTable dtNew = new DataTable();
            #region 添加表格标题
            DataColumn dc = new DataColumn("省份");
            dtNew.Columns.Add(dc);
            var sqlGDLY = " and F_DeleteFlag=0";
            var recordCount = 0;
            //var dtGDLY = BLL.PagerBLL.GetListPager(
            //  "T_Sys_UserAccount",
            //  "F_UserId",
            //  "*",
            //  sqlGDLY,
            //  "ORDER BY F_Userid asc ",
            //  10,
            //  1,
            //  true,
            //  out recordCount);
            //List<Model.T_Sys_UserAccount> modelList = new BLL.T_Sys_UserAccount().DataTableToList(dtGDLY);

            var modelList = new BLL.T_Sys_UserAccount().GetModelList(" F_DeleteFlag=0 ");
            for (int i = 0; i < modelList.Count; i++)
            {
                string colname = modelList[i].F_UserCode;
                dtNew.Columns.Add(new DataColumn(colname));
            }
            dtNew.Columns.Add("总计");
            #endregion

            string sqltimeCallRecords = "";
            if (stime != null && stime.Trim() != "")
            {
                sqltimeCallRecords += " and CONVERT(varchar , CreateTime, 120)>=CONVERT(varchar , '" + stime.Trim() + " 00:00:01', 120) ";
            }
            if (endtime != null && endtime.Trim() != "")
            {
                sqltimeCallRecords += " and CONVERT(varchar , CreateTime, 120)<=CONVERT(varchar , '" + endtime.Trim() + " 23:59:59', 120) ";
            }

            double day = 0;
            if (stime != null && endtime != null && endtime.Trim() != "" && stime.Trim() != "")
            {
                TimeSpan time = Convert.ToDateTime(endtime) - Convert.ToDateTime(stime);
                day = time.Days + 1;
            }
            //获取省份数据
            DataTable dt = new DataTable();
            string sql = "select distinct b.F_Province from [dbo].[T_Wo_WorkOrder] a,T_Cus_CustomerBase b where a.Address = b.F_CustomerIndustry and b.F_Province is not null";
            dt = DbHelperSQL.Query(sql).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string f_prov = "";
                DataRow drNew = dtNew.NewRow();
                if (dt.Rows[i][0].ToString() != "")
                    f_prov = dt.Rows[i][0].ToString();
                drNew["省份"] = f_prov;
                //获取工单来源数据
                DataTable dtnew = new DataTable();
                string sqlnew = "select * from T_Sys_UserAccount where 1=1 and F_DeleteFlag=0";
                dtnew = DbHelperSQL.Query(sqlnew).Tables[0];
                int sum = 0;
                for (int j = 0; j < dtnew.Rows.Count; j++)
                {
                    string f_ucode = "";
                    if (dtnew.Rows[j]["F_UserCode"] != null)
                        f_ucode = dtnew.Rows[j]["F_UserCode"].ToString();
                    string str = "select count(*) from [dbo].[T_Wo_WorkOrder] a where a.CreateUserID is not null and a.CreateUserID = '" + f_prov + "' and a.createuser = '" + f_ucode + "' and a.IsDel=0 " + sqltimeCallRecords;
                    int ecount = int.Parse(DbHelperSQL.GetSingle(str).ToString());
                    drNew[f_ucode] = ecount.ToString();
                    sum += ecount;
                    drNew["总计"] = sum.ToString();
                }
                //drNew[dtnew.Columns.Count - 1] = sum.ToString();
                dtNew.Rows.Add(drNew);
            }

            return dtNew;
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportExcel(string stime, string endtime)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                //导出dtnew
                NPOIHelper npoi = new NPOIHelper();
                DataTable dt = getData(stime, endtime);
                if (npoi.ExportToExcel("工单地区数据报表", dt, null) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            return res;
        }

        /// <summary>
        /// 获取工单来源报表
        /// </summary>
        /// <param name="sdate"></param>
        /// <param name="edate"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetList(string sdate, string edate, int isdc = 0)
        {
            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;

            if (!string.IsNullOrEmpty(sdate))
            {
                stime = DateTime.Parse(sdate);
            }
            if (!string.IsNullOrEmpty(edate))
            {
                etime = DateTime.Parse(edate);
            }
            if (string.IsNullOrEmpty(sdate) && string.IsNullOrEmpty(edate))
            {
                stime = new DateTime(stime.Year, stime.Month, 1); ;
            }

            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@sdate", stime.ToString("yyyy-MM-dd"));
            paras.Add("@edate", etime.ToString("yyyy-MM-dd"));
            var obj = DbHelperSQL.RunProcedure("P_WorkProvinceReport", paras, "WorkProvinceReport");
            if (isdc > 0)
            {
                NPOIHelper npoi = new NPOIHelper();
                if (npoi.ExportToExcel("工单地区报表", obj.Tables[0]) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            return Success("成功", obj);
        }


        public ActionResult GetTimeNodeAging()
        {
            int woid = 4650;
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@woid", woid.ToString());
            var obj = DbHelperSQL.RunProcedure("P_TimeNodeAging", paras, "TimeNodeAReport");
            return Success("成功", obj);
        }
    }
}