using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.tel
{
    public class CallrecordsController : BaseController
    {
        //获取通话记录列表
        public ActionResult GetList(string phone, string usercode)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string sql = "";
                DataTable dt = new DataTable();
                int roleid = CurrentUser.UserData.F_RoleId;
                int deptid = CurrentUser.UserData.F_DeptId;
                string deptCode = CurrentUser.UserData.F_DeptCode;
                string callstate = HttpUtility.UrlDecode(RequestString.GetQueryString("callstate"));
                string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
                string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
                string dept = HttpUtility.UrlDecode(RequestString.GetQueryString("dept"));
                string username = HttpUtility.UrlDecode(RequestString.GetQueryString("username"));

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

                //17=系统管理员,36=客服,37=组长,38=组员,39=业主,40=话务员,41=客服主管,43=分公司市场部主任,45=业务稽核,46=集团客户部,
                //47 =网络部,48=市场部经理,50=业务支撑中心,51=市场部,52=客户服务中心,53=总经理,54=副总经理,55=业务负责人,56=投诉处理员,57=基础业务主管,

                if (roleid != 0)
                {
                    if (roleid != 17)
                    {
                        //各分公司
                        if (deptCode.Replace("|0|1|", "").Length > 0)
                        {
                            if (roleid == 36 || roleid == 38 || roleid == 40)
                            {
                                usercode = CurrentUser.UserData.F_UserCode;
                                sql += " and UserCode='" + usercode + "'";
                            }
                            else
                            {
                                sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount where F_DeptID in (select F_DeptId from T_Sys_Department where F_DeptCode like '" + deptCode + "%')) ";
                            }
                        }
                        //总公司
                        //else
                        //{
                        //    sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount where F_DeptId=" + deptid + ")";
                        //}
                    }
                }

                if (usercode != null && usercode.Trim() != "")
                {
                    sql += " and UserCode='" + usercode + "'";
                }
                if (!string.IsNullOrWhiteSpace(dept) && Convert.ToInt32(dept) >= 0)
                {
                    sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount where F_DeptId=" + dept.Trim() + ")";
                }
                if (phone != null && phone.Trim() != "")
                {
                    sql += " and CallNumber like '%" + phone + "%'";
                }
                if (callstate.Trim() != "")
                {
                    sql += " and CallState='" + callstate + "'";
                }
                if (calltype.Trim() != "")
                {
                    sql += " and CallType='" + calltype + "'";
                }
                if (starttime.Trim() != "")
                {
                    sql += " and datediff(day,BeginTime,'" + starttime + "')<=0 ";
                }
                if (endtime.Trim() != "")
                {
                    sql += " and datediff(day,BeginTime,'" + endtime + "')>=0 ";
                }
                if (username.Trim() != "")
                {
                    sql += " and T_Sys_UserAccount.F_UserName like '%" + username.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 left join T_Sys_UserAccount ON T_Sys_UserAccount.F_UserCode=T_Call_CallRecords.UserCode  left join T_Sys_Department ON T_Sys_UserAccount.F_DeptId=T_Sys_Department.F_DeptId ",
                    "CallRecordsId",
                    "*,T_Sys_UserAccount.F_UserName,T_Sys_Department.F_DeptName,(SELECT F_DeptName from T_Sys_Department t where t.F_DeptId=T_Sys_Department.F_ParentId) as ParentName ",
                    sql,
                    "ORDER BY CallRecordsId desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

                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)
                {
                    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('\\', '/');
                    }
                    string ucode = dr["UserCode"] != null ? dr["UserCode"].ToString() : "";
                    string uname = dr["UserName"] != null ? dr["UserName"].ToString() : "";
                    if (ucode != "")
                    {
                        if (uname == "")
                        {
                            var uu = users.Where(u => u.F_UserCode.Equals(ucode)).FirstOrDefault();
                            if (uu != null)
                                dr["UserName"] = uu.F_UserName;
                        }
                    }
                }

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

                res = Content(obj.ToJson());

            }
            return res;
        }

        //通话记录导出
        public ActionResult GetListExpt(string phone, string usercode)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string sql = " 1=1 ";
                DataTable dt = new DataTable();

                int userid = CurrentUser.UserData.F_UserId;
                int roleid = CurrentUser.UserData.F_RoleId;
                int deptid = CurrentUser.UserData.F_DeptId;
                string deptcode = CurrentUser.UserData.F_DeptCode;
                string callstate = HttpUtility.UrlDecode(RequestString.GetQueryString("callstate"));
                string calltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
                string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                string endtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
                string dept = HttpUtility.UrlDecode(RequestString.GetQueryString("dept"));

                if (roleid != 0)
                {
                    if (roleid != 17)
                    {
                        //if (deptcode.IndexOf("|533|") > 0)
                        //{
                        //    sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount where F_DeptId=" + deptid + ")";
                        //}
                        if (deptcode.IndexOf("|531|") > 0)
                        {
                            if (roleid == 32)
                            {
                                usercode = CurrentUser.UserData.F_UserCode;
                                sql += " and UserCode='" + usercode + "'";
                            }
                            else
                            {
                                sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount where F_DeptID in (select F_DeptId from T_Sys_Department where F_DeptCode like '" + deptcode + "%')) ";
                            }
                        }
                        else
                        {
                            sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount where F_DeptId=" + deptid + ")";
                        }
                    }
                }

                if (usercode != null && usercode.Trim() != "")
                {
                    sql += " and UserCode='" + usercode + "'";
                }
                if (dept != null && dept.Trim() != "")
                {
                    sql += " and UserCode in (select F_UserCode from T_Sys_UserAccount where F_DeptId=" + dept.Trim() + ")";
                }
                if (phone != null && phone.Trim() != "")
                {
                    sql += " and CallNumber like '%" + phone + "%'";
                }
                if (callstate.Trim() != "")
                {
                    sql += " and CallState='" + callstate + "'";
                }
                if (calltype.Trim() != "")
                {
                    sql += " and CallType='" + calltype + "'";
                }
                if (starttime.Trim() != "")
                {
                    sql += " and datediff(day,BeginTime,'" + starttime + "')<=0 ";
                }
                if (endtime.Trim() != "")
                {
                    sql += " and datediff(day,BeginTime,'" + endtime + "')>=0 ";
                }

                dt = new BLL.T_Call_CallRecords().GetListExpt(sql).Tables[0];

                NPOIHelper npoi = new NPOIHelper();
                if (npoi.ExportToExcel("通话记录数据", dt, col()) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }

            }
            return res;
        }

        private string[] col()
        {
            string[] ccc = {
                   "电话号码","呼叫方向","呼叫状态","是否处理","坐席工号","坐席姓名",
                  "开始时间","通话开始时间","通话结束时间","结束时间","通话时长"
            };
            return ccc;
        }

        //删除通话记录
        public ActionResult DelCallRecord(string[] ids)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                if (ids != null && ids.Length > 0)
                {
                    string idd = " ";
                    foreach (string str in ids)
                    {
                        idd += str + ",";
                    }
                    if (new BLL.T_Call_CallRecords().DeleteList(idd.TrimEnd(',')))
                    {
                        res = Success("删除成功");
                    }
                    else
                        res = Error("删除失败");
                }
                else
                {
                    res = Error("请选择要删除的记录");
                }

            }
            return res;
        }


        public ActionResult GetCallVoiceRemoveName(string callId)
        {
            var callRecord = new BLL.T_Call_CallRecords().GetModelByCallId(callId);
            if (callRecord == null)
                return Error("通话记录不存在");
            var filePath = "";
            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            string path = callRecord.FilePath ?? "";
            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);
                }
                filePath = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
            }


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filePath);
            request.Method = "GET";
            request.ContentType = "audio/wav";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            return File(myResponseStream, "audio/wav", $"{callRecord.CallNumber}-{callRecord.BeginTime?.ToString("yyyyMMdd") ?? DateTime.Now.ToString("yyyyMMdd")}-{callRecord.UserCode}.wav");

        }
    }
}