using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Filter;
using CallCenterApi.Interface.Models.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.callout
{
    public class BanCallOutController : BaseController
    {
        private readonly BLL.T_Call_BanCallOut banCallOutBLL = new BLL.T_Call_BanCallOut();
        private readonly BLL.T_Sys_BanCallOutTime banCallOutTimeBLL = new BLL.T_Sys_BanCallOutTime();
        private readonly BLL.T_Sys_BanCallOut sysBanCallOutBLL = new BLL.T_Sys_BanCallOut();
        private readonly BLL.T_Sys_UserAccount userAccountBLL = new BLL.T_Sys_UserAccount();
        #region 禁止外呼号码管理
        public ActionResult GetList(FilterBanCallOut filter)
        {
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrWhiteSpace(filter.Phone))
            {
                sb.Append($"  and  F_Phone='{filter.Phone}'");
            }
            //if (filter.Start != null && filter.End != null)
            //{
            //    sb.Append($"  and  F_Phone='{filter.Phone}'");
            //}
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                             "T_Call_BanCallOut",
                             "F_Id",
                             "*",
                             sb.ToString(),
                             "ORDER BY F_ID desc",
                             filter.PageSize,
                             filter.PageIndex,
                             true,
                             out recordCount);
            List<Model.T_Call_BanCallOut> modelList = new BLL.T_Call_BanCallOut().DataTableToList(dt);
            var userList = userAccountBLL.DataTableToList1(userAccountBLL.GetList("").Tables[0]);
            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    id = x.Id,
                    phone = x.F_Phone,
                    settime = x.F_SetTime,
                    remark = x.F_Remark,
                    username = userList.SingleOrDefault(m => m.F_UserId == x.F_UserId)?.F_UserName ?? "系统管理"
                }),
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        public ActionResult Export()
        {
            var rows = new BLL.T_Call_BanCallOut().DataTableToList(DbHelperSQL.Query("SELECT F_Id,F_Phone,F_SetTime,F_Remark,F_UserId FROM T_Call_BanCallOut").Tables[0]);
            var userList = userAccountBLL.DataTableToList1(userAccountBLL.GetList("").Tables[0]);
            List<List<string>> list = new List<List<string>>();
            foreach (var item in rows)
            {
                List<string> listItem = new List<string>();
                list.Add(new List<string>()
                    {
                          item.F_Phone.ToString(),
                          item.F_SetTime.ToString(),
                          item.F_Remark.ToString(),
                          userList.SingleOrDefault(m => m.F_UserId == item.F_UserId)?.F_UserName ?? "系统管理"
                    });
            }

            NPOIHelper npoi = new NPOIHelper();
            var res = npoi.ExportToExcel($"限制号码_{DateTime.Now.ToString("yyyyMMddHHmmss")}", list, new string[] { "号码", "添加时间", "备注", "添加人" });
            return !string.IsNullOrWhiteSpace(res) ? Error(res) : Success("导出成功");
        }

        public ActionResult Add(BanCallOutInput input)
        {
            if (string.IsNullOrWhiteSpace(input.Phone))
                return Error("号码不可为空");
            input.Phone = input.Phone.Trim();
            string phone = RequestString.ToDBC(RequestString.RemoveNotNumber(WebHelper.NoHtml(input.Phone)));
            if (phone.Length != input.Phone.Length)
                return Error("号码格式不正确");
            if (string.IsNullOrWhiteSpace(input.Remark))
                return Error("备注不可以为空");
            var model = banCallOutBLL.GetModel(input.Phone);
            if (model != null)
                return Error("该号码已被限制外呼");
            if (banCallOutBLL.Add(new Model.T_Call_BanCallOut()
            {
                F_Phone = input.Phone,
                F_Remark = input.Remark
            }) > 0)
                return Success("添加成功");
            return Error("添加失败");
        }

        public ActionResult Delete(int[] ids)
        {
            if (ids == null || ids.Length <= 0)
                return Error("请选择需要删除的项");
            var idsStr = string.Join(",", ids);
            banCallOutBLL.DeleteBatch(idsStr);
            return Success("删除成功");
        }
        #endregion

        #region 限制外呼时间管理
        public ActionResult GetModel()
        {
            var deptId = CurrentUser.UserData.F_DeptId;
            var model = sysBanCallOutBLL.GetModel(deptId);
            return Success("获取成功", new
            {
                id = model?.F_Id ?? 0,
                deptid = model?.F_DeptId ?? 0,
                starttime1 = model?.StartTime1.Value.ToString("yyyy-MM-dd HH:mm:ss ") ?? "",
                starttime2 = model?.StartTime2.Value.ToString("yyyy-MM-dd HH:mm:ss ") ?? "",
                endtime1 = model?.EndTime1.Value.ToString("yyyy-MM-dd HH:mm:ss ") ?? "",
                endtime2 = model?.EndTime2.Value.ToString("yyyy-MM-dd HH:mm:ss ") ?? "",
            });
        }

        public ActionResult CreateOrUpdate(SysBanCallOutInput input)
        {
            Model.T_Sys_BanCallOut model = sysBanCallOutBLL.GetModel(CurrentUser.UserData.F_DeptId);
            if (input.F_Id <= 0)
            {
                if (model != null)
                    return Error("已经存在该条数据");
                model.F_DeptId = CurrentUser.UserData.F_DeptId;
                model.StartTime1 = input.StartTime1;
                model.EndTime1 = input.EndTime1;
                model.StartTime2 = input.StartTime2;
                model.EndTime2 = input.EndTime2;
                if (sysBanCallOutBLL.Add(model))
                    return Success("添加成功");
                return Error("添加失败");
            }

            if (model == null)
                return Error("该条数据不存在");
            model.StartTime1 = input.StartTime1;
            model.EndTime1 = input.EndTime1;
            model.StartTime2 = input.StartTime2;
            model.EndTime2 = input.EndTime2;
            if (sysBanCallOutBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        #endregion

    }
}