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.quality
{
    public class QCManageController : BaseController
    {
        BLL.T_QCResult qcbll = new BLL.T_QCResult();
        //获取未质检列表
        public ActionResult GetList()
        {
            string sql  = " and F_QCState=0    and CallState='1'  and CallType=1";
            DataTable dt = new DataTable();

            string phone = HttpUtility.UrlDecode(RequestString.GetQueryString("phone"));
            string usercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string startl = HttpUtility.UrlDecode(RequestString.GetQueryString("startl"));
            string endl = HttpUtility.UrlDecode(RequestString.GetQueryString("endl"));
            string optid = HttpUtility.UrlDecode(RequestString.GetQueryString("optid"));

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

       

            if (phone.Trim() != "")
            {
                sql += " and CallNumber like '%" + phone + "%'";
            }
            if (usercode.Trim() != "")
            {
                sql += " and UserCode='" + usercode + "'";
            }
            if (calltype.Trim() != "")
            {
                sql += " and CallType='" + calltype + "'";
            }
            if (starttime.Trim() == "" && endtime.Trim() == "")
            {
                //sql += " and DATEDIFF(week, BeginTime,getdate())=1 ";//默认显示上周记录
            }
            else
            {
                if (starttime.Trim() != "")
                {
                    starttime = starttime+" 00:00:00";
                    sql += " and BeginTime>='" + starttime + "' ";
                }
                if (endtime.Trim() != "")
                {
                    endtime= endtime + " 23:59:59";
                    sql += " and BeginTime<='" + endtime + "'";
                }
            }
            if (startl.Trim() != "")
            {
                sql += " and TalkLongTime>=" + startl + " ";
            }
            if (endl.Trim() != "")
            {
                sql += " and TalkLongTime<=" + endl + " ";
            }

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Call_CallRecords a   inner join T_Call_OutTaskTelNum b on  a.callid= b.callid and a.CallNumber=b.F_Phone  ",
                "CallRecordsId",
                "*,[dbo].GetUserName(UserCode) usernamenew",
                sql,
                "ORDER BY CallRecordsId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            //dt.Columns.Add("lc");
            //dt.Columns.Add("dc");
          //  List<Model.T_Call_CallRecordsLD> ldList = new BLL.T_Call_CallRecordsLD().GetModelList("");
            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
          //  var users = new BLL.T_Sys_UserAccount().GetModelList("");
            foreach (DataRow dr in dt.Rows)
            {
                //int lc = ldList.Where(l => l.F_CallRecordsID == int.Parse(dr["CallRecordsId"].ToString()) && l.F_OptID == int.Parse(optid) && l.F_IsListen == true).Count();
                //int dc = ldList.Where(l => l.F_CallRecordsID == int.Parse(dr["CallRecordsId"].ToString()) && l.F_OptID == int.Parse(optid) && l.F_IsDownload == true).Count();
                //dr["lc"] = lc;
                //dr["dc"] = dc;

                string path = dr["FilePath"] != null ? dr["FilePath"].ToString() : "";
                if (path != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                {
                    var ym = config.F_ParamValue;
                    if (ym.Substring(ym.Length - 1) == "/")
                    {
                        ym = ym.Substring(0, ym.Length - 1);
                    }
                    dr["FilePath"] = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                }
            }
        var obj = new
            {
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }

        //获取已质检列表
        public ActionResult GetYZJList()
        {
            string sql = " 1=1 and CallNumber in (select F_Phone from T_Call_OutTaskTelNum) ";
            DataTable dt = new DataTable();

            string phone = HttpUtility.UrlDecode(RequestString.GetQueryString("phone"));
            string usercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string startl = HttpUtility.UrlDecode(RequestString.GetQueryString("startl"));
            string endl = HttpUtility.UrlDecode(RequestString.GetQueryString("endl"));
            string optid = HttpUtility.UrlDecode(RequestString.GetQueryString("optid"));

            string deptid = HttpUtility.UrlDecode(RequestString.GetQueryString("deptid"));

            int did = 0;

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            //已接通，已质检
            sql += "  and CallState='1' and F_QCState=1 ";

            if (phone.Trim() != "")
            {
                sql += " and CallNumber like '%" + phone + "%'";//模糊搜索
            }
            if (usercode.Trim() != "")
            {
                sql += " and UserCode='" + usercode + "'";
            }
            if (calltype.Trim() != "")
            {
                sql += " and CallType='" + calltype + "'";
            }
            if (starttime.Trim() != "")
            {
                starttime = starttime + " 00:00:00";
                sql += " and BeginTime>='" + starttime + "'";
            }
            if (endtime.Trim() != "")
            {
                endtime = endtime + " 23:59:59";
                sql += " and BeginTime<='" + endtime + "'";
            }
            if (startl.Trim() != "")
            {
                sql += " and TalkLongTime>=" + startl + " ";
            }
            if (endl.Trim() != "")
            {
                sql += " and TalkLongTime<=" + endl + " ";
            }

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            if (deptid.Trim() != "")
            {
                did = Convert.ToInt32(deptid);
                sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount   where F_DeptId = '" + did + "')";
            }

            sql += " order by   F_QCTime desc";
            List<Model.T_Call_CallRecords_QC> Plist = new BLL.T_Call_CallRecords_QC().GetModelList(sql);//.GetListV1(sql);
            List<Model.T_Call_CallRecordsLD> ldList = new BLL.T_Call_CallRecordsLD().GetModelList(""); //所有的质检记录

            List<Model.T_Sys_UserAccount> userlist = new BLL.T_Sys_UserAccount().GetModelList(""); //所有的user
            string sqluser = "select b.F_DeptName,a.F_usercode from T_Sys_UserAccount  a  left join T_Sys_Department b on a.F_DeptId = b.F_DeptId";
            DataTable dtuser = DbHelperSQL.Query(sqluser).Tables[0];

             var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var users = new BLL.T_Sys_UserAccount().GetModelList("");

            Model.PageData<object> pageData = new Model.PageData<object>();
            var list = Plist.Select(d => {
                int lc = ldList.Where(l => l.F_CallRecordsID == d.CallRecordsId && l.F_OptID == int.Parse(optid) && l.F_IsListen == true).Count();
                int dc = ldList.Where(l => l.F_CallRecordsID == d.CallRecordsId && l.F_OptID == int.Parse(optid) && l.F_IsDownload == true).Count();
              //  string name = ldList.Where(l => l.F_CallRecordsID == d.CallRecordsId).FirstOrDefault()?.F_OptBy.ToString() ?? "";
                DataRow dr = dtuser.Select(" F_usercode='" + d.UserCode + "'").FirstOrDefault(); 
                
               string path =d.FilePath != null ? d.FilePath.ToString() : "";
                if (path != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                {
                    var ym = config.F_ParamValue;
                    if (ym.Substring(ym.Length - 1) == "/")
                    {
                        ym = ym.Substring(0, ym.Length - 1);
                    }
                    d.FilePath = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                }



                return new
                {
                    _saleOffice= dr!=null?dr["F_DeptName"].ToString():"",
                    _callnumber = d.CallNumber,
                    _filepath = d.FilePath,
                    _f_qcstate = d.F_QCState,
                    _f_qcscore = d.F_QCScore,
                    _f_qcquestion = d.F_QCQuestion,
                    _f_qcadvise = d.F_QCAdvise,
                    _calltype = d.CallType,
                    _callstate = d.CallState,
                    _usercode = d.UserCode,
                    _username = d.UserName,
                    _talkstarttime = d.TalkStartTime,
                    _talkendtime = d.TalkEndTime,
                    _talklongtime = d.TalkLongTime,
                    _businesstype = d.BusinessType,
                    _f_qclc = lc,
                    _f_qcdc = dc,
                    _zjName = d.F_QCUserName,
                    _callrecordsid = d.CallRecordsId,
                    _qctime=d.F_QCTime
                };
            }).ToList<object>();

            var obj = new
            {
                rows = list.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList(),
                total = list.Count
            };

            return Content(obj.ToJson());

        }

        [AllowAnonymous]
        //获取不要评分的已质检列表 
        public ActionResult GetYZJListNew()
        {
            string sql = " and CallNumber in (select F_Phone from T_Call_OutTaskTelNum) ";
            DataTable dt = new DataTable();

            string phone = HttpUtility.UrlDecode(RequestString.GetQueryString("phone"));
            string usercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string startl = HttpUtility.UrlDecode(RequestString.GetQueryString("startl"));
            string endl = HttpUtility.UrlDecode(RequestString.GetQueryString("endl"));
            string optid = HttpUtility.UrlDecode(RequestString.GetQueryString("optid"));

            string deptid = HttpUtility.UrlDecode(RequestString.GetQueryString("deptid"));

            string qcstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("qcstarttime"));

            string qcendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("qcendtime"));

            int did = 0;

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            //已接通，已质检
            sql += "  and CallState='1' and F_QCState=1 ";

            if (phone.Trim() != "")
            {
                sql += " and CallNumber like '%" + phone + "%'";//模糊搜索
            }
            if (usercode.Trim() != "")
            {
                sql += " and UserCode='" + usercode + "'";
            }
            if (calltype.Trim() != "")
            {
                sql += " and CallType='" + calltype + "'";
            }
            if (starttime.Trim() != "")
            {
                starttime = starttime + " 00:00:00";
                sql += " and BeginTime>='" + starttime + "'";
            }
            if (endtime.Trim() != "")
            {
                endtime = endtime + " 23:59:59";
                sql += " and BeginTime<='" + endtime + "'";
            }

            if (qcstarttime.Trim() != "")
            {
                qcstarttime = qcstarttime + " 00:00:00";
                sql += " and F_QCTime>='" + qcstarttime + "'";
            }
            if (qcendtime.Trim() != "")
            {
                qcendtime = qcendtime + " 23:59:59";
                sql += " and F_QCTime<='" + qcendtime + "'";
            }


            if (startl.Trim() != "")
            {
                sql += " and TalkLongTime>=" + startl + " ";
            }
            if (endl.Trim() != "")
            {
                sql += " and TalkLongTime<=" + endl + " ";
            }

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            if (deptid.Trim() != "")
            {
                did = Convert.ToInt32(deptid);
                sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount   where F_DeptId = '" + did + "')";
            }

           
            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();

           

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Call_CallRecords  left join T_qcresult on T_Call_CallRecords.CallRecordsId=T_qcresult.F_CallRecordsId",
                "CallRecordsId",
                " CallRecordsId,F_QCTime,CallNumber, dbo.GetDeptNameByUserCode(UserCode) saleOffice,F_QCUserName, (case when F_QCState=0 then '未质检' when F_QCState=1 then '已质检' else '' end ) F_QC,( case when CallType=0 then '呼入' when CallType=1 then '呼出' else '' end) F_CallType,(case when CallState=0 then '未接通' when CallState=1 then '已接通' else '' end) F_CallState,UserCode,UserName, TalkStartTime,TalkEndTime, TalkLongTime,FilePath,(case when F_QCExistProblem=0 then '否' when F_QCExistProblem=1 then '是'  else '' end) QCExistProblem,F_ExistProblem,F_FocusUserProblem",
                sql,
                "ORDER BY F_QCTime desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

   

            foreach (DataRow dr in dt.Rows)
            {
               

                string path = dr["FilePath"] != null ? dr["FilePath"].ToString() : "";
                if (path != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                {
                    var ym = config.F_ParamValue;
                    if (ym.Substring(ym.Length - 1) == "/")
                    {
                        ym = ym.Substring(0, ym.Length - 1);
                    }
                    dr["FilePath"] = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                }
            }
            var obj = new
            {
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }


        //获取已质检列表
        public ActionResult ExportYZJList()
        {
            string sql = " 1=1 and CallNumber in (select F_Phone from T_Call_OutTaskTelNum) ";
            DataTable dt = new DataTable();

            string phone = HttpUtility.UrlDecode(RequestString.GetQueryString("phone"));
            string usercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string startl = HttpUtility.UrlDecode(RequestString.GetQueryString("startl"));
            string endl = HttpUtility.UrlDecode(RequestString.GetQueryString("endl"));
            string optid = HttpUtility.UrlDecode(RequestString.GetQueryString("optid"));

            string deptid = HttpUtility.UrlDecode(RequestString.GetQueryString("deptid"));

            string qcstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("qcstarttime"));

            string qcendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("qcendtime"));



            int did = 0;

          

            //已接通，已质检
            sql += "  and CallState='1' and F_QCState=1 ";

            if (!string.IsNullOrEmpty( phone))
            {
                sql += " and CallNumber like '%" + phone + "%'";//模糊搜索
            }
            if (!string.IsNullOrEmpty(usercode))
             
            {
                sql += " and UserCode='" + usercode + "'";
            }
            if (!string.IsNullOrEmpty(calltype))

            {
                sql += " and CallType='" + calltype + "'";
            }
            if (!string.IsNullOrEmpty(starttime))
                
            {
                starttime = starttime + " 00:00:00";
                sql += " and BeginTime>='" + starttime + "'";
            }
            if (!string.IsNullOrEmpty(endtime))
 
            {
                endtime = endtime + " 23:59:59";
                sql += " and BeginTime<='" + endtime + "'";
            }
            if (!string.IsNullOrEmpty(startl))
 
            {
                sql += " and TalkLongTime>=" + startl + " ";
            }
            if (!string.IsNullOrEmpty(endl))
            {
                sql += " and TalkLongTime<=" + endl + " ";
            }
            if (!string.IsNullOrEmpty(deptid))
            {
                did = Convert.ToInt32(deptid);
                sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount   where F_DeptId = '" + did + "')";
            }

            if (qcstarttime.Trim() != "")
            {
                qcstarttime = qcstarttime + " 00:00:00";
                sql += " and F_QCTime>='" + qcstarttime + "'";
            }
            if (qcendtime.Trim() != "")
            {
                qcendtime = qcendtime + " 23:59:59";
                sql += " and F_QCTime<='" + qcendtime + "'";
            }



            dt = DbHelperSQL.Query(" select CallNumber, dbo.GetDeptNameByUserCode(UserCode),F_QCUserName, (case when F_QCState=0 then '未质检' when F_QCState=1 then '已质检' else '' end ) F_QC,F_QCTime, ( case when CallType=0 then '呼入' when CallType=1 then '呼出' else '' end) F_CallType,(case when CallState=0 then '未接通' when CallState=1 then '已接通' else '' end) F_CallState,UserCode,UserName, TalkStartTime,TalkEndTime, TalkLongTime,(case when F_QCExistProblem=0 then '否' when F_QCExistProblem=1 then '是'  else '' end) QCExistProblem,F_ExistProblem,F_FocusUserProblem FROM T_Call_CallRecords left join T_qcresult on T_Call_CallRecords.CallRecordsId=T_qcresult.F_CallRecordsId where " + sql + " order by F_QCTime desc").Tables[0];







            //List<Model.T_Call_CallRecords_QC> Plist = new BLL.T_Call_CallRecords_QC().GetModelList(sql);//.GetListV1(sql);
            //List<Model.T_Call_CallRecordsLD> ldList = new BLL.T_Call_CallRecordsLD().GetModelList(""); //所有的质检记录

            //List<Model.T_Sys_UserAccount> userlist = new BLL.T_Sys_UserAccount().GetModelList(""); //所有的user
            //string sqluser = "select b.F_DeptName,a.F_usercode from T_Sys_UserAccount  a  left join T_Sys_Department b on a.F_DeptId = b.F_DeptId";
            ////DataTable dtuser = DbHelperSQL.Query(sqluser).Tables[0];
            //Model.PageData<object> pageData = new Model.PageData<object>();
            //var list = Plist.Select(d => {
            //    int lc = ldList.Where(l => l.F_CallRecordsID == d.CallRecordsId && l.F_OptID == int.Parse(optid) && l.F_IsListen == true).Count();
            //    int dc = ldList.Where(l => l.F_CallRecordsID == d.CallRecordsId && l.F_OptID == int.Parse(optid) && l.F_IsDownload == true).Count();
            //    //  string name = ldList.Where(l => l.F_CallRecordsID == d.CallRecordsId).FirstOrDefault()?.F_OptBy.ToString() ?? "";
            //    DataRow dr = dtuser.Select(" F_usercode='" + d.UserCode + "'").FirstOrDefault();

            //    return new
            //    {
                   
            //        _saleOffice = dr != null ? dr["F_DeptName"].ToString() : "",
            //        _callnumber = d.CallNumber,
            //        _filepath = d.FilePath,
            //        _f_qcstate = d.F_QCState,
            //        _f_qcscore = d.F_QCScore,
            //        _f_qcquestion = d.F_QCQuestion,
            //        _f_qcadvise = d.F_QCAdvise,
            //        _calltype = d.CallType,
            //        _callstate = d.CallState,
            //        _usercode = d.UserCode,
            //        _username = d.UserName,
            //        _talkstarttime = d.TalkStartTime,
            //        _talkendtime = d.TalkEndTime,
            //        _talklongtime = d.TalkLongTime,
            //        _businesstype = d.BusinessType,
            //        _f_qclc = lc,
            //        _f_qcdc = dc,
            //        _zjName = d.F_QCUserName,
            //        _callrecordsid = d.CallRecordsId
            //    };
            //}).ToList<object>();


            NPOIHelper npoi = new NPOIHelper();
            if (npoi.ExportToExcel("质检结果", dt, col3()) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }


            //var obj = new
            //{
            //    rows = list .ToList(),
            //    total = list.Count
            //};

            //return Content(obj.ToJson());

        }
        private string[] col3()
        {
            string[] ccc3 = {
                //用户分类、营业部、电话号码、【移网质量、渠道服务、光网质量、装维服务、套餐资费】（五大类所对应的分值）、分配坐席、呼叫结果、调查时间
                 "电话号码",  "营业部","质检人","是否质检","质检时间", "呼叫方向","呼叫状态","坐席工号","坐席姓名","通话开始时间","通话结束时间","通话时长（S）","质检中是否存在问题","存在的问题","需关注用户问题"
            };
            return ccc3;
        }





        //获取质检详情
        public ActionResult GetIndexList(string id)
        {
            DataTable dt = new DataTable();
            DataTable dtindex = new DataTable();
            DataTable dtres =new DataTable();

            dt = new BLL.T_QC_IndexCategory().GetList(" F_DeleteFlag=0 order by F_Sort ,F_CategoryId").Tables[0];
            dtindex = new BLL.T_QC_IndexBase().GetList(" F_DeleteFlag=0 order by F_Sort ,F_CategoryId").Tables[0];
            dtres = new BLL.T_QC_IndexRes().GetList(" CallRecordsId=" + id + " ").Tables[0];
            int i = 0;
            int m = 0;
            int indexcount = 0;
            double allscore = 0;
            double childscore = 0;
            double childpf = 0;
            double allpf = 0;
            List<Model.QCModel> qclist = new List<Model.QCModel>();
            object obj = null;

            foreach (DataRow dr in dt.Select("F_ParentId=0"))
            {
                Model.QCModel qcml = new Model.QCModel();
                List<Model.QCModel> qcclist = new List<Model.QCModel>();

                i = 0;
                indexcount = 0;
                childscore = 0;
                childpf = 0;

                string categoryid = dr["F_CategoryId"].ToString().Trim();

                qcml.Qcid = categoryid;
                qcml.Qcname = dr["F_CategoryName"].ToString().Trim();

                obj = DbHelperSQL.GetSingle("select count(*) from T_QC_IndexBase where F_CategoryId in(select F_CategoryId from T_QC_IndexCategory where F_ParentId=" + dr["F_CategoryId"] + ")");
                qcml.Rowspan = obj.ToString();
                foreach (DataRow childdr in dt.Select("F_ParentId=" + categoryid + ""))
                {
                    Model.QCModel qcmlc = new Model.QCModel();
                    List<Model.QCModel> qccrlist = new List<Model.QCModel>();
                    m = 0;
                    #region 子分类
                    string childcategoryid = childdr["F_CategoryId"].ToString().Trim();
                    DataRow[] arrchild = dtindex.Select("F_CategoryId=" + childcategoryid + "");
                    indexcount += arrchild.Length;

                    //加载项
                    qcmlc.Qcid = categoryid + "-" + childcategoryid;
                    qcmlc.Qcname = childdr["F_CategoryName"].ToString().Trim();
                    obj = DbHelperSQL.GetSingle("select count(*) from T_QC_IndexBase where F_CategoryId=" + childdr["F_CategoryId"]);
                    qcmlc.Rowspan = obj.ToString();
                    #endregion
                    foreach (DataRow indexdr in arrchild)
                    {
                        Model.QCModel qcmlcr = new Model.QCModel();
                        string indexid = indexdr["F_IndexId"].ToString().Trim();
                        string pf = "0";
                        ////分类分数合计
                        //childscore += Convert.ToInt32(indexdr["F_Score"].ToString().Trim());
                        ////总计合计
                        //allscore += Convert.ToInt32(indexdr["F_Score"].ToString().Trim());
                       
                        try
                        {
                            pf = dtres.Select("F_IndexId=" + indexid + "")[0]["F_QCScore"].ToString().Trim();
                            childpf += Convert.ToDouble(pf);//分类评分合计
                            allpf += Convert.ToDouble(pf);//评分总计
                        }
                        catch
                        {
                        }

                        #region 指标
                        //加载指标
                        qcmlcr.Qcid = categoryid + "-" + childcategoryid + "-" + indexid;
                        qcmlcr.Qcname = indexdr["F_Title"].ToString().Trim();
                        qcmlcr.Qcscore = indexdr["F_Score"].ToString().Trim();
                        qcmlcr.Qcpf = pf;
                        qcmlcr.Rowspan = "0";
                        qcmlcr.Colspan = "0";

                        childscore += Convert.ToDouble(string.IsNullOrEmpty(qcmlcr.Qcscore)?"0": qcmlcr.Qcscore);
                        allscore += Convert.ToDouble(string.IsNullOrEmpty(qcmlcr.Qcscore) ? "0" : qcmlcr.Qcscore);
                        #endregion
                        m++;

                        qccrlist.Add(qcmlcr);

                    }
                    i++;
                    qcmlc.Qclist = qccrlist;
                    qcclist.Add(qcmlc);
                }
                //合计
                qcml.Qcscore = childscore.ToString().Trim();
                qcml.Qcpf = childpf.ToString().Trim();
                qcml.Qclist = qcclist;
                qcml.Colspan = "2";
                qclist.Add(qcml);
            }
            Model.QCModel qcmlhj = new Model.QCModel();
            qcmlhj.Qcid = "0";
            qcmlhj.Qcname = "总计";
            qcmlhj.Qcscore = allscore.ToString().Trim();
            qcmlhj.Qcpf = allpf.ToString().Trim();
            qcmlhj.Qclist = qclist;
            qcmlhj.Colspan = "3";

            return Success("质检部分加载成功", qcmlhj);

        }

        public ActionResult GetQcResult(string id)
        {
          var list=  qcbll.GetModelList(" F_CallRecordsId='"+id+"'");
            if (list != null && list.Count > 0)
            {
                return Success("获取数据成功", list);
            }
            else {
                return Success("");
            }
        }
        //保存质检得分
        public ActionResult SaveData(string id, string xmlinfo)
        {
            DataTable dt = new DataTable();

            //string id = HttpUtility.UrlDecode(RequestString.GetQueryString("id"));
            ////string userid = HttpUtility.UrlDecode(RequestString.GetQueryString("userid"));
            //string username = HttpUtility.UrlDecode(RequestString.GetQueryString("username"));
            //string xmlinfo = HttpUtility.UrlDecode(RequestString.GetQueryString("xmlinfo"));
            //string question = HttpUtility.UrlDecode(RequestString.GetQueryString("question"));
            //string advise = HttpUtility.UrlDecode(RequestString.GetQueryString("advise"));

            dt = new BLL.T_QC_IndexRes().GetList(" CallRecordsId=" + id + " ").Tables[0];
            double allscore = 0;
            foreach (string scoreinfo in xmlinfo.Trim(';').Split(';'))
            {
                //判断存在该指标评估则修改，无则添加
                //string indexid = scoreinfo.Split(':')[0];
                string idsss = scoreinfo.Split(':')[0];
                string indexid = idsss.Split('-')[2];
                if (dt.Select(" F_IndexId=" + indexid + " ").Length > 0)
                {
                    Model.T_QC_IndexRes model = new Model.T_QC_IndexRes();
                    model.F_Id = Convert.ToInt32(dt.Select(" F_IndexId=" + indexid + " ")[0]["F_Id"].ToString());
                    model.CallRecordsId = Convert.ToInt32(id);
                    try
                    {
                        model.F_IndexId = Convert.ToInt32(indexid);
                    }
                    catch
                    { }
                    try
                    {
                        model.F_QCScore = Convert.ToDouble(scoreinfo.Split(':')[1]);
                        allscore += Convert.ToDouble(scoreinfo.Split(':')[1]);
                    }
                    catch
                    { }
                    new BLL.T_QC_IndexRes().Update(model);
                }
                else
                {
                    Model.T_QC_IndexRes model = new Model.T_QC_IndexRes();
                    model.CallRecordsId = Convert.ToInt32(id);
                    try
                    {
                        model.F_IndexId = Convert.ToInt32(indexid);
                    }
                    catch
                    { }
                    try
                    {
                        model.F_QCScore = Convert.ToDouble(scoreinfo.Split(':')[1]);
                        allscore += Convert.ToDouble(scoreinfo.Split(':')[1]);
                    }
                    catch
                    { }
                    new BLL.T_QC_IndexRes().Add(model);
                }
            }

            Model.T_Call_CallRecords_QC callmodel = new Model.T_Call_CallRecords_QC();
            callmodel.CallRecordsId = Convert.ToInt32(id);
            callmodel.F_QCState = 1;
            callmodel.F_QCScore = Convert.ToDecimal( allscore);
            callmodel.F_QCUserId = CurrentUser.UserData.F_UserId;
            callmodel.F_QCUserName = CurrentUser.UserData.F_UserName;
            callmodel.F_QCTime = DateTime.Now;
            callmodel.F_QCIsSelect = 0;
            callmodel.F_QCRemark = "";
            //callmodel.F_QCQuestion = question;
            //callmodel.F_QCAdvise = advise;
            if (new BLL.T_Call_CallRecords_QC().UpdateQC(callmodel))
            {
                return Success("保存成功");
            }
            else
            {
                return Error("保存质检评分信息失败");
            }

        }


        public ActionResult SaveProblemData(string existproblem,int qcexistproblem, string focusproblem,int id = 0)
        {
            if (id<=0)
            {
                return Error("失败");
            }


            Model.T_QCResult qc = new Model.T_QCResult();
            qc.F_CallRecordsId = id;
            qc.F_QCExistProblem = qcexistproblem;
            qc.F_ExistProblem = existproblem;
            qc.F_FocusUserProblem = focusproblem;
           int r= qcbll.Add(qc);
            if (r>0)
            {
                Model.T_Call_CallRecords_QC callmodel = new Model.T_Call_CallRecords_QC();
                callmodel.CallRecordsId = id;
                callmodel.F_QCState = 1;
                
                callmodel.F_QCUserId = CurrentUser.UserData.F_UserId;
                callmodel.F_QCUserName = CurrentUser.UserData.F_UserName;
                callmodel.F_QCTime = DateTime.Now;
                callmodel.F_QCIsSelect = 0;
                callmodel.F_QCRemark = "";
                 
                if (new BLL.T_Call_CallRecords_QC().UpdateQC(callmodel))
                {
                    return Success("保存成功");
                }
                else
                {
                    return Error("保存失败");
                }


               
            }
            else
            {
                return Success("保存数据失败");
            }
           
        }

        //添加日志
        public ActionResult AddLogs()
        {

            string id = HttpUtility.UrlDecode(RequestString.GetQueryString("id"));
            //string optid = HttpUtility.UrlDecode(RequestString.GetQueryString("optid"));
            //string optby = HttpUtility.UrlDecode(RequestString.GetQueryString("optby"));
            string type = HttpUtility.UrlDecode(RequestString.GetQueryString("type"));

            bool r = addldlog(int.Parse(id), CurrentUser.UserData.F_UserId, CurrentUser.UserData.F_UserName, int.Parse(type));
            if (r)
            {
                return Success("添加日志成功");
            }
            else
            {
                return Error("添加日志失败");
            }

        }
        private bool addldlog(int id, int optid, string optby, int type)
        {
            bool res = false;
            try
            {
                Model.T_Call_CallRecordsLD ldmodel = new Model.T_Call_CallRecordsLD();
                ldmodel.F_CallRecordsID = id;
                if (type == 0)
                    ldmodel.F_IsListen = true;
                else if (type == 1)
                    ldmodel.F_IsDownload = true;
                ldmodel.F_OptID = optid;
                ldmodel.F_OptBy = optby;
                ldmodel.F_OptDate = DateTime.Now;
                return new BLL.T_Call_CallRecordsLD().Add(ldmodel) > 1;
            }
            catch (Exception ex)
            {
            }
            return res;
        }

    }
}