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
    {
        //获取未质检列表
        public ActionResult GetList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            string sql = " 1=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;

            sql += " and CallState='1' and F_QCState<>1  ";

            if (phone.Trim() != "")
            {
                sql += " and CallNumber='" + 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() != "")
                {
                    sql += " and BeginTime>='" + starttime + "'";
                }
                if (endtime.Trim() != "")
                {
                    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);
            }

            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("");
            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();
                return new
                {
                    _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,
                    _callrecordsid = d.CallRecordsId
                };
            }).ToList<object>();
            //pageData.Rows = list.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
            //pageData.Total = list.Count;

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

            res = Content(obj.ToJson());

            //if (pageData.Total > 0)
            //{
            //    res = Success("未质检列表加载成功", pageData);
            //}
            //else
            //{
            //    res = Error("未质检列表暂无数据");
            //}

            return res;
        }

        //获取已质检列表
        public ActionResult GetYZJList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            string sql = " 1=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;

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

            if (phone.Trim() != "")
            {
                sql += " and CallNumber='" + phone + "'";
            }
            if (usercode.Trim() != "")
            {
                sql += " and UserCode='" + usercode + "'";
            }
            if (calltype.Trim() != "")
            {
                sql += " and CallType='" + calltype + "'";
            }
            if (starttime.Trim() != "")
            {
                sql += " and BeginTime>='" + starttime + "'";
            }
            if (endtime.Trim() != "")
            {
                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);
            }

            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("");
            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();
                return new
                {
                    _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,
                    _callrecordsid = d.CallRecordsId
                };
            }).ToList<object>();

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

            res = Content(obj.ToJson());

            //pageData.Rows = list.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
            //pageData.Total = list.Count;

            //if (pageData.Total > 0)
            //{
            //    res = Success("已质检列表加载成功", pageData);
            //}
            //else
            //{
            //    res = Error("已质检列表暂无数据");
            //}

            return res;
        }

        //获取质检详情
        public ActionResult GetIndexList(string id)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            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;
            int allscore = 0;
            int childscore = 0;
            int childpf = 0;
            int 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";
                        try
                        {
                            //分类分数合计
                            childscore += Convert.ToInt32(indexdr["F_Score"].ToString().Trim());
                            //总计合计
                            allscore += Convert.ToInt32(indexdr["F_Score"].ToString().Trim());
                        }
                        catch
                        { }
                        try
                        {
                            pf = dtres.Select("F_IndexId=" + indexid + "")[0]["F_QCScore"].ToString().Trim();
                            childpf += Convert.ToInt32(pf);//分类评分合计
                            allpf += Convert.ToInt32(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";
                        #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";

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


            dtres.Clear();
            dtres.Dispose();
            dtindex.Clear();
            dtindex.Dispose();
            dt.Clear();
            dt.Dispose();

            return res;
        }


        //保存质检得分
        public ActionResult SaveData(string id, string xmlinfo)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            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];
            int allscore = 0;
            foreach (string scoreinfo in xmlinfo.Trim(';').Split(';'))
            {
                //判断存在该指标评估则修改，无则添加
                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.ToInt32(scoreinfo.Split(':')[1]);
                        allscore += Convert.ToInt32(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.ToInt32(scoreinfo.Split(':')[1]);
                        allscore += Convert.ToInt32(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 = 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))
            {
                res = Success("保存成功");
            }
            else
            {
                res = Error("保存质检评分信息失败");
            }

            dt.Clear();
            dt.Dispose();

            return res;
        }

        //添加日志
        public ActionResult AddLogs()
        {
            ActionResult res = NoToken("未知错误，请重新登录");

            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)
            {
                res = Success("添加日志成功");
            }
            else
            {
                res = Error("添加日志失败");
            }

            return res;
        }
        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;
                res = new BLL.T_Call_CallRecordsLD().Add(ldmodel) > 1;
            }
            catch (Exception ex)
            {
            }
            return res;
        }

    }
}