using CallCenter.Utility;
using CallCenterApi.Interface.Controllers.Base;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.Quality
{
    [Authority]
    public class QCManageController : BaseController
    {
        // GET: QCManage

        //获取未质检列表
        public ActionResult GetNoQCList(string phone, string usercode)
        {
            string sql = " and CallState=1 and TalkLongTime>0 and F_QCState=0 ";
            DataTable dt = new DataTable();

            string callstate = HttpUtility.UrlDecode(RequestString.GetQueryString("callstate"));
            string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string actiontype = HttpUtility.UrlDecode(RequestString.GetQueryString("actiontype"));
            string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string tasktype = HttpUtility.UrlDecode(RequestString.GetQueryString("tasktype"));
            string extnumber = HttpUtility.UrlDecode(RequestString.GetQueryString("extnumber"));
            string PhoneType = HttpUtility.UrlDecode(RequestString.GetQueryString("phoneType"));
            int islike = RequestString.GetInt("islike", 1);

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

            if (usercode != null && usercode.Trim() != "")
            {
                if (usercode.IndexOf(',') > 0)
                {
                    sql += " and UserCode in(" + usercode + ")";
                }
                else
                {
                    sql += " and UserCode ='" + usercode + "'";
                }
            }
            if (PhoneType != null && PhoneType.Trim() != "")
            {
                sql += " and PhoneType='" + PhoneType + "'";
            }

            if (phone != null && phone.Trim() != "")
            {
                sql += " and CallNumber like '%" + phone + "%'";
            }

            if (calltype.Trim() != "")
            {
                if (calltype == "3")
                {
                    sql += " and CallType='1'";
                    sql += " and CallRecordsId in(select F_CallRecordId from T_Bus_VisitResult WITH(NOLOCK) where F_CallRecordId !='' and F_CallRecordId is not null )";
                }
                else
                    sql += " and CallType='" + calltype + "'";
            }
            if (tasktype.Trim() != "")
            {
                if (tasktype.Trim() == "2")
                {
                    sql += " and TaskType='" + tasktype + "'";
                }
                else if (tasktype.Trim() == "0")
                {
                    sql += " and (TaskType is null or TaskType!='2')";
                }
            }
            if (actiontype.Trim() != "")
            {
                sql += " and ActionType=" + actiontype.Trim();
            }
            if (starttime.Trim() != "")
            {
                sql += " and BeginTime>='" + starttime + "' ";
            }
            if (endtime.Trim() != "")
            {
                sql += " and BeginTime<='" + endtime + "' ";
            }
            if (extnumber.Trim() != "")
            {
                sql += " and ExtNumber like '%" + extnumber.Trim() + "%'";
            }

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

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

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Call_CallRecords WITH(NOLOCK)",
                "CallRecordsId",
                "*,dbo.GetUserName(UserCode) as UserName,dbo.GetDictionaryName(F_CallInType) as TypeName",
                sql,
                "ORDER BY CallRecordsId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

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

            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);
                    }

                    string lujing = path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                    string wlpath = ym + lujing;

                    dr["FilePath"] = wlpath;
                }
            }

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }

        //获取已质检列表
        public ActionResult GetQCList(string phone, string usercode)
        {
            string sql = " and CallState=1 and TalkLongTime>0 and F_QCState=1 ";
            DataTable dt = new DataTable();

            string callstate = HttpUtility.UrlDecode(RequestString.GetQueryString("callstate"));
            string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string actiontype = HttpUtility.UrlDecode(RequestString.GetQueryString("actiontype"));
            string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string tasktype = HttpUtility.UrlDecode(RequestString.GetQueryString("tasktype"));
            string extnumber = HttpUtility.UrlDecode(RequestString.GetQueryString("extnumber"));
            string PhoneType = HttpUtility.UrlDecode(RequestString.GetQueryString("phoneType"));
            int islike = RequestString.GetInt("islike", 1);

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

            if (usercode != null && usercode.Trim() != "")
            {
                if (usercode.IndexOf(',') > 0)
                {
                    sql += " and UserCode in(" + usercode + ")";
                }
                else
                {
                    sql += " and UserCode ='" + usercode + "'";
                }
            }
            if (PhoneType != null && PhoneType.Trim() != "")
            {
                sql += " and PhoneType='" + PhoneType + "'";
            }

            if (phone != null && phone.Trim() != "")
            {
                sql += " and CallNumber like '%" + phone + "%'";
            }
            if (calltype.Trim() != "")
            {
                if (calltype == "3")
                {
                    sql += " and CallType='1'";
                    sql += " and CallRecordsId in(select F_CallRecordId from T_Bus_VisitResult WITH(NOLOCK) where F_CallRecordId !='' and F_CallRecordId is not null )";
                }
                else
                    sql += " and CallType='" + calltype + "'";
            }
            if (tasktype.Trim() != "")
            {
                if (tasktype.Trim() == "2")
                {
                    sql += " and TaskType='" + tasktype + "'";
                }
                else if (tasktype.Trim() == "0")
                {
                    sql += " and (TaskType is null or TaskType!='2')";
                }
            }
            if (actiontype.Trim() != "")
            {
                sql += " and ActionType=" + actiontype.Trim();
            }
            if (starttime.Trim() != "")
            {
                sql += " and BeginTime>='" + starttime + "' ";
            }
            if (endtime.Trim() != "")
            {
                sql += " and BeginTime<='" + endtime + "' ";
            }
            if (extnumber.Trim() != "")
            {
                sql += " and ExtNumber like'%" + extnumber.Trim() + "%'";
            }

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

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

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Call_CallRecords WITH(NOLOCK)",
                "CallRecordsId",
                "*,dbo.GetUserName(UserCode) as UserName,dbo.GetDictionaryName(F_CallInType) as TypeName",
                sql,
                "ORDER BY F_QCTime desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

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

            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);
                    }

                    string lujing = path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                    string wlpath = ym + lujing;

                    dr["FilePath"] = wlpath;
                }
            }

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }

        //获取质检详情
        public ActionResult GetIndexList(int id)
        {
            DataTable dt = new BLL.T_QC_IndexCategory().GetList(" F_DeleteFlag=0 order by F_Sort ,F_CategoryId").Tables[0];
            DataTable dtindex = new BLL.T_QC_IndexBase().GetList(" F_DeleteFlag=0 order by F_Sort ,F_CategoryId").Tables[0];
            DataTable dtres = new BLL.T_QC_IndexRes().GetList(" CallRecordsId=" + id + " ").Tables[0];

            List<object> list = new List<object>();
            int allscore = 0;
            int allpf = 0;
            foreach (DataRow dr in dt.Select("F_ParentId=0"))
            {
                string categoryid = dr["F_CategoryId"].ToString().Trim();
                DataRow[] drcs = dtindex.Select("F_CategoryId=" + categoryid);

                var rowspan = drcs.Count();
                int csc = int.Parse(dr["F_Score"].ToString().Trim());
                allscore += csc;
                if (rowspan > 1)
                {
                    var l = new
                    {
                        Qcid = categoryid,
                        Qcname = dr["F_CategoryName"].ToString().Trim(),
                        Qcscore = csc,
                        Qcpf = 0,
                        TypeName="",
                        Rowspan = rowspan,
                        Colspan = 1
                    };
                    list.Add(l);
                }

                foreach (DataRow drc in drcs)
                {
                    string childid = drc["F_IndexId"].ToString().Trim();
                    int sc = int.Parse(drc["F_Score"].ToString().Trim());
                    var pfdr = dtres.Select("F_IndexId=" + childid);
                    int pf = pfdr.Count() > 0 ? int.Parse(pfdr[0]["F_QCScore"].ToString()) : 0;
                    allpf += pf;
                    var l1 = new
                    {
                        Qcid = childid,
                        Qcname = drc["F_Title"].ToString().Trim(),
                        Qcscore = sc,
                        Qcpf = pf,
                        TypeName = rowspan == 1 ? dr["F_CategoryName"].ToString().Trim() : "",
                        Rowspan = 1,
                        Colspan = 1
                    };
                    list.Add(l1);
                }
            }

            var lt = new
            {
                Qcid = "0",
                Qcname = "总计",
                Qcscore = allscore,
                Qcpf = allpf,
                TypeName = "",
                Rowspan = 1,
                Colspan = 2
            };
            list.Add(lt);

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

            return Success("质检加载成功", list);
        }


        //保存质检得分
        public ActionResult SaveData(int id,string json)
        {
            if (id > 0)
            {
                int allscore = 0;
                List<string> list = new List<string>();
                list.Add("delete from T_QC_IndexRes where CallRecordsId=" + id);
                foreach (var scoreinfo in json.ToObject<List<JObject>>())
                {
                    list.Add("insert into T_QC_IndexRes(CallRecordsId,F_IndexId,F_Score,F_QCScore) values(" + id + "," + scoreinfo["Id"].ToString() + "," + scoreinfo["Score"].ToString() + "," + scoreinfo["QCScore"].ToString() + ")");

                    allscore += int.Parse( scoreinfo["QCScore"].ToString());
                }
                list.Add("update T_Call_CallRecords set F_QCState=1,F_QCScore=" + allscore+ ",F_QCUserId="+ User.F_UserId+ ",F_QCUserName='"+ User.F_UserName+ "',F_QCTime=getdate() where CallRecordsId="+ id);

                if (DB.DbHelperSQL.ExecuteSqlTran(list)>0)
                {
                    return Success("保存成功");
                }
                else
                {
                    return Error("保存失败");
                }
            }
            else
            {
                return Error("保存失败");
            }
        }
    }
}