using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

  
using NPOI.XSSF.UserModel;
 



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();
        private readonly BLL.T_Call_OutTask otBLL = new BLL.T_Call_OutTask();

        #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 外呼问题报表数据查询
        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

        #region 不满意报表
        #region 数据
        /// <summary>
        /// 不满意报表
        /// </summary>
        /// <param name="TaskID">任务id 必选</param>
        /// <param name="quesid">问题id 必选</param>
        /// <param name="ansid">当前问题答案id 可多选</param>
        /// <param name="sdate">开始时间</param>
        /// <param name="edate">结束时间</param>
        /// <returns></returns>
        public ActionResult GetReportBMY(string TaskID, int quesid, string ansids, string sdate, string edate)
        {
            DataTable dtnew = new DataTable();

            dtnew = getdateBMY(TaskID, quesid, ansids, sdate, edate);
            return Success("获取详细报表数据成功", dtnew);

        }
        public DataTable getdateBMY(string TaskID, int quesid, string ansids, string sdate, string edate)
        {
            DataTable dtnew = new DataTable();
            #region 新建输出表
            dtnew.Columns.Add("name");
            dtnew.Columns.Add("phone");
            dtnew.Columns.Add("answer");
            #endregion

            #region 查询条件
            string sqlotn = "";
            string sqlans = " and isnull(F_TaskID,'')='" + TaskID + "' " + " and isnull(F_QID,'')='" + quesid + "' ";
            if (!string.IsNullOrWhiteSpace(TaskID))
            { sqlotn = " and isnull(F_TaskID,'')='" + TaskID + "' "; }
            //string sqlotn = " and isnull(F_TaskID,'')='" + TaskID + "' ";
            #region 选中答案搜索
            if (string.IsNullOrWhiteSpace(TaskID))
            { sqlans = "  and isnull(F_QID,'')='" + quesid + "' "; }
            //string sqlans = " and isnull(F_TaskID,'')='" + TaskID + "' " + " and isnull(F_QID,'')='" + quesid + "' ";
            if (!string.IsNullOrWhiteSpace(ansids) && ansids != "null")
            {
                sqlans += " and F_QIID in (" + ansids.Trim() + ") ";
            }
            sqlotn += " and F_Id in (select F_CusTelID from T_Call_OutAnswers where 1=1 " + sqlans + ")";
            #endregion
            if (!string.IsNullOrWhiteSpace(sdate))
                sqlotn += " and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0";
            if (!string.IsNullOrWhiteSpace(edate))
                sqlotn += " and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0";
            #endregion
            var otnlist = otnBLL.GetModelList(" 1=1 " + sqlotn);

            if (otnlist.Count > 0)
            {
                foreach (var itemotn in otnlist)
                {
                    DataRow dr = dtnew.NewRow();
                    dr["name"] = itemotn.F_CusName;
                    dr["phone"] = itemotn.F_Phone;
                    string ans = "";
                    #region 答案
                    var anslist = ansBLL.GetModelList(" F_CusTelID=" + itemotn.F_Id + sqlans);
                    if (anslist.Count > 0)
                    {
                        string anan = "";
                        foreach (var ansitem in anslist)
                        {
                            anan += ansitem.F_Answer + ";";
                        }
                        ans = anan.Trim(';') + "。";
                    }
                    #endregion
                    dr["answer"] = ans;
                    dtnew.Rows.Add(dr);
                }
            }
            return dtnew;
        }
        #endregion
        #region 表头
        public ActionResult GetColoumnBMY(string TaskID, int quesid = 0)
        {
            string[] col = getcoloumn(TaskID, quesid);

            return Success("获取详细报表表头成功", col);

        }
        public string[] getcoloumn(string TaskID, int quesid = 0)
        {
            string sqlques = "F_QuestionId=" + quesid;
            var quesmodel = questionBLL.GetModel(quesid);
            var ques = "";
            if (quesmodel != null)
            {
                ques = quesmodel.F_Title;

            }
            string[] col = { "姓名", "电话", ques };
            return col;
        }
        #endregion
        #region 导出
        public ActionResult GetReportBMYExpt(string TaskID, string ansids, string sdate, string edate, int quesid)
        {
            DataTable dtnew = getdateBMY(TaskID, quesid, ansids, sdate, edate);
            NPOIHelper npoi = new NPOIHelper();
            string[] col = getcoloumn(TaskID, quesid);
            if (npoi.ExportToExcel("详细报表数据", dtnew, col) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
        }
        #endregion
        #endregion

        #region 下拉框
        /// <summary>
        /// 任务列表下拉
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTaskDDL()
        {
            var alllist = otBLL.GetModelList(" F_DeleteFlag=0 order by F_TaskID desc");
            return Success("获取任务列表下拉成功", alllist);
        }
        /// <summary>
        /// 问题列表下拉
        /// </summary>
        /// <returns></returns>
        public ActionResult GetQuesDDL(int taskid = 0)
        {
            string sql = "";
            if (taskid > 0)
            {
                sql += " and 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 + "') )";
            }
            var list = questionBLL.GetModelList(" F_Type!=1" + sql);
            return Success("获取问题列表下拉成功", list);
        }
        /// <summary>
        /// 问题选项列表下拉
        /// </summary>
        /// <returns></returns>
        public ActionResult GetQuesItemDDL(int quesid = 0)
        {
            string sql = " 1=1 ";
            if (quesid > 0)
            {
                sql += " and F_QuestionId=" + quesid;
            }
            var list = questionItemBLL.GetModelList(sql);
            return Success("获取问题选项列表下拉成功", list);
        }
        #endregion


        #region 文档里四个报表 ；
        //1、给六大问题得分汇总报表

        public ActionResult GetTypeScore(string sdate, string edate,int export=0)
        {
            DataTable dtnew = getTypeSore(sdate, edate);

            if (export==1)
            {

                NPOIHelper npoi = new NPOIHelper();          
                string[] ccc = {

                    "问题分类","10分","9分","8分","7分","6分","5分","4分","3分","2分","1分","合计","低分占比（9分以下）"
            };

                if (npoi.ExportToExcel("六大问题得分汇总数据", dtnew, ccc) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            return Success("获取成功", dtnew);

        }

        public DataTable getTypeSore(string sdate, string edate)
        {
            StringBuilder wheresql = new StringBuilder();
            if (!string.IsNullOrWhiteSpace(sdate))
                wheresql.Append(" and DATEDIFF(day,F_CreateOn,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                wheresql.Append(" and DATEDIFF(day,F_CreateOn,'" + edate.Trim() + "')>=0");
            


            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("typename");
            DataColumn col = new DataColumn("ten", typeof(System.Int32));
            dtnew.Columns.Add(col);
            col.DefaultValue = 0;

            DataColumn col2 = new DataColumn("nine", typeof(System.Int32));
            dtnew.Columns.Add(col2);
            col2.DefaultValue = 0;

            DataColumn col3 = new DataColumn("eight", typeof(System.Int32));
            dtnew.Columns.Add(col3);
            col3.DefaultValue = 0;

            DataColumn col4 = new DataColumn("seven", typeof(System.Int32));
            dtnew.Columns.Add(col4);
            col4.DefaultValue = 0;

            DataColumn col5 = new DataColumn("six", typeof(System.Int32));
            dtnew.Columns.Add(col5);
            col5.DefaultValue = 0;

            DataColumn col6 = new DataColumn("five", typeof(System.Int32));
            dtnew.Columns.Add(col6);
            col6.DefaultValue = 0;

            DataColumn col7 = new DataColumn("four", typeof(System.Int32));
            dtnew.Columns.Add(col7);
            col7.DefaultValue = 0;


            DataColumn col8 = new DataColumn("three", typeof(System.Int32));
            dtnew.Columns.Add(col8);
            col8.DefaultValue = 0;
            DataColumn col9 = new DataColumn("two", typeof(System.Int32));
            dtnew.Columns.Add(col9);
            col9.DefaultValue = 0;
            DataColumn col10 = new DataColumn("one", typeof(System.Int32));
            dtnew.Columns.Add(col10);
            col10.DefaultValue = 0;

            DataColumn col11 = new DataColumn("sum", typeof(System.Int32));
            dtnew.Columns.Add(col11);
            col11.DefaultValue = 0;
            DataColumn col12 = new DataColumn("per", typeof(System.String));
            dtnew.Columns.Add(col12);

            #region 新建输出表
            int sum1 = 0;
            int sum11 = 0;
            #endregion

            BLL.T_TypeResult bll = new BLL.T_TypeResult();
            DataTable dt = DbHelperSQL.Query("SELECT F_typevalue1,COUNT(1) num   FROM   [dbo].[T_TypeResult]    where  F_typename1='移网上网质量' "+ wheresql.ToString()+"    group by F_typevalue1  order by F_typevalue1 desc").Tables[0];

            DataRow dr = dtnew.Rows.Add();
            dr["typename"] = "移网上网质量";

            foreach (DataRow item in dt.Rows)
            {
                switch (item["F_typevalue1"].ToString())
                {
                    case "10分":
                        dr["ten"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        sum11 += Convert.ToInt32(item["num"]);
                        break;
                    case "9分":
                        dr["nine"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        sum11 += Convert.ToInt32(item["num"]);

                        break;
                    case "8分":
                        dr["eight"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                 
                        break;
                    case "7分":
                        dr["seven"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        
                        break;
                    case "6分":
                        dr["six"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        break;
                    case "5分":
                        dr["five"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        break;
                    case "4分":
                        dr["four"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        break;
                    case "3分":
                        dr["three"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        break;
                    case "2分":
                        dr["two"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        break;
                    case "1分":
                        dr["one"] = item["num"];
                        sum1 += Convert.ToInt32(item["num"]);
                        break;

                    default:

                        break;
                }
            }

            dr["sum"] = sum1;

            dr["per"] = sum1 == 0 ? "0" : string.Format("{0:F2}%", ((double)(sum1 - sum11) / sum1) * 100);

            DataTable dt2 = DbHelperSQL.Query("SELECT F_typevalue2,COUNT(1) num   FROM   [dbo].[T_TypeResult]    where  F_typename2='移网通话质量'    " + wheresql.ToString() + "  group by F_typevalue2  order by F_typevalue2 desc").Tables[0];

            int sum2 = 0;
            int sum22 = 0;
            DataRow dr2 = dtnew.Rows.Add();
            dr2["typename"] = "移网通话质量";

            foreach (DataRow item in dt2.Rows)
            {
                switch (item["F_typevalue2"].ToString())
                {
                    case "10分":
                        dr2["ten"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        sum22 += Convert.ToInt32(item["num"]);
                        break;
                    case "9分":
                        dr2["nine"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        sum22 += Convert.ToInt32(item["num"]);
                        break;
                    case "8分":
                        dr2["eight"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        
                        break;
                    case "7分":
                        dr2["seven"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                    
                        break;
                    case "6分":
                        dr2["six"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        break;
                    case "5分":
                        dr2["five"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        break;
                    case "4分":
                        dr2["four"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        break;
                    case "3分":
                        dr2["three"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        break;
                    case "2分":
                        dr2["two"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        break;
                    case "1分":
                        dr2["one"] = item["num"];
                        sum2 += Convert.ToInt32(item["num"]);
                        break;

                    default:

                        break;
                }
            }
            dr2["sum"] = sum2;

            dr2["per"] = sum2 == 0 ? "0" : string.Format("{0:F2}%", ((double)(sum2 - sum22) / sum2) * 100);

            DataTable dt3 = DbHelperSQL.Query("SELECT F_typevalue3,COUNT(1) num   FROM   [dbo].[T_TypeResult]    where  F_typename3='光网网络质量'  " + wheresql.ToString() + "    group by F_typevalue3  order by F_typevalue3 desc").Tables[0];
            int sum3 = 0;
            int sum33 = 0;
            DataRow dr3 = dtnew.Rows.Add();
            dr3["typename"] = "光网网络质量";
            foreach (DataRow item in dt3.Rows)
            {
                switch (item["F_typevalue3"].ToString())
                {
                    case "10分":
                        dr3["ten"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                        sum33 += Convert.ToInt32(item["num"]);
                        break;
                    case "9分":
                        dr3["nine"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                        sum33 += Convert.ToInt32(item["num"]);
                        break;
                    case "8分":
                        dr3["eight"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                      
                        break;
                    case "7分":
                        dr3["seven"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                 
                        break;
                    case "6分":
                        dr3["six"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                        break;
                    case "5分":
                        dr3["five"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                        break;
                    case "4分":
                        dr3["four"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                        break;
                    case "3分":
                        dr3["three"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                        break;
                    case "2分":
                        dr3["two"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                        break;
                    case "1分":
                        dr3["one"] = item["num"];
                        sum3 += Convert.ToInt32(item["num"]);
                        break;

                    default:

                        break;
                }
            }
            dr3["sum"] = sum3;

            dr3["per"] = sum3 == 0 ? "0" : string.Format("{0:F2}%", ((double)(sum3 - sum33) / sum3) * 100);

            DataTable dt4 = DbHelperSQL.Query("SELECT F_typevalue4,COUNT(1) num   FROM   [dbo].[T_TypeResult]    where  F_typename4='装维服务' " + wheresql.ToString() + "     group by F_typevalue4  order by F_typevalue4 desc").Tables[0];

            int sum4 = 0;
            int sum44 = 0;
            DataRow dr4 = dtnew.Rows.Add();
            dr4["typename"] = "装维服务";
            foreach (DataRow item in dt4.Rows)
            {
                switch (item["F_typevalue4"].ToString())
                {
                    case "10分":
                        dr4["ten"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);
                        sum44 += Convert.ToInt32(item["num"]);
                        break;
                    case "9分":
                        dr4["nine"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);
                        sum44 += Convert.ToInt32(item["num"]);
                        break;
                    case "8分":
                        dr4["eight"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);
                        
                        break;
                    case "7分":
                        dr4["seven"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);
                     
                        break;
                    case "6分":
                        dr4["six"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);
                        break;
                    case "5分":
                        dr4["five"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);
                        break;
                    case "4分":
                        dr4["four"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);
                        break;
                    case "3分":
                        dr4["three"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);

                        break;
                    case "2分":
                        dr4["two"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);

                        break;
                    case "1分":
                        dr4["one"] = item["num"];
                        sum4 += Convert.ToInt32(item["num"]);

                        break;

                    default:

                        break;
                }
            }
            dr4["sum"] = sum4;

            dr4["per"] = sum4 == 0 ? "0" : string.Format("{0:F2}%", ((double)(sum4 - sum44) / sum4) * 100);

            DataTable dt5 = DbHelperSQL.Query("SELECT F_typevalue5,COUNT(1) num   FROM   [dbo].[T_TypeResult]    where  F_typename5='营业厅服务'    " + wheresql.ToString() + "  group by F_typevalue5  order by F_typevalue5 desc").Tables[0];
            int sum5 = 0;
            int sum55 = 0;
            DataRow dr5 = dtnew.Rows.Add();
            dr5["typename"] = "营业厅服务";
            foreach (DataRow item in dt5.Rows)
            {
                switch (item["F_typevalue5"].ToString())
                {
                    case "10分":
                        dr5["ten"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                        sum55 += Convert.ToInt32(item["num"]);
                        break;
                    case "9分":
                        dr5["nine"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                        sum55 += Convert.ToInt32(item["num"]);
                        break;
                    case "8分":
                        dr5["eight"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                      
                        break;
                    case "7分":
                        dr5["seven"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                   
                        break;
                    case "6分":
                        dr5["six"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                        break;
                    case "5分":
                        dr5["five"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                        break;
                    case "4分":
                        dr5["four"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                        break;
                    case "3分":
                        dr5["three"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                        break;
                    case "2分":
                        dr5["two"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                        break;
                    case "1分":
                        dr5["one"] = item["num"];
                        sum5 += Convert.ToInt32(item["num"]);
                        break;

                    default:

                        break;
                }
            }
            dr5["sum"] = sum5;

            dr5["per"] = sum5 == 0 ? "0" : string.Format("{0:F2}%", ((double)(sum5 - sum55) / sum5) * 100);

            DataTable dt6 = DbHelperSQL.Query("SELECT F_typevalue6,COUNT(1) num   FROM   [dbo].[T_TypeResult]    where  F_typename6='资费政策'   " + wheresql.ToString() + "   group by F_typevalue6  order by F_typevalue6 desc").Tables[0];
            int sum6 = 0;
            int sum66 = 0;
            DataRow dr6 = dtnew.Rows.Add();
            dr6["typename"] = "资费政策";
            foreach (DataRow item in dt6.Rows)
            {
                switch (item["F_typevalue6"].ToString())
                {
                    case "10分":
                        dr6["ten"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                        sum66 += Convert.ToInt32(item["num"]);
                        break;
                    case "9分":
                        dr6["nine"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                        sum66 += Convert.ToInt32(item["num"]);
                        break;
                    case "8分":
                        dr6["eight"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                 
                        break;
                    case "7分":
                        dr6["seven"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                      
                        break;
                    case "6分":
                        dr6["six"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                        break;
                    case "5分":
                        dr6["five"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                        break;
                    case "4分":
                        dr6["four"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                        break;
                    case "3分":
                        dr6["three"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                        break;
                    case "2分":
                        dr6["two"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                        break;
                    case "1分":
                        dr6["one"] = item["num"];
                        sum6 += Convert.ToInt32(item["num"]);
                        break;

                    default:

                        break;
                }
            }
            dr6["sum"] = sum6;

            dr6["per"] = sum6 == 0 ? "0" : string.Format("{0:F2}%", ((double)(sum6 - sum66) / sum6) * 100);


            DataRow dr7 = dtnew.Rows.Add();
            dr7["typename"] = "合计";
            dr7["ten"] = (from d in dtnew.AsEnumerable() select d.Field<int>("ten")).ToList().Sum();
            dr7["nine"] = (from d in dtnew.AsEnumerable() select d.Field<int>("nine")).ToList().Sum();
            dr7["eight"] = (from d in dtnew.AsEnumerable() select d.Field<int>("eight")).ToList().Sum();
            dr7["seven"] = (from d in dtnew.AsEnumerable() select d.Field<int>("seven")).ToList().Sum();
            dr7["six"] = (from d in dtnew.AsEnumerable() select d.Field<int>("six")).ToList().Sum();
            dr7["five"] = (from d in dtnew.AsEnumerable() select d.Field<int>("five")).ToList().Sum();
            dr7["four"] = (from d in dtnew.AsEnumerable() select d.Field<int>("four")).ToList().Sum();
            dr7["three"] = (from d in dtnew.AsEnumerable() select d.Field<int>("three")).ToList().Sum();
            dr7["two"] = (from d in dtnew.AsEnumerable() select d.Field<int>("two")).ToList().Sum();
            dr7["one"] = (from d in dtnew.AsEnumerable() select d.Field<int>("one")).ToList().Sum();
            dr7["sum"] = (from d in dtnew.AsEnumerable() select d.Field<int>("sum")).ToList().Sum();
            if (dr7["sum"].ToString()!="0")
            {
                             string.Format("{0:F2}%", ((double)(sum5 - sum55) / sum5) * 100);
                dr7["per"] = string.Format("{0:F2}%", ((double)((int)dr7["eight"] +(int)dr7["seven"] +(int)dr7["six"] + (int)dr7["five"] + (int)dr7["four"] + (int)dr7["three"] + (int)dr7["two"] + (int)dr7["one"]) / (int)dr7["sum"]) * 100);

            }
            else
            {
                dr7["per"] = 0;
            }


            return dtnew;
        }

        //2、呼叫明细列表和报表

        public ActionResult GetDetail(string sdate, string edate, int export = 0, int taskid=0,int pagesize = 10, int pageindex = 1)
        {
            //目标用户 营业部 号码 是否接通  通话时长 外呼人 外呼时间 移网上网质量 移网通话质量 宽带网络质量  装维服务  
            //营业厅服务 资费政策 问题内容 问题处理情况  是否处理
           // string tablenew = "(select  b.F_Id,ExpandVchField1,Expandfield2,F_Phone ,F_HJJGName ,(select TalkLongTime from T_Call_CallRecords where CallId=b.callid) talktime,F_UserName,a.F_createon,a.F_typeValue1,a.F_typeValue2 ,a.F_typeValue3 ,a.F_typeValue4 ,a.F_typeValue5 ,a.F_typeValue6 from  T_TypeResult a left join  T_Call_OutTaskTelNum b on a.F_phoneid = b.F_Id ) as t";
           string tablenew = "(select F_FPState,F_DeleteFlag,F_TaskId,  b.F_Id,ExpandVchField1,Expandfield2,F_Phone ,F_HJJGName ," +
                " (case when b.CallId is not null and b.CallId !='' then '是' else ( case  when ExpandSintField5 = 1  then '否' else '未拨打' end) end)CallState ,(select TalkLongTime from T_Call_CallRecords where CallId=b.callid) talktime,F_UserName,a.F_createon,a.F_typeValue1,a.F_typeValue2 ,a.F_typeValue3 ,a.F_typeValue4 ,a.F_typeValue5 ,a.F_typeValue6   from  T_Call_OutTaskTelNum b left join  T_TypeResult a  on a.F_phoneid = b.F_Id  left join T_Wo_WorkOrder c on c.WjID=b.F_id) as t";
            StringBuilder wheresql = new StringBuilder();
            wheresql.Append(" and F_HJJGName is not null and  F_FPState = 1 and F_DeleteFlag = 0 ");
            if (!string.IsNullOrWhiteSpace(sdate))
                wheresql.Append(" and DATEDIFF(day,F_createon,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                wheresql.Append(" and DATEDIFF(day,F_createon,'" + edate.Trim() + "')>=0");

            if (taskid != 0)
            {

                wheresql.Append(" and F_TaskId='"+taskid+"'  "); 
            }

            if (export == 1)
            {
                NPOIHelper npoi = new NPOIHelper();

                DataTable dtt = DbHelperSQL.Query("select * from " + tablenew +" where 1=1  " + wheresql.ToString()+ " ORDER BY F_createon desc").Tables[0];

                dtt.Columns.Remove("F_Id");
                dtt.Columns.Remove("F_TaskId");
                dtt.Columns.Remove("F_FPState");
                dtt.Columns.Remove("F_DeleteFlag");

                string[] ccc = {

                    "目标用户","营业部","号码","修复结果","是否接通","通话时长","外呼人","外呼时间","移网上网质量","移网通话质量","宽带网络质量","装维服务","营业厅服务","资费政策"//,"问题登记","问题处理情况"

                };

                if (npoi.ExportToExcel("呼叫明细报表", dtt, ccc) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }

              

            }

            int recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    tablenew,
                    "F_Id",
                    "*",
                    wheresql.ToString(),
                    "ORDER BY F_createon desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }
 

        //4、营业部热点问题统计

        List<string> arrlist = new List<string>(); //排列顺序的item项id
        DataTable dtNew = new DataTable();
        //获取表头
        public ActionResult GetColumnListT()
        {

            List<Model.QCModel> qclist = new List<Model.QCModel>();

            #region 加载固定项
            DataColumn dc1 = new DataColumn("SaleOffice", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("HJCount", Type.GetType("System.String"));

            dtNew.Columns.Add(dc1);
            dtNew.Columns.Add(dc2);

            Model.QCModel qcm1 = new Model.QCModel();
            qcm1.Qcid = "yyb1";
            qcm1.Qcname = "营业部";
            qcm1.Rowspan = "2";
            Model.QCModel qcm2 = new Model.QCModel();
            qcm2.Qcid = "hjzs2";
            qcm2.Qcname = "呼叫总数";
            qcm2.Rowspan = "2";

            qclist.Add(qcm1);
            qclist.Add(qcm2);
            #endregion



            DataSet ds = DbHelperSQL.Query(" select a.F_CategoryId,b.F_CategoryName,a.F_QuestionId  from  T_Ask_Question a left join T_Ask_QuestionCategory b on a.F_CategoryId=b.F_CategoryId where   b.F_CategoryName in ('移网上网质量', '移网通话质量', '资费政策', '营业厅服务', '装维服务', '光网网络质量') and F_SortModel = 1");

            DataSet dsitem = DbHelperSQL.Query("  select * from [T_Ask_QuestionItems] ");

            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    DataTable dtitem = dsitem.Tables[0];

                    Model.QCModel qcml = new Model.QCModel();
                    qcml.Qcid = dt.Rows[i]["F_CategoryId"].ToString();
                    qcml.Qcname = dt.Rows[i]["F_CategoryName"].ToString();
                    int questionid = Convert.ToInt32(dt.Rows[i]["F_QuestionId"].ToString());
                    DataRow[] dritems = dtitem.Select("F_QuestionId='" + questionid + "'");

                    var var_dttable = dtitem.AsEnumerable().Where<DataRow>(w => Convert.ToInt32(w["F_QuestionId"]) == questionid);
                    int count = var_dttable.Count<DataRow>();
                    qcml.Colspan = count.ToString();
                    List<Model.QCModel> qccllist = new List<Model.QCModel>();
                    for (int j = 0; j < count; j++)
                    {
                        Model.QCModel qccmll = new Model.QCModel();
                        qccmll.Qcid = dt.Rows[i]["F_CategoryId"].ToString() + "-" + questionid +"-"+ dritems[j]["F_ItemId"].ToString();
                        qccmll.Qcname = dritems[j]["F_ItemName"].ToString();

                        DataColumn dc = new DataColumn("Q" + dritems[j]["F_ItemId"].ToString(), Type.GetType("System.String"));
                        dtNew.Columns.Add(dc);

                        qccllist.Add(qccmll);
                        arrlist.Add(dritems[j]["F_ItemId"].ToString());

                    }
                    qcml.Qclist = qccllist;

                    qclist.Add(qcml);
                }

            }


            return Success("获取质检表头成功", qclist);

            #endregion



        }


        public ActionResult GetSaleOfficeHotQuestionDataList(string stime, string endtime,int taskid=0)
        {
            GetColumnListT();
            #region 加载固定项


            string sql = "select F_DeptId,F_DeptName from T_Sys_Department where F_State=1  and F_ParentId!=0 and F_ParentName is not null ";
            DataTable dtdept = DbHelperSQL.Query(sql).Tables[0];
            BLL.T_Sys_UserAccount bll = new BLL.T_Sys_UserAccount();      
            var userlist=    bll.GetModelList(" F_DeleteFlag=0");
            string sqltimeCallRecords = "";
            if (stime != null && stime.Trim() != "")
            {
                sqltimeCallRecords += " and CONVERT(varchar , ExpandDatField1, 120)>=CONVERT(varchar , '" + stime.Trim() + " 00:00:01', 120) ";
            }
            if (endtime != null && endtime.Trim() != "")
            {
                sqltimeCallRecords += " and CONVERT(varchar , ExpandDatField1, 120)<=CONVERT(varchar , '" + endtime.Trim() + " 23:59:59', 120) ";
            }
            int pageid = Int32.Parse(Configs.GetValue("pageid"));

            string countsql = "";
            if (taskid != 0)
            {
                countsql = "select F_UserId, count(1) num from T_Call_OutTaskTelNum    where   F_TaskId ='"+taskid+ "'  and F_HJJGName is not null and F_FPState = 1 and F_DeleteFlag = 0" + sqltimeCallRecords + "   group by F_UserId ";
            }

            else {
                countsql = "select F_UserId, count(1) num from T_Call_OutTaskTelNum    where   F_TaskId in  (select F_TaskId from dbo.T_Call_OutTask where F_PagerID = '" + pageid + "'  )   and F_HJJGName is not null and F_FPState = 1 and F_DeleteFlag = 0" + sqltimeCallRecords + "   group by F_UserId ";
            }


            //userid  和呼叫总数  
            DataTable dtuserhj = DbHelperSQL.Query(countsql).Tables[0];
            string answerstimesql =" where 1=1 ";
            if (stime != null && stime.Trim() != "")
            {
                answerstimesql += " and CONVERT(varchar , F_OptOn, 120)>=CONVERT(varchar , '" + stime.Trim() + " 00:00:01', 120) ";
            }
            if (endtime != null && endtime.Trim() != "")
            {
                answerstimesql += " and CONVERT(varchar , F_OptOn, 120)<=CONVERT(varchar , '" + endtime.Trim() + " 23:59:59', 120) ";
            }

            if (taskid != 0)
            {
                answerstimesql += " and F_TaskID='"+taskid+"' ";
            }


            //answer表分组查询userid，num，选项id
            string answers = "  select F_OptBy F_UserId, F_QIID, COUNT(1) num from  dbo.T_Call_OutAnswers "+ answerstimesql+"   group by F_OptBy,F_QIID";

            DataTable dtanswers = DbHelperSQL.Query(answers).Tables[0];

            foreach (DataRow dr  in dtdept.Rows)
            {
                DataRow drNew = dtNew.NewRow();
                int depid = Convert.ToInt32( dr["F_DeptId"]);
                drNew["SaleOffice"] = dr["F_DeptName"];
                int hjcount = 0;
                var userlistdept=   userlist.Where(x=>x.F_DeptId == depid).Select(x=>x.F_UserId).ToList();
                string userstr = "";
                foreach (int item in userlistdept)
                {
                    DataRow drs = dtuserhj.Select("F_UserId='" + item + "'").FirstOrDefault();
                    if (drs != null)
                    {
                        hjcount += Convert.ToInt32(drs["num"]);
                    }
                    
                    userstr += item + ",";
                }          
                drNew["HJCount"] = hjcount;        

                userstr = userstr.Remove(userstr.Length - 1, 1);
               // DataRow[] dranswers = dtanswers.Select(" F_UserId in (" + userstr + ")");
                foreach (string  item in arrlist) //答案项的id
                {
                    //drNew["Q" + item] = dtanswers.Compute("Sum(num)", "F_UserId in (" + userstr + ") and F_QIID='" + item + "'").ToString();
                    drNew["Q" + item] = dtanswers.Select(" F_UserId in (" + userstr + ") and F_QIID='"+ item + "' ").Sum(x=>x.Field<int>("num"));                    
                }
                dtNew.Rows.Add(drNew);
            }

            if (dtNew.Rows.Count > 0)
            {
                DataRow drnew = dtNew.NewRow();
                drnew["SaleOffice"] = "合计";
                drnew["HJCount"] = dtuserhj.Select("").Sum(x => x.Field<int>("num"));
                foreach (string item in arrlist) //答案项的id
                {
                    //drnew["Q" + item] = dtanswers.Compute("Sum(num)", "F_QIID='" + item + "'").ToString();
                    drnew["Q" + item] = dtanswers.Select(" F_QIID='" + item + "' ").Sum(x => x.Field<int>("num"));
                }
                dtNew.Rows.Add(drnew);
            }
            return Success("获取营业部热点问题统计成功", dtNew);
        }


        public ActionResult ExportSaleOfficeHotQuestionData(string stime, string endtime, int taskid = 0)
        {
            DataTable dtNew2 = new DataTable();
            List<Model.QCModel> qclist = new List<Model.QCModel>();
            #region 加载固定项
            DataColumn dc1 = new DataColumn("SaleOffice", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("HJCount", Type.GetType("System.String"));
            dtNew2.Columns.Add(dc1);
            dtNew2.Columns.Add(dc2);

            #endregion

            #region 获取表头
            List<Model.CModel> clist = new List<Model.CModel>();
            Model.CModel qcm1 = new Model.CModel();

            qcm1.Cname = "营业部";
            qcm1.Count = 2;
            Model.CModel qcm2 = new Model.CModel();

            qcm2.Cname = "呼叫总数";
            qcm2.Count = 2;
            clist.Add(qcm1);
            clist.Add(qcm2);


            List<string> cidlist = new List<string>(); //排列顺序的item项id

            DataSet ds = DbHelperSQL.Query(" select a.F_CategoryId,b.F_CategoryName,a.F_QuestionId  from  T_Ask_Question a left join T_Ask_QuestionCategory b on a.F_CategoryId=b.F_CategoryId where   b.F_CategoryName in ('移网上网质量', '移网通话质量', '资费政策', '营业厅服务', '装维服务', '光网网络质量') and F_SortModel = 1");

            DataSet dsitem = DbHelperSQL.Query("  select * from [T_Ask_QuestionItems] ");

            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    DataTable dtitem = dsitem.Tables[0];
                    Model.CModel cd = new Model.CModel();

                    cd.Cname = dt.Rows[i]["F_CategoryName"].ToString();



                    int questionid = Convert.ToInt32(dt.Rows[i]["F_QuestionId"].ToString());
                    DataRow[] dritems = dtitem.Select("F_QuestionId='" + questionid + "'");

                    var var_dttable = dtitem.AsEnumerable().Where<DataRow>(w => Convert.ToInt32(w["F_QuestionId"]) == questionid);
                    int count = var_dttable.Count<DataRow>();
                    cd.Count = count;

                    List<Model.CModel> qccllist = new List<Model.CModel>();
                    for (int j = 0; j < count; j++)
                    {
                        Model.CModel qccmll = new Model.CModel();
                        qccmll.Cname = dritems[j]["F_ItemName"].ToString();
                           qccmll.Cid = dritems[j]["F_ItemId"].ToString();
                        qccmll.Count = 0;
                        qccllist.Add(qccmll);

                        DataColumn dc4 = new DataColumn("Q"+qccmll.Cid , Type.GetType("System.String"));
                       
                        dtNew2.Columns.Add(dc4);


                        cidlist.Add(dritems[j]["F_ItemId"].ToString());

                    }
                    cd.Clist = qccllist;

                    clist.Add(cd);
                }

            }
            #endregion


            #region 获取数据
            string sql = "select F_DeptId,F_DeptName from T_Sys_Department where F_State=1  and F_ParentId!=0 and F_ParentName is not null ";
            DataTable dtdept = DbHelperSQL.Query(sql).Tables[0];
            BLL.T_Sys_UserAccount bll = new BLL.T_Sys_UserAccount();
            var userlist = bll.GetModelList(" F_DeleteFlag=0");
            string sqltimeCallRecords = "";
            if (stime != null && stime.Trim() != "")
            {
                sqltimeCallRecords += " and CONVERT(varchar , ExpandDatField1, 120)>=CONVERT(varchar , '" + stime.Trim() + " 00:00:01', 120) ";
            }
            if (endtime != null && endtime.Trim() != "")
            {
                sqltimeCallRecords += " and CONVERT(varchar , ExpandDatField1, 120)<=CONVERT(varchar , '" + endtime.Trim() + " 23:59:59', 120) ";
            }

            int pageid = Int32.Parse(Configs.GetValue("pageid"));
            //  string countsql = "select F_UserId, count(1) num from T_Call_OutTaskTelNum    where   F_TaskId in  (select F_TaskId from dbo.T_Call_OutTask where F_PagerID = '" + pageid + "'  )   and F_HJJGName is not null" + sqltimeCallRecords + "   group by F_UserId ";

          

            string countsql = "";
            if (taskid != 0)
            {
                countsql = "select F_UserId, count(1) num from T_Call_OutTaskTelNum    where   F_TaskId ='" + taskid + "'  and F_HJJGName is not null and F_FPState = 1 and F_DeleteFlag = 0 " + sqltimeCallRecords + "   group by F_UserId ";
            }

            else
            {
                countsql = "select F_UserId, count(1) num from T_Call_OutTaskTelNum    where   F_TaskId in  (select F_TaskId from dbo.T_Call_OutTask where F_PagerID = '" + pageid + "'  )   and F_HJJGName is not null and F_FPState = 1 and F_DeleteFlag = 0 " + sqltimeCallRecords + "   group by F_UserId ";
            }

            //userid  和呼叫总数  
            DataTable dtuserhj = DbHelperSQL.Query(countsql).Tables[0];
            string answerstimesql = " where 1=1 ";
            if (stime != null && stime.Trim() != "")
            {
                answerstimesql += " and CONVERT(varchar , F_OptOn, 120)>=CONVERT(varchar , '" + stime.Trim() + " 00:00:01', 120) ";
            }
            if (endtime != null && endtime.Trim() != "")
            {
                answerstimesql += " and CONVERT(varchar , F_OptOn, 120)<=CONVERT(varchar , '" + endtime.Trim() + " 23:59:59', 120) ";
            }
             if (taskid != 0)
            {
                answerstimesql += " and F_TaskID='"+taskid+"' ";
            }


            //answer表分组查询userid，num，选项id
            string answers = "  select F_OptBy F_UserId, F_QIID, COUNT(1) num from  dbo.T_Call_OutAnswers " + answerstimesql + "   group by F_OptBy,F_QIID";

            DataTable dtanswers = DbHelperSQL.Query(answers).Tables[0];

            foreach (DataRow dr in dtdept.Rows)
            {
                DataRow drNew = dtNew2.NewRow();
                int depid = Convert.ToInt32(dr["F_DeptId"]);
               drNew["SaleOffice"] = dr["F_DeptName"];
                int hjcount = 0;
                var userlistdept = userlist.Where(x => x.F_DeptId == depid).Select(x => x.F_UserId).ToList();
                string userstr = "";
                foreach (int item in userlistdept)
                {
                    DataRow drs = dtuserhj.Select("F_UserId='" + item + "'").FirstOrDefault();
                    if (drs != null)
                    {
                        hjcount += Convert.ToInt32(drs["num"]);
                    }

                    userstr += item + ",";
                }
                drNew["HJCount"] = hjcount;

                userstr = userstr.Remove(userstr.Length - 1, 1);

                DataRow[] dranswers = dtanswers.Select(" F_UserId in (" + userstr + ")");

                foreach (string item in cidlist) //答案项的id
                {
                    drNew["Q" + item] = dtanswers.Select(" F_UserId in (" + userstr + ") and F_QIID='" + item + "' ").Sum(x => x.Field<int>("num"));
                }
                dtNew2.Rows.Add(drNew);          

               
            }

            if (dtNew2.Rows.Count > 0)
            {
                DataRow drnew = dtNew2.NewRow();
                drnew["SaleOffice"] = "合计";
                drnew["HJCount"] = dtuserhj.Select("").Sum(x => x.Field<int>("num"));
                foreach (string item in cidlist) //答案项的id
                {
                    //drnew["Q" + item] = dtanswers.Compute("Sum(num)", "F_QIID='" + item + "'").ToString();
                    drnew["Q" + item] = dtanswers.Select(" F_QIID='" + item + "' ").Sum(x => x.Field<int>("num"));
                }
                dtNew2.Rows.Add(drnew);
            }

            #endregion
            ExportToExcelHeBing("营业部热点问题统计", dtNew2, clist);
            return Success("");
        

        }
  
        public string ExportToExcelHeBing(string Name, DataTable dt, List<Model.CModel> clist)
        {
            //HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            //ISheet sheet = hssfworkbook.CreateSheet("营业部热点统计");

            //起始行，结束行，起始列，结束列
            // sheet.AddMergedRegion(new CellRangeAddress(0,0,0,10));           
            try
            {                
                HSSFWorkbook workbook = new HSSFWorkbook();//导出xls
                ISheet sheet = workbook.CreateSheet("sheet1");

                ICellStyle HeadercellStyle = workbook.CreateCellStyle();
                HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.Alignment = HorizontalAlignment.Center;
                HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
                HeadercellStyle.FillPattern = FillPattern.SolidForeground;
                HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;

                //字体
                NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
                headerfont.Boldweight = (short)FontBoldWeight.Bold;
                headerfont.FontHeightInPoints = 12;
                HeadercellStyle.SetFont(headerfont);


                //用column name 作为列名
                int icolIndex = 0;
                IRow headerRow = sheet.CreateRow(0);

                IRow headerRow1 = sheet.CreateRow(1);

                ICell cell3 = headerRow.CreateCell(icolIndex);
                cell3.SetCellValue("营业部");
                cell3.CellStyle = HeadercellStyle;
                icolIndex++;
                ICell cell2 = headerRow.CreateCell(icolIndex);
                cell2.SetCellValue("呼叫总数");
                cell2.CellStyle = HeadercellStyle;
                icolIndex++;

                ICell c1 = headerRow1.CreateCell(0);
                c1.SetCellValue("");
                c1.CellStyle = HeadercellStyle;
                ICell c2= headerRow1.CreateCell(1);
                c2.SetCellValue("");
                c2.CellStyle = HeadercellStyle;

                //起始行，结束行，起始列，结束列
                sheet.AddMergedRegion(new CellRangeAddress(0, 1, 0, 0));
                sheet.AddMergedRegion(new CellRangeAddress(0, 1, 1, 1));

                if (clist == null || (clist != null && clist.Count == 0))
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(dc.ColumnName);
                        cell.CellStyle = HeadercellStyle;                   

                        icolIndex++;
                    }
                }
                else
                {
                    foreach (Model.CModel  dc in clist)
                    {
                        if (dc.Clist!=null && dc.Clist.Count != 0)
                        {
                            ICell cell = headerRow.CreateCell(icolIndex);
                            cell.SetCellValue(dc.Cname);
                            cell.CellStyle = HeadercellStyle;
                            int i = icolIndex;
                            foreach (Model.CModel item in dc.Clist)
                            {
                               
                                ICell celll = headerRow1.CreateCell(i);
                                celll.SetCellValue(item.Cname);
                                celll.CellStyle = HeadercellStyle;
                                i++;
                            }

                            for (int j = 0; j < dc.Clist.Count; j++)
                            {
                                ICell ce = headerRow.CreateCell(icolIndex);
                                ce.SetCellValue(dc.Cname);
                                ce.CellStyle = HeadercellStyle;
                                j++;
                               
                            }

                            //起始行，结束行，起始列，结束列
                            sheet.AddMergedRegion(new CellRangeAddress(0, 0, icolIndex, icolIndex + dc.Clist.Count-1));
                          icolIndex= icolIndex + dc.Count;
                        }
                    }
                }
                ICellStyle cellStyle = workbook.CreateCellStyle();

                //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
                cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;


                NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
                cellfont.Boldweight = (short)FontBoldWeight.Normal;
                cellStyle.SetFont(cellfont);

                //建立内容行
                int iRowIndex = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    int iCellIndex = 0;
                    IRow irow = sheet.CreateRow(iRowIndex + 2);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string strsj = string.Empty;
                        if (dr[i] != null)
                        {
                            strsj = dr[i].ToString();
                        }
                        ICell cell = irow.CreateCell(iCellIndex);
                        cell.SetCellValue(strsj);
                        cell.CellStyle = cellStyle;
                        iCellIndex++;
                    }
                    iRowIndex++;
                }

              
                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);

                    HttpContext curContext = System.Web.HttpContext.Current;


                    // 设置编码和附件格式
                    curContext.Response.ContentType = "application/vnd.ms-excel";
                    curContext.Response.ContentEncoding = Encoding.UTF8;//Encoding.UTF8;
                    curContext.Response.Charset = "";
                    curContext.Response.AppendHeader("Content-Disposition",
                        "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));

                    curContext.Response.BinaryWrite(ms.GetBuffer());

                    workbook = null;
                    ms.Close();
                    ms.Dispose();

                    curContext.Response.End();
                }
        
                return "";
            }
            catch
            {
                return "导出失败！";
            }
            
        }


        //5 新增报表（营业部热点问题清单统计表）
        //反映问题是问卷里的问答题；
        //工单的处理情况，问题分类,热点问题;问题分类,热点问题;问题分类,热点问题;问题分类,热点问题;问题分类,热点问题;   
        //处理部门，客户姓名，创建人坐席工号；调查时间；手机号码 


        //搜索条件：营业部；时间，任务名称；手机号码

        

        public ActionResult getSaleOfficeHotQuestionDetailData(string sdate, string edate,string yingyebu,string phone, int export = 0, int taskid = 0, int pagesize = 10, int pageindex = 1)
        {
            string tablenew = "(select   F_TaskId,  b.F_Id, b.F_userid,F_FPState,F_DeleteFlag,ExpandVchField1,Expandfield2,F_Phone,Expandfield3,a.F_typeValue12,a.F_typeValue22  ,a.F_typeValue32 ,a.F_typeValue42 ,a.F_typeValue52  ,a.F_typeValue62 , b.F_UserName createname, a.F_typeValue7,(select  top 1  Clcontent from T_Wo_WorkOrder where  WjID = b.F_id   ) Clcontent,b.ExpandDatField1, (case when b.CallId is not null and b.CallId !='' then '是' else ( case  when ExpandSintField5 = 1  then '否' else '未拨打' end) end)CallState ,b.F_HJJGName,ISNULL( d.TalkLongTime,0) TalkTime   from T_Call_OutTaskTelNum b left join T_TypeResult a on a.F_phoneid = b.F_Id    left join T_Call_CallRecords d on b.CallId=d.CallId ) as t";
            StringBuilder wheresql = new StringBuilder();
            wheresql.Append(" and F_HJJGName is not null and F_FPState = 1 and F_DeleteFlag = 0");
            if (!string.IsNullOrWhiteSpace(sdate))
                wheresql.Append(" and DATEDIFF(day,ExpandDatField1,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                wheresql.Append(" and DATEDIFF(day,ExpandDatField1,'" + edate.Trim() + "')>=0");

            if (!string.IsNullOrWhiteSpace(yingyebu))
            {
                wheresql.Append(" and  F_userid in ( select F_userid from T_Sys_UserAccount where F_DeptId ='"+ yingyebu + "' )");
            }
            //    wheresql.Append(" and Expandfield2='"+ yingyebu + "' ");

            if (!string.IsNullOrWhiteSpace(phone))
                wheresql.Append(" and F_Phone='" + phone + "' ");
            if (taskid != 0)
            {

                wheresql.Append(" and F_TaskId='" + taskid + "'  ");
            }

            if (export == 1)
            {
                NPOIHelper npoi = new NPOIHelper();

                DataTable dtt = DbHelperSQL.Query("select * from " + tablenew + " where 1=1  " + wheresql.ToString() + " ORDER BY ExpandDatField1 desc").Tables[0];

                dtt.Columns.Remove("F_Id");
                dtt.Columns.Remove("F_TaskId");
                dtt.Columns.Remove("F_FPState");
                dtt.Columns.Remove("F_DeleteFlag");
                dtt.Columns.Remove("F_userid");
                
                string[] ccc = {

                   // 目标分类    营业部 号码  宽带账号    问题分类    热点问题    坐席姓名    反映问题    处理结果    呼叫时间    是否接通    呼叫结果

                    "目标用户","营业部","号码","宽带账号","移网上网质量","移网通话质量","光网网络质量","装维服务","营业厅服务","资费政策","坐席姓名","反映问题","处理结果","呼叫时间","是否接通","呼叫结果","通话时长(s)"

                };

                if (npoi.ExportToExcel("营业部热点问题清单统计表", dtt, ccc) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }



            }

            int recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    tablenew,
                    "F_Id",
                    "*",
                    wheresql.ToString(),
                    "ORDER BY ExpandDatField1 desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }




        #endregion
        #region 营业部排名报表，按营业部呼叫量排名（导入的号码的呼叫量）
        public ActionResult GetRank(string sdate, string edate, int taskid=0,int export=0)
        {
            DataTable dtNew2 = new DataTable();
            List<Model.QCModel> qclist = new List<Model.QCModel>();
            #region 加载固定项
            DataColumn dc1 = new DataColumn("SaleOffice", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("HJCount", Type.GetType("System.Int32"));
            dtNew2.Columns.Add(dc1);
            dtNew2.Columns.Add(dc2);
            #endregion
            BLL.T_Sys_UserAccount bll = new BLL.T_Sys_UserAccount();
            var userlist = bll.GetModelList(" F_DeleteFlag=0");

            DataTable dt = new DataTable();
            StringBuilder wheresql = new StringBuilder();
            wheresql.Append(" F_FPState = 1 and F_DeleteFlag = 0 and F_Taskid in (select F_TaskID from T_Call_OutTask where  F_IsStart = 1 and F_DeleteFlag = 0 ) ");

            if (!string.IsNullOrWhiteSpace(sdate))
                wheresql.Append(" and DATEDIFF(day,F_fptime,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                wheresql.Append(" and DATEDIFF(day,F_fptime,'" + edate.Trim() + "')>=0");

            if (taskid != 0)
            {
                wheresql.Append("  and  F_TaskId ='" + taskid + "'");
            }

            string sql = "  select  F_UserId, SUM(case when CallId is not null then 1 else 0 end ) callnum from T_Call_OutTaskTelNum  where  " + wheresql.ToString() + "  group by F_UserId ";
            dt = DbHelperSQL.Query(sql).Tables[0];

            string depsql = "select F_DeptId,F_DeptName from T_Sys_Department where F_State=1  and F_ParentId!=0 and F_ParentName is not null  ";
            DataTable dtdept = DbHelperSQL.Query(depsql).Tables[0];

            foreach (DataRow dr in dtdept.Rows)
            {
                DataRow drNew = dtNew2.NewRow();
                int depid = Convert.ToInt32(dr["F_DeptId"]);
                drNew["SaleOffice"] = dr["F_DeptName"];
                int hjcount = 0;
                var userlistdept = userlist.Where(x => x.F_DeptId == depid).Select(x => x.F_UserId).ToList();
                string userstr = "";
                foreach (int item in userlistdept)
                {
                    DataRow drs = dt.Select("F_UserId='" + item + "'").FirstOrDefault();
                    if (drs != null)
                    {
                        hjcount += Convert.ToInt32(drs["callnum"]);
                    }

                    userstr += item + ",";
                }
                drNew["HJCount"] = hjcount;
                
                dtNew2.Rows.Add(drNew);
            }
         
            DataTable dtMap = null;//创建DataTable


            DataView dv = dtNew2.DefaultView;//dsMap为DataSet数据源
            dv.Sort = "HJCount desc";//r_code为排序字段 
            dtMap = dv.ToTable();//排序完成

            DataColumn dc = null;
            dc = dtMap.Columns.Add("ID", Type.GetType("System.Int32"));
            dc.SetOrdinal(0);
            for (int i = 0; i < dtMap.Rows.Count; i++)
            {
                dtMap.Rows[i]["ID"] = i + 1;
            }


            if (dtMap.Rows.Count > 0)
            {
                DataRow drlast = dtMap.NewRow();//.Rows.Add();
              
                drlast["SaleOffice"] = "合计";
                drlast["HJCount"] = dtNew2.Select("HJCount is not null").Sum(x => x.Field<int>("HJCount"));

                dtMap.Rows.Add(drlast);
            }



            if (export != 0)
            {
                NPOIHelper npoi = new NPOIHelper();
               
                string[] ccc = {
                   "排名", "营业部","呼叫量"

                };

                if (npoi.ExportToExcel("营业部排名报表", dtMap, ccc) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }



            }


            return Success("营业部排名报表获取成功", dtMap);
        }

         public ActionResult GetRankExpt(string sdate, string edate, string taskid)
        {
            DataTable dt = new DataTable();
            return Success("daochu营业部排名报表获取成功", dt);
        }

        #endregion
       
      


        //3、营业部任务汇总表 根据分配时间 的任务量
        //营业部 任务量 呼叫量 呼叫率  呼通量，呼通率，平均通话时长； 
        public ActionResult  GetTaskDetail(string sdate, string edate, int export = 0, int taskid = 0)
        {
            //两个wheresql几乎完全一样，只有一个用到leftjoin的时候会提示f_deleteflag 不明确所以加了一个A.
            StringBuilder wheresql1 = new StringBuilder();
            StringBuilder wheresql = new StringBuilder();
            wheresql1.Append(" F_FPState = 1 and a.F_DeleteFlag = 0 and F_Taskid in (select F_TaskID from T_Call_OutTask where  F_IsStart = 1 and F_DeleteFlag = 0 ) ");
            wheresql.Append(" F_FPState = 1 and F_DeleteFlag = 0 and F_Taskid in (select F_TaskID from T_Call_OutTask where  F_IsStart = 1 and F_DeleteFlag = 0 ) ");

            if (!string.IsNullOrWhiteSpace(sdate))
             
               wheresql.Append(" and DATEDIFF(day,A.begintime,'" + sdate.Trim() + "')<=0");

                 
                wheresql1.Append(" and DATEDIFF(day,F_fptime,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                  wheresql.Append(" and DATEDIFF(day,A.begintime,'" + edate.Trim() + "')>=0");
                wheresql1.Append(" and DATEDIFF(day,F_fptime,'" + edate.Trim() + "')>=0");

            if (taskid != 0)
            {
                wheresql.Append("  and  F_TaskId ='" + taskid + "'");
                wheresql1.Append("  and  F_TaskId ='" + taskid + "'");
            }

      

             string sql = "select b.F_DeptId, COUNT(1) tasknum , SUM(case when CallId is not null and CallId != '' then 1 else 0 end) callnum from T_Call_OutTaskTelNum A left join T_Sys_UserAccount B on A.F_UserId = B.F_UserId where " + wheresql1.ToString() + "  group by B.F_DeptId ";


            string deptsql = "  select distinct a.F_DeptId,b.F_DeptName from [T_Sys_UserAccount] a left join  T_Sys_Department b on a.F_DeptId=b.F_DeptId";


            string hjxqsql = "SELECT   COUNT(1) exhalationflux, ISNULL(SUM(TalkLongTime), 0) talklong,  DBO.GetDeptIdByUserId(B.F_UserId) F_DeptId FROM [dbo]. [T_Call_CallRecords] A INNER JOIN T_Call_OutTaskTelNum B     ON A.CallId=B.CallId" +
                
                " AND B.CallId  is not null and "+wheresql.ToString()+ "  GROUP BY DBO.GetDeptIdByUserId(B.F_UserId)";


            //呼出 接通的电话
            string hjxqsql2 = "SELECT   COUNT(1) exhalationflux,   DBO.GetDeptIdByUserId(B.F_UserId) F_DeptId FROM [dbo]. [T_Call_CallRecords] A INNER JOIN T_Call_OutTaskTelNum B     ON A.CallId=B.CallId" +

                           " AND B.CallId  is not null  and a.CallState=1  and CallType = 1 and " + wheresql.ToString() + "  GROUP BY DBO.GetDeptIdByUserId(B.F_UserId)";



            DataTable deptdt = DbHelperSQL.Query(deptsql).Tables[0];
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];
            DataTable hjxqdt= DbHelperSQL.Query(hjxqsql).Tables[0];

            DataTable hjxqdt2 = DbHelperSQL.Query(hjxqsql2).Tables[0];

            //营业部 任务量 呼叫量 呼叫率  呼通量，呼通率，平均通话时长；


            deptdt.Columns.Add("tasknum", typeof(int)); //任务量
            deptdt.Columns.Add("callnum", typeof(int)); //呼叫量           

            deptdt.Columns.Add("callpercent"); //呼叫率

            deptdt.Columns.Add("exhalationflux", typeof(int));//呼通量

            deptdt.Columns.Add("exhalationper");//呼通率

            deptdt.Columns.Add("talklong");//平均通话时长

            deptdt.Columns.Add("depname");//平均通话时长

             foreach (DataRow dr in deptdt.Rows)
            {
                dr["depname"] = dr["F_DeptName"];

                var dr2 = dt.Select(" F_DeptId='" + dr["F_DeptId"].ToString() + "'");
                dr["tasknum"] = (from DataRow dr1 in dr2 select dr1.Field<int>("tasknum")).FirstOrDefault();
                
                var dr22= hjxqdt2.Select(" F_DeptId='" + dr["F_DeptId"].ToString() + "'");
                dr["exhalationflux"] = (from DataRow dr1 in dr22 select dr1.Field<int>("exhalationflux")).FirstOrDefault();

                var hjxqdr = hjxqdt.Select(" F_DeptId='" + dr["F_DeptId"].ToString() + "'");

                dr["callnum"] = (from DataRow dr1 in hjxqdr select dr1.Field<int>("exhalationflux")).FirstOrDefault();

                int tasknum = Convert.ToInt32(dr["tasknum"].ToString());
                //呼叫量
                int callnum = Convert.ToInt32(dr["callnum"].ToString());
                //呼叫率
                dr["callpercent"] = callnum == 0 ? "0" : string.Format("{0:F2}%", ((double)(callnum) / tasknum) * 100);

                dr["talklong"] = (from DataRow dr1 in hjxqdr select dr1.Field<int>("talklong")).FirstOrDefault();

                int exhalationflux = Convert.ToInt32(dr["exhalationflux"]);
              
                dr["exhalationper"] = Convert.ToInt32(dr["callnum"].ToString()) == 0 ? "0" : string.Format("{0:F2}%", ((double)(exhalationflux) / callnum) * 100);

               int talklong = Convert.ToInt32(dr["talklong"].ToString());
                dr["talklong"] = exhalationflux == 0 ? "0" : string.Format("{0:F2}", ((double)(talklong) / exhalationflux));

            }




            if (deptdt.Rows.Count > 0)
            {
                deptdt.Columns["depname"].SetOrdinal(0);
                deptdt.Columns.Remove("F_DeptId");
                deptdt.Columns.Remove("F_DeptName");

                DataRow drlast = deptdt.NewRow();//.Rows.Add();
                drlast["depname"] = "合计";
                drlast["tasknum"] = deptdt.Select("tasknum is not null").Sum(x => x.Field<int>("tasknum"));
                drlast["callnum"] = deptdt.Select("callnum is not null").Sum(x => x.Field<int>("callnum"));
                drlast["callpercent"] = drlast["callnum"].ToString() == "0" ? "0" : string.Format("{0:F2}%", ((double)(Convert.ToInt32(drlast["callnum"])) / Convert.ToInt32(drlast["tasknum"])) * 100);
                drlast["exhalationflux"] = deptdt.Select().Sum(x => x.Field<int>("exhalationflux"));
                drlast["exhalationper"] = drlast["callnum"].ToString() == "0" ? "0" : string.Format("{0:F2}%", ((double)(Convert.ToInt32(drlast["exhalationflux"])) / Convert.ToInt32(drlast["callnum"])) * 100);

                int talklongsum = hjxqdt.Select().Sum(x => x.Field<int>("talklong"));
                drlast["talklong"] = drlast["exhalationflux"].ToString() == "0" ? "0" : string.Format("{0:F2}", ((double)(talklongsum) / Convert.ToInt32(drlast["exhalationflux"])));
                deptdt.Rows.Add(drlast);
            }
            if (export == 1)
            {
                NPOIHelper npoi = new NPOIHelper();
                string[] ccc = {

                     "营业部","任务量","呼叫量","呼叫率","呼通量","呼通率（%）","平均通话时长"
                };

                if (npoi.ExportToExcel("营业部任务汇总表", deptdt, ccc) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }



            }

            return Success("营业部任务汇总表获取成功", deptdt);
        }


    }
}
