using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using CallCenterApi.Dto;
using CallCenterApi.IRepositories;
using MadRunFabric.Common;
using MadRunFabric.Model.CallCenterApi;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using WorkOrderApi.IRepositories;

namespace CallCenterApi.Controllers.telbusiness
{
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class CallRecordsController : BaseController
    {
        private readonly ILogger<CallRecordsController> _logger;
        private readonly ICall_RecordsRepository _call_recordsRepository;
        private readonly ISys_SystemConfigRepository _sys_systemconfigRepository;
        private readonly ICus_Customer_ProjectRepository _cus_customer_projectepository;
        private readonly IBus_WorkOrder_BaseRepository _bus_workorder_baserepository;
        public CallRecordsController(ILogger<CallRecordsController> logger, ICall_RecordsRepository call_recordsRepository, ISys_SystemConfigRepository sys_systemconfigRepository, ICus_Customer_ProjectRepository cus_customer_projectepository, IBus_WorkOrder_BaseRepository bus_workorder_baserepository)
        {
            _call_recordsRepository = call_recordsRepository;
            _sys_systemconfigRepository = sys_systemconfigRepository;
            _logger = logger;
            _cus_customer_projectepository = cus_customer_projectepository;
            _bus_workorder_baserepository = bus_workorder_baserepository;
        }
        [Authorize]
        [HttpGet("getall")]
        public async Task<IActionResult> GetAllListsAsync()
        {
            try
            {
                var recordlist = await _call_recordsRepository.GetAll();
                return Success("获取全部数据成功", recordlist);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取分机呼入全部数据异常");
                return Error("获取分机呼入全部数据异常");
            }
        }

        /// <summary>
        /// 获取列表 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListByPageAsync(string stime, string etime, string keyword,string usercode,string province,string city,int callstate=-1, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            //排序字段
            var sort = Builders<mw_call_records>.Sort.Descending("id");
            var list = await _call_recordsRepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _call_recordsRepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<mw_call_records>>();
            if(!string.IsNullOrWhiteSpace(stime))
            {
                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(stime + " 00:00:00"))>=0 || s.endtime.CompareTo(DateTime.Parse(stime + " 00:00:00")) >= 0));
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(etime + " 23:59:59")) <= 0 || s.endtime.CompareTo(DateTime.Parse(etime + " 23:59:59")) <= 0));
            }
            //模糊查询
            if (!string.IsNullOrWhiteSpace(keyword))
                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.callnumber.Contains(keyword)));
            if (!string.IsNullOrWhiteSpace(usercode))
                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.agent_code.Equals (usercode)));
            if (callstate > -1)
            {
                listfilter.Add(Builders<mw_call_records>.Filter.Eq("callstate", callstate));
            }

            if (!string.IsNullOrWhiteSpace(province))
            {
                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.city .Contains (province )));
            }
            if (!string.IsNullOrWhiteSpace(city ))
            {
                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.city.Contains(city)));
            }
            #endregion
            int recordCount = 0;
            if (listfilter.Count > 0)
            {
                var filter = Builders<mw_call_records>.Filter.And(listfilter);
                list = await _call_recordsRepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _call_recordsRepository.CountAsync(filter);   //获取总数
            }
            
            recordCount = int.Parse(redCount.ToString());
            //2018-7-21 获取录音文件路径
            #region 获取路径

            var dModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("PlayPath") & s.isdelete == false, null);
            string recordpath = dModel.paramvalue;

            #endregion

            var obj = new
            {
                rows = list,
                total = recordCount,
                recordpath
            };
            return Success("成功", obj);
        }

        //导出
        [Authorize]
        [HttpGet("exportexcel")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportExcelAsync(string stime, string etime, string keyword, string usercode, string province, string city, int callstate = -1)
        {
            try
            {

                #region 条件信息
                //排序字段
                var sort = Builders<mw_call_records>.Sort.Descending("id");
                var list = await _call_recordsRepository.Get(null);
                var redCount = await _call_recordsRepository.CountAsync(null); //获取总数
                                                                               //根据条件查询集合
                var listfilter = new List<FilterDefinition<mw_call_records>>();
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(stime + " 00:00:00")) >= 0 || s.endtime.CompareTo(DateTime.Parse(stime + " 00:00:00")) >= 0));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(etime + " 23:59:59")) <= 0 || s.endtime.CompareTo(DateTime.Parse(etime + " 23:59:59")) <= 0));
                }
                //模糊查询
                if (!string.IsNullOrWhiteSpace(keyword))
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.callnumber.Contains(keyword)));
                if (!string.IsNullOrWhiteSpace(usercode))
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.agent_code.Equals(usercode)));
                if (callstate > -1)
                {
                    listfilter.Add(Builders<mw_call_records>.Filter.Eq("callstate", callstate));
                }

                if (!string.IsNullOrWhiteSpace(province))
                {
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.city.Contains(province)));
                }
                if (!string.IsNullOrWhiteSpace(city))
                {
                    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.city.Contains(city)));
                }
                #endregion
                int recordCount = 0;
                if (listfilter.Count > 0)
                {
                    var filter = Builders<mw_call_records>.Filter.And(listfilter);
                    list = await _call_recordsRepository.Get(filter,null,sort );
                    
                }
                
                var dtNew = list.ToList();
                if (dtNew != null)
                {
                    var tb = ModelConvertHelper<mw_call_records>.ConvertListToDataTable(dtNew);
                    //导出dtnew 
                    NPOIHelper npoi = new NPOIHelper();
                    string[] cols = { "姓名", "电话", "来电电话", "工单类型", "业务办理", "接收部门", "接收人", "工单内容", "创建人", "创建时间", "工单编号" };
                    string[] colname = { "name", "phone", "callintel", "typename", "businesstype", "deptname", "sureuser", "content", "createuser", "createtime", "ordercode" };

                    byte[] sm = npoi.ExportToExcel1(tb, cols,colname );
                    if (sm != null)
                    {
                        return File(sm, "application/vnd.ms-excel", "通话记录.xlsx");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Error("导出失败");

                //return Success("根据条件获取数据成功", tasklist);

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出异常");
                return Error("导出失败");
            }
            //return Success("导出成功");
        }

        //2019-4-15 公司售后系统使用，添加返回客户和是否有工单
        /// <summary>
        /// 获取列表 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListAsync(string stime, string etime, string keyword)
        {
            #region 条件信息
            //排序字段
            var sort = Builders<mw_call_records>.Sort.Descending("id");
            var list = await _call_recordsRepository.Get(null,null, sort);
            var redCount = await _call_recordsRepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<mw_call_records>>();
            //if (!string.IsNullOrWhiteSpace(stime))
            //{
            //    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(stime)) >= 0 || s.endtime.CompareTo(DateTime.Parse(stime)) >= 0));
            //}
            //if (!string.IsNullOrWhiteSpace(etime))
            //{
            //    listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.begintime.CompareTo(DateTime.Parse(etime)) <= 0 || s.endtime.CompareTo(DateTime.Parse(etime)) <= 0));
            //}
            if (!string.IsNullOrWhiteSpace(stime))
            {
                DateTime dt2 = DateTime.Now.ToLocalTime();
                if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                    listfilter.Add(Builders<mw_call_records>.Filter.Gt("begintime", dt2));
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                DateTime dt2 = DateTime.Now.ToLocalTime();
                if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                    listfilter.Add(Builders<mw_call_records>.Filter.Lt("begintime", dt2));
            }

            //模糊查询
            if (!string.IsNullOrWhiteSpace(keyword))
                listfilter.Add(Builders<mw_call_records>.Filter.Where(s => s.callnumber.Contains(keyword)));
            #endregion
            int recordCount = 0;
            if (listfilter.Count > 0)
            {
                var filter = Builders<mw_call_records>.Filter.And(listfilter);
                list = await _call_recordsRepository.Get(filter, null, sort);
                redCount = await _call_recordsRepository.CountAsync(filter);   //获取总数
            }
            //var lists = _call_recordsRepository.GetLists(stime, etime, keyword);//关联查询前缀判断条件没加上
            //return Success("成功", lists);
            List<mw_call_records> tlist = list.ToList();
            var tb = ModelConvertHelper<mw_call_records>.ConvertListToDataTable(tlist);
            DataTable dtnew = tb;
            dtnew.Columns.Add("name");
            dtnew.Columns.Add("cusname");
            dtnew.Columns.Add("existorder");
            for (int i = 0; i < dtnew.Rows.Count; i++)
            {
                //根据电话查客户信息和有无工单
                string phone = dtnew.Rows[i]["callnumber"].ToString();//加过前缀的号码
                var cModel = await _cus_customer_projectepository.GetSingle(s => s.mobilephone .Equals(phone ), null);//|| s.mobilephone.Equals(phone.Substring (1,phone .Length -1))
                if (cModel != null)
                {
                    dtnew.Rows[i]["name"] = cModel.name;
                    dtnew.Rows[i]["cusname"] = cModel.customername;
                }
                else
                {
                    dtnew.Rows[i]["name"] = "";
                    dtnew.Rows[i]["cusname"] = "";
                }
                
                var bmodel = await _bus_workorder_baserepository.GetSingle(s => s.phone.Equals(phone) || s.phone.Equals(phone.Substring(1, phone.Length - 1)), null);
                if (bmodel != null)
                {
                    dtnew.Rows[i]["existorder"] = "有";
                }
                else
                {
                    dtnew.Rows[i]["existorder"] = "无";
                }
            }


            //var lists = _call_recordsRepository.GetLists(stime, etime, keyword);
            //recordCount = int.Parse(redCount.ToString());
            //2018-7-21 获取录音文件路径
            #region 获取路径

            var dModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("PlayPath") & s.isdelete == false, null);
            string recordpath = dModel.paramvalue;

            #endregion

            var obj = new
            {
                rows = dtnew ,
                //total = recordCount,
                recordpath
            };
            return Success("成功", obj);
        }
    }
}