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 CallOutReportController : BaseController
    {
        private readonly BLL.T_Call_OutTaskTelNum otnBLL = new BLL.T_Call_OutTaskTelNum();
        private readonly BLL.T_Ask_Question questionBLL = new BLL.T_Ask_Question();
        private readonly BLL.T_Call_OutAnswers ansBLL = new BLL.T_Call_OutAnswers();
        private readonly BLL.T_Ask_QuestionItems questionItemBLL = new BLL.T_Ask_QuestionItems();

        #region 获取外呼任务报表查询
        /// <summary>
        /// 外呼任务报表
        /// </summary>
        /// <param name="TaskID">任务id</param>
        /// <param name="quesid">问题id</param>
        /// <param name="countryid">乡镇id</param>
        /// <param name="sdate">开始时间</param>
        /// <param name="edate">结束时间</param>
        /// <returns></returns>
        public ActionResult GetReport(string TaskID, string quesid, string countryid, string sdate, string edate)
        {
            #region 新建输出表
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("wenti");
            dtnew.Columns.Add("xuanxiang");
            dtnew.Columns.Add("shuliang");
            dtnew.Columns.Add("bili");
            #endregion

            #region 根据问题id获取问题的查询条件
            string sqlques = "F_QuestionId IN (select ta.F_QuestionId from  T_Ask_PagerItems ta where ta.F_PagerId=(select F_PagerID from T_Call_OutTask where isnull(F_TaskID,'')='" + TaskID + "') ) and F_Type!=1";
            if (!string.IsNullOrWhiteSpace(quesid))
                sqlques = "F_QuestionId="+ quesid;
            #endregion
            #region 回答问题查询条件
            string sqlans = " isnull(F_TaskID,'')='" + TaskID + "' ";
            if (!string.IsNullOrWhiteSpace(countryid))
                sqlans += " and isnull(F_Expand1,'')='" + countryid + "' ";
            if (!string.IsNullOrWhiteSpace(sdate))
                sqlans += " and DATEDIFF(day,F_OptOn,'"+ sdate.Trim() + "')<=0";
            if (!string.IsNullOrWhiteSpace(edate))
                sqlans += " and DATEDIFF(day,F_OptOn,'" + edate.Trim() + "')>=0";
            #endregion
            var queslist = questionBLL.GetModelList(sqlques);

            if (queslist.Count > 0)
            {
                foreach (var itemques in queslist)
                {
                    string content = itemques.F_Content;
                    string question = itemques.F_Title;

                    sqlans += " and isnull(F_QID,'')='" + itemques.F_QuestionId + "' ";
                    //根据问题ID获取当前问题各选项答案总数
                    int totalnum = ansBLL.GetRecordCount(sqlans);

                    //根据问题ID查询问题项
                    var dsi = questionItemBLL.GetModelList(" isnull(F_QuestionId,'') = '" + itemques.F_QuestionId + "' ");
                    if (dsi.Count > 0)
                    {
                        foreach (var itemqi in dsi)
                        {
                            DataRow dr = dtnew.NewRow();
                            dr["wenti"] = question;
                            dr["xuanxiang"] = itemqi.F_ItemName;
                            int num = ansBLL.GetRecordCount(sqlans + "  and isnull(F_QIID,'')='" + itemqi.F_ItemId + "' ");
                            dr["shuliang"] = num;
                            if (totalnum != 0)
                            {
                                if (num > 0)
                                {
                                    dr["bili"] = Math.Round(Convert.ToDecimal(Convert.ToDecimal(num) / totalnum * 100), 1).ToString() + "%";
                                }
                                else
                                {
                                    dr["bili"] = "0";
                                }
                            }
                            else
                            { dr["bili"] = "0"; }

                            dtnew.Rows.Add(dr);
                        }
                    }
                    #region 总计
                    DataRow drzj = dtnew.NewRow();
                    drzj["wenti"] = "总计";
                    drzj["xuanxiang"] = "";
                    drzj["shuliang"] = totalnum;
                    drzj["bili"] = "-";
                    dtnew.Rows.Add(drzj);
                    #endregion
                }
            }
            return Success("获取外呼任务报表数据成功", dtnew);
            
        }

        #region 外呼任务报表导出Excel
        public ActionResult GetReportExpt(string TaskID, string quesid, string countryid, string sdate, string edate)
        {
            #region 新建输出表
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("wenti");
            dtnew.Columns.Add("xuanxiang");
            dtnew.Columns.Add("shuliang");
            dtnew.Columns.Add("bili");
            #endregion

            #region 根据问题id获取问题的查询条件
            string sqlques = "F_QuestionId IN (select ta.F_QuestionId from  T_Ask_PagerItems ta where ta.F_PagerId=(select F_PagerID from T_Call_OutTask where isnull(F_TaskID,'')='" + TaskID + "') ) and F_Type!=1";
            if (!string.IsNullOrWhiteSpace(quesid))
                sqlques = "F_QuestionId=" + quesid;
            #endregion
            #region 回答问题查询条件
            string sqlans = " isnull(F_TaskID,'')='" + TaskID + "' ";
            if (!string.IsNullOrWhiteSpace(countryid))
                sqlans += " and isnull(F_Expand1,'')='" + countryid + "' ";
            if (!string.IsNullOrWhiteSpace(sdate))
                sqlans += " and DATEDIFF(day,F_OptOn,'" + sdate.Trim() + "')<=0";
            if (!string.IsNullOrWhiteSpace(edate))
                sqlans += " and DATEDIFF(day,F_OptOn,'" + edate.Trim() + "')>=0";
            #endregion
            var queslist = questionBLL.GetModelList(sqlques);

            if (queslist.Count > 0)
            {
                foreach (var itemques in queslist)
                {
                    string content = itemques.F_Content;
                    string question = itemques.F_Title;

                    sqlans += " and isnull(F_QID,'')='" + itemques.F_QuestionId + "' ";
                    //根据问题ID获取当前问题各选项答案总数
                    int totalnum = ansBLL.GetRecordCount(sqlans);

                    //根据问题ID查询问题项
                    var dsi = questionItemBLL.GetModelList(" isnull(F_QuestionId,'') = '" + itemques.F_QuestionId + "' ");
                    if (dsi.Count > 0)
                    {
                        foreach (var itemqi in dsi)
                        {
                            DataRow dr = dtnew.NewRow();
                            dr["wenti"] = question;
                            dr["xuanxiang"] = itemqi.F_ItemName;
                            int num = ansBLL.GetRecordCount(sqlans + "  and isnull(F_QIID,'')='" + itemqi.F_ItemId + "' ");
                            dr["shuliang"] = num;
                            if (totalnum != 0)
                            {
                                if (num > 0)
                                {
                                    dr["bili"] = Math.Round(Convert.ToDecimal(Convert.ToDecimal(num) / totalnum * 100), 1).ToString() + "%";
                                }
                                else
                                {
                                    dr["bili"] = "0";
                                }
                            }
                            else
                            { dr["bili"] = "0"; }

                            dtnew.Rows.Add(dr);
                        }
                    }
                    #region 总计
                    DataRow drzj = dtnew.NewRow();
                    drzj["wenti"] = "总计";
                    drzj["xuanxiang"] = "";
                    drzj["shuliang"] = totalnum;
                    drzj["bili"] = "-";
                    dtnew.Rows.Add(drzj);
                    #endregion
                }
            }
            //导出dtnew
            NPOIHelper npoi = new NPOIHelper();
            string[] col = { "问题", "选项", "数量", "比例" };
            if (npoi.ExportToExcel("外呼任务报表统计数据", dtnew, col) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
        }
        #endregion
        #endregion

        #region  获取乡镇统计排名
        public ActionResult GetRank(string sdate, string edate,string taskid)
        {
            if (string.IsNullOrWhiteSpace(sdate))
            {
                sdate = DateTime.Now.ToString("yyyy-MM-dd");
            }
            if (string.IsNullOrWhiteSpace(edate))
            {
                edate = DateTime.Now.ToString("yyyy-MM-dd");
            }
            string strand = "";
            if (!string.IsNullOrWhiteSpace(taskid))
            {
                strand = "and F_TaskId='" + taskid + "'";
            }
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("xiangzhen", Type.GetType("System.String"));
            dtnew.Columns.Add("zongshu", Type.GetType("System.Int32"));
            int leiji = 0;
            var conf = new BLL.T_Sys_DictionaryValue().GetModelList(" F_DictionaryFlag='JBDW' ");
            if (conf.Count > 0)
            {
                foreach (var itemconf in conf)
                {
                    DataRow dr = dtnew.NewRow();
                    dr["xiangzhen"] = itemconf.F_Name;
                    //根据乡镇获取总数
                    int totalnum= otnBLL.GetRecordCount(" DATEDIFF(day,ExpandDatField1,'" + sdate + "')<=0 and DATEDIFF(day,ExpandDatField1,'" + edate + "')>=0 and ExpandIntField1='" + itemconf.F_DictionaryValueId+ "' "+strand );
                    //int totalnum = ansBLL.GetRecordCount(" DATEDIFF(day,F_OptOn,'" + sdate + "')<=0 and DATEDIFF(day,F_OptOn,'" + edate + "')>=0 and F_Answer='" + itemconf.F_Name + "' ");

                    leiji += totalnum;
                    dr["zongshu"] = totalnum;

                    dtnew.Rows.Add(dr);
                }
            }

            dtnew.DefaultView.Sort = "zongshu DESC";
            DataTable dtTemp = dtnew.DefaultView.ToTable();
            //计算总计
            DataRow dr0 = dtTemp.NewRow();
            dr0["xiangzhen"] = "总计";
            dr0["zongshu"] = leiji;

            dtTemp.Rows.Add(dr0);
            return Success("获取乡镇报表数据成功", dtTemp);
            
        }
        #region  数据查询--获取排名
        public ActionResult GetRankExpt(string sdate, string edate,string taskid)
        {
            if (string.IsNullOrWhiteSpace(sdate))
            {
                sdate = DateTime.Now.ToString("yyyy-MM-dd");
            }
            if (string.IsNullOrWhiteSpace(edate))
            {
                edate = DateTime.Now.ToString("yyyy-MM-dd");
            }

            string strand = "";
            if (!string.IsNullOrWhiteSpace(taskid))
            {
                strand = "and F_TaskId='" + taskid + "'";
            }
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("paiming", Type.GetType("System.String"));
            dtnew.Columns.Add("xiangzhen", Type.GetType("System.String"));
            dtnew.Columns.Add("zongshu", Type.GetType("System.Int32"));
            int leiji = 0;

            var conf = new BLL.T_Sys_DictionaryValue().GetModelList(" F_DictionaryFlag='JBDW' ");
            if (conf.Count > 0)
            {
                foreach (var itemconf in conf)
                {
                    DataRow dr = dtnew.NewRow();
                    dr["xiangzhen"] = itemconf.F_Name;
                    //根据乡镇获取总数
                    int totalnum = otnBLL.GetRecordCount(" DATEDIFF(day,ExpandDatField1,'" + sdate + "')<=0 and DATEDIFF(day,ExpandDatField1,'" + edate + "')>=0 and ExpandIntField1='" + itemconf.F_DictionaryValueId + "' "+ strand);
                    //int totalnum = ansBLL.GetRecordCount(" DATEDIFF(day,F_OptOn,'" + sdate + "')<=0 and DATEDIFF(day,F_OptOn,'" + edate + "')>=0 and F_Answer='" + itemconf.F_Name + "' ");

                    leiji += totalnum;
                    dr["zongshu"] = totalnum;

                    dtnew.Rows.Add(dr);
                }
            }
            dtnew.DefaultView.Sort = "zongshu DESC";
            DataTable dtTemp = dtnew.DefaultView.ToTable();
            for (int h = 0; h < dtTemp.Rows.Count; h++)
            {
                dtTemp.Rows[h]["paiming"] = h + 1;
            }
            //计算总计
            DataRow dr0 = dtTemp.NewRow();
            dr0["paiming"] = "";
            dr0["xiangzhen"] = "总计";
            dr0["zongshu"] = leiji;
            dtTemp.Rows.Add(dr0);

            //return res;
            //导出dtnew
            NPOIHelper npoi = new NPOIHelper();
            string[] col = { "排名", "乡镇", "总数" };
            if (npoi.ExportToExcel("乡镇排名统计数据", dtTemp, col) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
        }
        #endregion
        #endregion

        #region 外呼问题报表数据查询
        List<string> arlist = new List<string>();//表头问题分项
        List<string> checklist = new List<string>();//查询条件问题分项
        DataTable dtNews = new DataTable();
        DataTable dtCol = new DataTable();
        int columnsnum = 1;//左边留一空列，用于显示查询条件答案
        //获取表头
        public ActionResult GetColumnList(string TaskID, string quesid1, string quesid2)
        {
            columnsnum = 1;
            arlist.Clear();
            checklist.Clear();
            #region
            dtCol.Columns.Add("wenti", Type.GetType("System.String"));
            dtCol.Columns.Add("fenxiangshu", Type.GetType("System.Int32"));
            dtCol.Columns.Add("wentiid", Type.GetType("System.String"));
            #endregion
            #region 根据问题id获取问题的查询条件
            string sqlques = "F_QuestionId IN (select ta.F_QuestionId from  T_Ask_PagerItems ta where ta.F_PagerId=(select F_PagerID from T_Call_OutTask where isnull(F_TaskID,'')='" + TaskID + "') ) and F_Type!=1";
            //if (!string.IsNullOrWhiteSpace(quesid))
            //    sqlques = "F_QuestionId=" + quesid;
            #endregion

            var quesmodel = questionBLL.GetModel(int.Parse(quesid2));
            if (quesmodel != null)
            {
                DataRow dr = dtCol.NewRow();
                dr["wenti"] = quesmodel.F_Title;
                #region 第一列
                //根据问题ID查询问题项
                var dsitem = questionItemBLL.GetModelList(" isnull(F_QuestionId,'') = '" + quesid1 + "' ");
                if (dsitem.Count > 0)
                {
                    foreach (var itemqi in dsitem)
                    {
                        arlist.Add(itemqi.F_ItemName);
                        columnsnum++;
                    }
                    dr["fenxiangshu"] = dsitem.Count;
                }
                #endregion
                dr["wentiid"] = quesmodel.F_QuestionId;
                dtCol.Rows.Add(dr);
                #region 横向表头
                //根据问题ID查询问题项
                var dsi2 = questionItemBLL.GetModelList(" isnull(F_QuestionId,'') = '" + quesid2 + "' ");
                if (dsi2.Count > 0)
                {
                    foreach (var itemqi in dsi2)
                    {
                        checklist.Add(itemqi.F_ItemName);
                    }
                    checklist.Add("总计"); //增加总计
                }
                #endregion
            }

            return Success("获取外呼问题报表表头成功", dtCol);
        }

        //获取数据
        public ActionResult GetDataList(string TaskID, string quesid1, string quesid2, string countryid, string sdate, string edate)
        {
            int index1 = 0;
            int index2 = 0;
            GetColumnList(TaskID, quesid1, quesid2);
            int rowcount = checklist.Count + 1;//行数

            string[,] newdata = new string[rowcount, columnsnum];
            #region 回答问题查询条件
            string sqlans = " isnull(F_TaskID,'')='" + TaskID + "' ";
            string sqlans1 = " ";
            if (!string.IsNullOrWhiteSpace(countryid))
                sqlans += " and isnull(F_Expand1,'')='" + countryid + "' ";
            if (!string.IsNullOrWhiteSpace(sdate))
                sqlans += "DATEDIFF(day,F_OptOn,'" + sdate.Trim() + "')<=0";
            if (!string.IsNullOrWhiteSpace(edate))
                sqlans += "DATEDIFF(day,F_OptOn,'" + edate.Trim() + "')>=0";
            #endregion
            #region 第一行添加
            newdata[index1, index2] = "";
            index2++;
            for (int j = 0; j < arlist.Count; j++)
            {
                newdata[index1, index2] = arlist[j];
                index2++;
            }
            
            index1++;//第一行添加结束
            #endregion
            //获取百分比
            List<string> rowlist = new List<string>();

            foreach (string items in checklist)
            {
                int colnum = 2;
                index2 = 0;
                DataRow drr = dtNews.NewRow();
                newdata[index1, index2] = items;
                int n = 0;
                int len = 0;
                for (int m = 0; m < dtCol.Rows.Count; m++)
                {

                    sqlans1 = sqlans;
                    sqlans += " and F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_TaskID='" + TaskID + "' AND F_QID='" + quesid2 + "' AND F_Answer='" + items + "') and  F_QID='" + quesid1 + "' ";
                    sqlans1 += " and F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_TaskID='" + TaskID + "' AND F_QID='" + quesid2 + "') and  F_QID='" + quesid1 + "' ";
                    //根据问题查询回答该问题的总次数
                    int totalnum = 0;
                    int num = 0;
                    totalnum = ansBLL.GetRecordCount(sqlans);

                    string fenxiangshu = dtCol.Rows[m]["fenxiangshu"].ToString();
                    int fenxiang = fenxiangshu == "" ? 0 : Convert.ToInt32(fenxiangshu);
                    len = len + fenxiang;
                    while (n < len)
                    {
                        index2++;
                        if (items.Equals("总计"))
                        {
                            //同一问题下的分项
                            num = ansBLL.GetRecordCount(sqlans1 + "' and  F_Answer='" + newdata[0, n + 1] + "'");
                            newdata[index1, index2] = num.ToString();
                        }
                        else
                        {
                            //同一问题下的分项
                            num = ansBLL.GetRecordCount(sqlans + "  and isnull(F_Answer,'')='" + newdata[0, n + 1] + "' ");

                            newdata[index1, index2] = num.ToString();
                        }
                        n++;

                    }
                    colnum++;
                }
                index1++;
            }
            return Success("获取外呼问题报表数据成功", newdata);
            
        }
        #endregion
    }
}