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

namespace CallCenterApi.Interface.Controllers.tel
{
    public class CallrecordsController : BaseController
    {
        private readonly BLL.T_Sys_Department deptBLL = new BLL.T_Sys_Department();
        private readonly BLL.T_Call_CallRecords callRecordBLL = new BLL.T_Call_CallRecords();
        //获取通话记录列表
        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;

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

                var depts = deptBLL.DataTableToListForLevel(DbHelperSQL.Query($"with cte(F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,lvl) as( select F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,0 lvl from T_Sys_Department where F_DeptId={deptid} union all select dept.F_DeptId,dept.F_DeptName,dept.F_ParentId,dept.F_DeptCode,dept.F_Layer,lvl+1 from T_Sys_Department dept inner join cte on dept.F_DeptId = cte.F_ParentId) select F_DeptId,F_ParentId,F_DeptName,F_DeptCode,F_Layer,lvl from  cte ").Tables[0]);
                var deptCompany = depts.Where(x => x.Layer == 1).OrderBy(x => x.Level).FirstOrDefault();
                if (roleid != 0)
                {
                    if (roleid != 17)
                    {
                        //各分公司
                        if (deptCode.Replace("|0|1|", "").Length > 0)
                        {
                            if (roleid == 36 || roleid == 38 || roleid == 40 || roleid == 58)
                            {
                                sql += " and UserCode='" + CurrentUser.UserData.F_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 '" + (deptCompany?.DeptCode ?? 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 (!string.IsNullOrWhiteSpace(dept))
                {
                    var deptModel = deptBLL.GetModel(!string.IsNullOrWhiteSpace(dept) ? Convert.ToInt32(dept) : 0);
                    if (deptModel != null)
                    {
                        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 '{deptModel.F_DeptCode}%'))";
                    }
                }
                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",
                    "CallRecordsId",
                    "*",
                    sql,
                    "ORDER BY CallRecordsId desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
                var callRecordList = callRecordBLL.DataTableToList(dt);
                var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
                var users = new BLL.T_Sys_UserAccount().GetModelList("");
                var deptList = deptBLL.DataTableToListForLevel(DbHelperSQL.Query("select F_DeptId,F_ParentId,F_DeptName,F_DeptCode,F_Layer,0 lvl FROM T_Sys_Department ").Tables[0]);
                var resList = new List<CallRecordDto>();
                foreach (var item in callRecordList)
                {
                    string path = item.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);
                        }
                        item.FilePath = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                    }
                    string ucode = item.UserCode ?? "";
                    string uname = item.UserName ?? "";
                    Model.T_Sys_UserAccount uu = null;
                    uu = users.Where(u => u.F_UserCode.Equals(item.UserCode)).FirstOrDefault();
                    if (uu != null)
                        item.UserName = uu.F_UserName;

                    Model.T_Sys_DepartmentLevel deptCategory = new Model.T_Sys_DepartmentLevel();
                    Model.T_Sys_DepartmentLevel deptChannel = new Model.T_Sys_DepartmentLevel();
                    if (uu != null)
                    {
                        var depId = uu.F_DeptId;
                        deptChannel = deptList.SingleOrDefault(x => x.Layer == 3 && x.DeptId == depId);
                        deptCategory = deptList.SingleOrDefault(x => x.Layer == 2 && (deptChannel?.ParentId ?? 0) == x.DeptId);


                    }


                    resList.Add(new CallRecordDto
                    {
                        CallId = item.CallId,
                        CallNumber = item.CallNumber,
                        FilePath = item.FilePath,
                        CallType = item.CallType,
                        DealType = item.DealType,
                        CallState = item.CallState,
                        IsDeal = item.IsDeal,
                        UserCode = item.UserCode,
                        UserName = item.UserName,
                        BeginTime = item.BeginTime,
                        RingStartTime = item.RingStartTime,
                        TalkStartTime = item.TalkStartTime,
                        TalkEndTime = item.TalkEndTime,
                        RingLongTime = item.RingLongTime,
                        TalkLongTime = item.TalkLongTime,
                        CompanyName = deptCompany?.DeptName ?? "",
                        CategoryName = deptCategory?.DeptName ?? "",
                        ChannelName = deptChannel?.DeptName ?? "",
                    });

                }



                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = resList,
                    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 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"));


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

                var depts = deptBLL.DataTableToListForLevel(DbHelperSQL.Query($"with cte(F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,lvl) as( select F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,0 lvl from T_Sys_Department union all select dept.F_DeptId,dept.F_DeptName,dept.F_ParentId,dept.F_DeptCode,dept.F_Layer,lvl+1 from T_Sys_Department dept inner join cte on dept.F_DeptId = cte.F_ParentId) select F_DeptId,F_ParentId,F_DeptName,F_DeptCode,F_Layer,lvl from  cte ").Tables[0]);
                var deptCompany = depts.Where(x => x.Layer == 1).OrderBy(x => x.Level).FirstOrDefault();

                if (roleid != 0)
                {
                    if (roleid != 17)
                    {
                        //各分公司
                        if (deptCode.Replace("|0|1|", "").Length > 0)
                        {
                            if (roleid == 36 || roleid == 38 || roleid == 40 || roleid == 50)
                            {
                                sql += " and UserCode='" + CurrentUser.UserData.F_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 '" + (deptCompany?.DeptCode ?? deptCode) + "%')) ";
                            }
                        }
                    }
                }

                if (usercode != null && usercode.Trim() != "")
                {
                    sql += " and UserCode='" + usercode + "'";
                }
                if (dept != null && dept.Trim() != "")
                {
                    var deptModel = deptBLL.GetModel(!string.IsNullOrWhiteSpace(dept) ? Convert.ToInt32(dept) : 0);
                    if (deptModel != null)
                    {
                        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 '{deptModel.F_DeptCode}%'))";
                    }
                }
                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  BeginTime>='{starttime}' ";
                }
                if (endtime.Trim() != "")
                {
                    sql += $" and  BeginTime<='{endtime}' ";
                }

                List<Model.T_Call_CallRecordsExpt> callRecordList = callRecordBLL.DataTableToListExpt(callRecordBLL.GetListExpt(sql).Tables[0]);
                var users = new BLL.T_Sys_UserAccount().GetModelList("");
                var deptList = deptBLL.DataTableToListForLevel(DbHelperSQL.Query("select F_DeptId,F_ParentId,F_DeptName,F_DeptCode,F_Layer,0 lvl FROM T_Sys_Department ").Tables[0]);

                List<List<string>> resList = new List<List<string>>();
                foreach (var item in callRecordList)
                {
                    Model.T_Sys_UserAccount uu = null;
                    uu = users.Where(u => u.F_UserCode.Equals(item.usercode)).FirstOrDefault();
                    Model.T_Sys_DepartmentLevel deptCategory = new Model.T_Sys_DepartmentLevel();
                    Model.T_Sys_DepartmentLevel channelCategory = new Model.T_Sys_DepartmentLevel();
                    if (uu != null)
                    {
                        var depId = uu.F_DeptId;
                        channelCategory = deptList.SingleOrDefault(x => x.Layer == 3 && x.DeptId == depId);
                        deptCategory = deptList.SingleOrDefault(x => x.Layer == 2 && (channelCategory?.ParentId ?? 0) == x.DeptId);
                    }

                    resList.Add(new List<string>()
                    {
                        item.callnumber??"",
                        item.calltypes??"",
                        item.callstates??"",
                        item.usercode??"",
                        item.username??"",
                        deptCompany?.DeptName ?? "",
                        deptCategory?.DeptName ?? "",
                        channelCategory?.DeptName ?? "",
                        item.begintime?.ToString("yyyy-MM-dd HH:mm:ss")??"",
                        item.talkstarttime?.ToString("yyyy-MM-dd HH:mm:ss")??"",
                        item.talkendtime?.ToString("yyyy-MM-dd HH:mm:ss")??"",
                        item.endtime?.ToString("yyyy-MM-dd HH:mm:ss")??"",
                        item.talklongtime.ToString(),

                    });
                }
                NPOIHelper npoi = new NPOIHelper();
                if (npoi.ExportToExcel($"通话记录_{DateTime.Now.ToString("yyyyMMddHHmmss")}", resList, col()) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }

            }
            return res;
        }
        //private void todo(object aa)
        //{
        //    string sql = "";
        //    int startindex = Convert.ToInt32(aa.ToString().Split(',')[0]);
        //    int limitstep = Convert.ToInt32(aa.ToString().Split(',')[1]);
        //    for (int i = (startindex > 1 ? ((startindex - 1) * 100) : 0); i < (startindex == limitstep ? (dt.Rows.Count) : startindex * 100); i++)
        //    {

        //    }
        //    Thread.Sleep(2000);
        //}
        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");

        }
    }
}