using CallCenter.Utility;
using CallCenterApi.Common;
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.tel
{
    public class CallInScreenController : BaseController
    {
        /// <summary>
        /// 添加黑名单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AddBlack()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);

            string tel = HttpUtility.UrlDecode(RequestString.GetFormString("tel"));
            string callid = HttpUtility.UrlDecode(RequestString.GetFormString("callid"));
            int n = RequestString.GetInt("num", 0);
            int type = RequestString.GetInt("type", 0);
            Model.T_Call_Blacklist dModel = new BLL.T_Call_Blacklist().GetModelList(" F_TelPhone='" + tel + "' ").FirstOrDefault();

            var date = DateTime.Now;
            var enddate = date;
            switch (type)
            {
                case 1: enddate = enddate.AddDays(n); break;
                case 2: enddate = enddate.AddHours(n); break;
                case 3: enddate = enddate.AddMinutes(n); break;
                case 4: enddate = DateTime.MaxValue; break;
            }
            if (dModel == null)
            {
                dModel = new Model.T_Call_Blacklist();
                dModel.F_CallId = callid;
                dModel.F_TelPhone = tel.Trim();
                dModel.F_SetTime = date;
                dModel.F_RemoveTime = enddate;
                dModel.F_BlackType = 1;
                dModel.F_InterceptNum = 1;
                dModel.F_UserId = ua.F_UserId;
                int b = new BLL.T_Call_Blacklist().Add(dModel);
                if (b > 0)
                {
                    //return Success("黑名单添加成功", date.ToString("yyyy-MM-dd HH:mm:ss") + "--" + enddate.ToString("yyyy-MM-dd HH:mm:ss"));
                    return Success("黑名单添加成功", dModel);
                }
                else
                {
                    return Error("黑名单添加失败");
                }
            }
            else
            {

                dModel.F_RemoveTime = enddate;
                dModel.F_BlackType = 1;
                if (new BLL.T_Call_Blacklist().Update(dModel))
                {
                    //return Success("黑名单修改成功", date.ToString("yyyy-MM-dd HH:mm:ss") + "--" + enddate.ToString("yyyy-MM-dd HH:mm:ss"));
                    return Success("黑名单添加成功", dModel);
                }
                else
                {
                    return Error("黑名单修改失败");
                }
            }


        }

        /// <summary>
        /// 取消黑名单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult DelBlack()
        {

            string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            Model.T_Call_Blacklist dModel = new BLL.T_Call_Blacklist().GetModelList(" F_TelPhone='" + tel + "' ").FirstOrDefault();


            bool bl = new BLL.T_Call_Blacklist().Delete(dModel.F_BlackId);
            if (bl)
            {
                return Success("黑名单取消成功");
            }
            else
            {
                return Error("黑名单取消失败");
            }


        }

        /// <summary>
        /// 根据来电号码获取客户信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetCustomerByTel()
        {

            DataTable dt = new DataTable();
            string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            BLL.T_Cus_CustomerBase bll = new BLL.T_Cus_CustomerBase();
            dt = bll.GetList(" F_Telephone like '%" + tel + "%' or F_Mobile like '%" + tel + "%' ").Tables[0];

            return Success("客户信息加载成功", dt);

        }

        /// <summary>
        /// 根据来电号码获取最近的callid
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetCallIdByPhone()
        {

            DataTable dt = new DataTable();
            string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            Model.T_Call_CallRecords model = new BLL.T_Call_CallRecords().GetModelByTelphone(tel);

            return Success("加载成功", model);


        }

        /// <summary>
        /// 根据callid获取最近的通话记录
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetTelRecordByCallid()
        {

            DataTable dt = new DataTable();

            string callid = HttpUtility.UrlDecode(RequestString.GetQueryString("callid"));
            Model.T_Call_CallRecords model = new BLL.T_Call_CallRecords().GetModelByCallId(callid);

            return Success("通话记录加载成功", model);

        }

        /// <summary>
        /// 来电归属地查询
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetPhoneLocation()
        {

            string location = "未知";

            string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            if (tel.Trim().Length == 11 && tel.Substring(0, 1) != "0")
            {
                BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModelList(" F_MobileNum = '" + tel.Substring(0, 7) + "'").FirstOrDefault(); 

                if (mobileModel != null)
                {
                    location = mobileModel.F_CityDes + mobileModel.F_CardDes;
                }
            }
            else
            {
                BLL.T_Sys_TelTitleData numbBll = new BLL.T_Sys_TelTitleData();
                List<Model.T_Sys_TelTitleData> mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + tel.Substring(0, 4) + "'");
                if (mobileModel == null || mobileModel.Count <= 0)
                {
                    mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + tel.Substring(0, 3) + "'");
                }
                if (mobileModel.Count > 0)
                {
                    location = mobileModel[0].F_TitleName;
                }
            }

            return Success("归属地加载成功", location);


        }

        /// <summary>
        /// 历史记录列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetOldList()
        {

            string sql = "";
            DataTable dt = new DataTable();

            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strcalltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

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

            if (strcalltype.Trim() != "" && strcalltype != "undefined")
            {
                sql += " and CallType=" + strcalltype + " ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and CallNumber= '" + strtel.Trim() + "' ";
            }
            //else
            //{
            //    sql += " and 1=0 ";
            //}
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,BeginTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,BeginTime,'" + strendtime + "')>=0   ";
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Call_CallRecords",
                "CallRecordsId",
                "*",
                sql,
                "ORDER BY CallRecordsId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            dt.Columns.Add("TypeName", typeof(string));
            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('\\', '/');
                }
                if (dr["F_CallInType"] != null && dr["F_CallInType"].ToString() != "")
                {
                    int tid = Int32.Parse(dr["F_CallInType"].ToString());
                    var tn = new BLL.T_Sys_DictionaryValue().GetModel(tid);
                    if (tn != null)
                    {
                        dr["TypeName"] = tn.F_Value;
                    }
                }
            }

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

            return Content(obj.ToJson());


        }

        /// <summary>
        /// 获取最新知识库
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetZSKList()
        {

            DataTable dt = new DataTable();
            string pid = HttpUtility.UrlDecode(RequestString.GetQueryString("pid"));
            string keywords = HttpUtility.UrlDecode(RequestString.GetQueryString("keywords"));

            string sql = " F_ISPass=1 ";
            if (pid.Trim() != "")
            {
                sql += " and F_CategoryId=" + pid.Trim();
            }
            if (keywords.Trim() != "")
            {
                sql += " and (F_Content like '%" + keywords.Trim() + "%' or F_Title like '%"
                    + keywords.Trim() + "%' or F_KeyWords like '%" + keywords.Trim() + "%')";
            }

            dt = new BLL.T_RepositoryInformation().GetList(8, sql, " F_RepositoryId desc").Tables[0];

            return Success("加载成功", dt);


        }

        /// <summary>
        /// 振铃事件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UpdateZL()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
            if (ua != null)
            {
                Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
                model.CallId = RequestString.GetFormString("callid");
                model.UserId = ua.F_UserId;
                model.UserCode = ua.F_UserCode;
                model.UserName = ua.F_UserName;
                model.ExtNumber = ua.F_WorkNumber;

                model.DealType = 5;
                bool bl = new BLL.T_Call_CallRecords().UpdateCallInRingTelRecord(model);
                if (bl)
                {
                    return Success("更新振铃状态成功");
                }
                else
                {
                    return Success("更新振铃状态失败");
                }
            }
            else
            {
                return Error("无此用户信息" + userId);
            }


        }

        /// <summary>
        /// 摘机事件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UpdateZJ()
        {

            Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
            model.CallId = RequestString.GetFormString("callid");
            model.CallState = 1;
            model.DealType = 6;
            bool bl = new BLL.T_Call_CallRecords().UpdateCallInAnswerTelRecord(model);
            if (bl)
            {
                Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(model.CallId);
                string type = vmodel.OperateType.ToString();
                if (type == "7")
                {
                    new BLL.T_Call_TaskTelNum().UpdateYJ(Convert.ToInt32(vmodel.OperateObject.ToString()), 1);
                }

                return Success("更新摘机状态成功");
            }
            else
            {
                return Success("更新摘机状态失败");//临时修改
            }

        }

        /// <summary>
        /// 挂机事件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UpdateGJ()
        {
            string strid = RequestString.GetFormString("callid");
            bool bl = new BLL.T_Call_CallRecords().UpdateCallInHookTelRecord(strid);
            if (bl)
            {
                return Success("更新挂机状态成功");
            }
            else
            {
                return Success("更新挂机状态失败");
            } 
        }

        /// <summary>
        /// 录音事件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UpdateLY()
        {
            Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
            model.CallId = RequestString.GetFormString("callid");
            model.CallState = 1;
            model.DealType = 6;
            model.FilePath = RequestString.GetFormString("path");
            bool bl = new BLL.T_Call_CallRecords().UpdateCallInPathTelRecord(model);
            if (bl)
            {
                Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(model.CallId);
                string type = vmodel.OperateType.ToString();
                if (type == "7")
                {
                    new BLL.T_Call_TaskTelNum().UpdateYJ(Convert.ToInt32(vmodel.OperateObject.ToString()), 1);
                }

                return Success("更新挂机状态成功");
            }
            else
            {
                return Success("更新挂机状态失败");
            }


        }

        /// <summary>
        /// 呼入性质
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UpdateCallInType()
        {
            string callid = RequestString.GetFormString("callid");
            int tid = RequestString.GetInt("typeid", 0);
            Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
            if (vmodel != null)
            {
                vmodel.F_CallInType = tid;
                if (new BLL.T_Call_CallRecords().Update(vmodel))
                {
                    return Success("操作成功");
                }
                else
                {
                    return Success("操作失败");
                }
            }
            else
            {
                return Success("操作失败");
            }
        }

        /// <summary>
        /// 呼出性质
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UpdateCallOutType()
        {
            string callid = RequestString.GetFormString("callid");
            int tid = RequestString.GetInt("typeid", 0);
            Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
            if (vmodel != null)
            {
                vmodel.F_CallOutType = tid;
                if (new BLL.T_Call_CallRecords().Update(vmodel))
                {
                    return Success("操作成功");
                }
                else
                {
                    return Success("操作失败");
                }
            }
            else
            {
                return Success("操作失败");
            }

        }

    }
}