
using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers.CallTel
{
    public class CallrecordsController : BaseController
    {
        //获取通话记录列表
        public ActionResult GetList( string phone, string usercode, string extnumber="", string starttime="", string endtime="", int islike=1, int type=0,int actiontype=0,int calltype=-1, int callstate=-1, int page = 1, int pagesize = 10, int transfertodept=0, int isdc=0)
        {
            string sql = "";
            DataTable dt = new DataTable();

            if (type != 0)
            {
                sql += " and F_CallInType = '" + type + "' ";
            }
            if (usercode != null && usercode.Trim() != "")
            {
                sql += " and UserCode in(" + usercode + ")";
            }
            
            if (islike > 0)
            {
                if (phone != null && phone.Trim() != "")
                {
                    sql += " and CallNumber like '%" + phone + "%'";
                }
            }
            else
            {
                if (phone != null && phone.Trim() != "")
                {
                    sql += " and CallNumber = '" + phone + "'";
                }
            }
            if (callstate > -1)
            {
                if (callstate == 0)
                {
                    sql += " and CallState=0 and isnull(UserCode,'')!='' ";
                }
                else if (callstate == 3)
                {
                    sql += " and CallState=0 and CallType=0 and isnull(UserCode,'')='' ";
                }
                else
                {
                    sql += " and CallState='" + callstate + "'";
                }
            }
            if (calltype > -1)
            {
                sql += " and CallType='" + calltype + "'";
            }
            if (actiontype > 0)
            {
                sql += " and ActionType=" + actiontype;
            }
            if (starttime.Trim() != "")
            {
                sql += " and BeginTime>='"+ Convert.ToDateTime(starttime).ToString("yyyy-MM-dd hh:mm:ss") + "' ";
            }
            if (endtime.Trim() != "")
            { 
                sql += " and BeginTime<='" + Convert.ToDateTime(endtime).ToString("yyyy-MM-dd hh:mm:ss") + "' ";
            }
            if(extnumber.Trim()!="")
            {
                sql += " and isnull(ExtNumber,'')='" + extnumber.Trim() + "'";
            }

            if (transfertodept > 0)
            {
                sql += " and F_TransferToDept='" + transfertodept + "'";
            }

            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select   ROW_NUMBER()  OVER(ORDER BY CallRecordsId desc) 编号, CallNumber 电话号码,(case CallType when 0 then '呼入' else '呼出' end ) 呼叫方向,(case CallState when 0 then ( case  when CallType=0 and isnull(UserCode,'')='' then  '主动放弃' else '未接通'   end    ) else '已接通' end ) 呼叫状态,UserCode 坐席工号,dbo.GetUserName(UserCode) as 坐席姓名, "
                    + "BeginTime 开始时间,TalkStartTime 通话开始时间 ,TalkEndTime " +
                    " 通话结束时间 ,EndTime 结束时间 ,LongTime 通话时长 ,PhoneType " +
                    "电话类别,"+ "case CallState when 0 then (case IsReply when 1 then '已回复' else '未回复' end) else '' end  是否回复 ,[dbo].[GetDepName](F_TransferToDept) 转接部门 "
                   + " from T_Call_CallRecords  a WITH(NOLOCK)  where 1=1 " + sql+ "ORDER BY CallRecordsId desc").Tables[0];
                var msg = new NPOIHelper().ExportToExcel("通话记录", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            else
            {
                int recordCount = 0;
                dt = Bll.PagerBll.GetListPager(
                    "T_Call_CallRecords WITH(NOLOCK)",
                    "CallRecordsId",
                    "*,dbo.GetUserName(UserCode) as UserName, WorkOrderId,dbo.GetDictionaryName(F_CallInType) as TypeName,(case CallState when 0 then (case IsReply when 1 then '已回复' else '未回复' end) else '' end  ) Showstate ,[dbo].[GetDepName](F_TransferToDept) TransferToDeptName",
                    sql,
                    "ORDER BY CallRecordsId desc",
                    pagesize,
                    page,
                    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 GetListWJ(string phone, string starttime="", string endtime="", int ishfSuccess=-1,int ishf=-1,int page = 1, int pagesize = 10)
        {

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


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

            if (starttime.Trim() != "")
            {
                sql += " and BeginTime>= '" + starttime + "' ";
            }
            if (endtime.Trim() != "")
            {
                sql += " and BeginTime<='" + endtime + "' ";
            }
            if (ishf>-1)
            {
                sql += " and F_wjishf=" + ishf + " ";
            }
            if (ishfSuccess>-1)
            {
                sql += " and F_wjishfSuccess=" + ishfSuccess;
            }
            sql += " and CallState='0' and CallType='0'";

            int recordCount = 0;
            dt = Bll.PagerBll.GetListPager(
                        "T_Call_CallRecords WITH(NOLOCK)",
                        "CallRecordsId",
                        "*",
                        sql,
                        "ORDER BY CallRecordsId desc",
                        pagesize,
                        page,
                        true,
                        out recordCount);

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

            return Content(obj.ToJson());
        }

        //获取转移或三方通话，均为手机号
        //rep_transfer只有转移的数据
        public ActionResult GetListZY(string phone, string usercode, string starttime="", string endtime="", int callstate = -1, int page = 1, int pagesize = 10)
        {
            string sql = "";
            DataTable dt = new DataTable();

            sql += " and ActionType>1";//1正常呼入呼出、2转移、3三方通话

            if (usercode != null && usercode.Trim() != "")
            {
                sql += " and UserCode='" + usercode + "'";
            }

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

            if (starttime.Trim() != "")
            {
                sql += " and BeginTime>= '" + Convert.ToDateTime(starttime).ToString("yyyy-MM-dd")+ " 00:00:00" + "' ";
            }
            if (endtime.Trim() != "")
            {
                sql += " and BeginTime<='" + Convert.ToDateTime(endtime).ToString("yyyy-MM-dd")+ " 23:59:59" + "' ";
            }

            int recordCount = 0;

            dt = Bll.PagerBll.GetListPager(
                   "T_Call_CallRecords WITH(NOLOCK)",
                   "CallRecordsId",
                   "*",
                   sql,
                   "ORDER BY CallRecordsId desc",
                   pagesize,
                   page,
                   true,
                   out recordCount);

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

            return Content(obj.ToJson());
        }

        //删除通话记录
        public ActionResult DelCallRecord(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (new Bll.T_Call_CallRecords().DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("请选择要删除的记录");
            }

        }

        public ActionResult UpdateCallRecord(int id)
        {
            Bll.T_Call_CallRecords bll = new Bll.T_Call_CallRecords();
            Model.T_Call_CallRecords model = bll.GetModel(id);
            model.IsReply = 1;
            bll.Update(model);
            return Success("更新成功");
        }

        //转移之后 记录一下转移时间 转移给dept 转移之后是否接通
        public ActionResult UpdateCallRecordForTransfer(string callid,string usercode, string transfertophone, int transfercallstate=0, int transfertodept=0)
        {


            if (string.IsNullOrEmpty(callid))
            {
                return Error("callid不能为空");
            }


            Bll.T_Call_CallRecords bll = new Bll.T_Call_CallRecords();
           List< Model.T_Call_CallRecords> modellist = bll.GetModelList(" UserCode='"+usercode+ "' and CallId='"+callid+"' ");

            if (modellist != null && modellist.Count > 0)
            {
                Model.T_Call_CallRecords model = modellist.First();
                model.F_TransferToTime = DateTime.Now;
                model.F_TransferToPhone = transfertophone;
                model.F_TransferToDept = transfertodept;
                model.F_TransferCallState = transfercallstate;
                bll.Update(model);
                return Success("更新转移记录成功");
            }

             
                return Error("更新转移记录失败");
            
        }
        
    }
}