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

namespace RMYY_CallCenter_Api.Controllers.CallTel
{
    public class IVRWordsController : BaseController
    {
        private Bll.T_Sys_IVRWords ivrbll = new Bll.T_Sys_IVRWords();
        private Bll.T_Sys_SeatGroup groupbll = new Bll.T_Sys_SeatGroup();
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="key"></param>
        /// <param name="state"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult GetList(string key, int state = 0, string starttime = "", string endtime = "", int page = 1, int pagesize = 10)
        {
            if (User != null)
            {
                #region 查询添加
                Task.Run(()=>SetNoUser());
                DataTable data = new DataTable();
                string sql = $" and F_IsDelete=0";
                if (starttime.Trim() != "" && starttime != "undefined")
                    sql += $"and datediff(second,F_StartTime,'" + starttime + "')<=0";
                if (endtime.Trim() != "" && endtime != "undefined")
                    sql += $"and datediff(second,F_EndTime,'" + endtime + "')>=0";
                if (!string.IsNullOrEmpty(key))
                    sql += $" and F_Content like '%{key}%'";
                if (state != 0)
                    sql += $"and F_IsState={state}";
                #endregion
                int recordCount = 0;
                data = Bll.PagerBll.GetListPager
                      (
                      "T_Sys_IVRWords aa",
                      "F_Id",
                      "*,(select F_UserName from T_Sys_UserAccount where F_UserCode=aa.F_CreateBy)as F_UserName",
                      sql,
                      "ORDER BY F_Id desc",
                      pagesize,
                      page,
                      true,
                      out recordCount
                      );
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = data,
                    total = recordCount
                };
                return Content(obj.ToJson());

            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="fid"></param>
        /// <returns></returns>
        public ActionResult GetModel(int fid)
        {
            if (fid < 0)
                return Error("参数错误！");
            var model = ivrbll.GetModel(fid);
            if (model != null)
            {
                //model.F_GroupName = groupbll.GetModelList($"F_ZXZCode={model.F_GroupCode}").FirstOrDefault()?.F_ZXZName ?? "";
                model.F_CreateUser = new Bll.T_Sys_UserAccount().GetModel(model.F_CreateBy)?.F_UserName ?? "";
                return Content(model.ToJson());
            }
            else
                return Error("查询失败！");
        }

        /// <summary>
        ///添加修改
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="sdate"></param>
        /// <param name="edate"></param>
        /// <param name="remark"></param>
        /// <param name="groupcode"></param>
        /// <param name="isstate"></param>
        /// <param name="type"></param>
        /// <param name="id"></param>
        /// <param name="wavstr"></param>
        /// <returns></returns>
        public ActionResult AddOrEditIVR(string title, string content, string sdate, string edate, string remark,  int isstate = 0, int type = 0, int id = 0,string wavstr="", string groupcode="")
        {
            if (User != null)
            {
                if (string.IsNullOrEmpty(sdate))
                    return Error("生效时间不能为空！");
                if (string.IsNullOrEmpty(edate))
                    return Error("生效时间不能为空！");

                int iss = CheckTime(sdate, edate,id);
                if (iss <= 0)
                {
                    if (id > 0)
                    {
                        var ivrmodel = ivrbll.GetModel(id);
                        if (ivrmodel != null)
                        {
                            ivrmodel.F_Title = title;
                            ivrmodel.F_Content = content;
                            ivrmodel.F_StartTime = Convert.ToDateTime(sdate);
                            ivrmodel.F_EndTime = Convert.ToDateTime(edate);
                            ivrmodel.F_GroupCode = groupcode;
                            ivrmodel.F_Type = type;
                            ivrmodel.F_Remark = remark;
                            ivrmodel.F_Files = wavstr;
                            ivrmodel.F_IsState = Convert.ToInt32(isstate);

                            ivrbll.Update(ivrmodel);
                            return Success("修改成功！");
                        }
                        else
                            return Error("修改失败！");
                    }
                    else
                    {
                        Model.T_Sys_IVRWords ivrmodel = new Model.T_Sys_IVRWords();
                        ivrmodel.F_Title = title;
                        ivrmodel.F_Content = content;
                        ivrmodel.F_StartTime = Convert.ToDateTime(sdate);
                        ivrmodel.F_EndTime = Convert.ToDateTime(edate);
                        ivrmodel.F_GroupCode = groupcode;
                        ivrmodel.F_Type = type;
                        ivrmodel.F_Remark = remark;
                        ivrmodel.F_Files = wavstr;
                        ivrmodel.F_CreateBy = User.F_UserCode;
                        ivrmodel.F_CreateTime = DateTime.Now;
                        ivrmodel.F_IsDelete = false;
                        ivrmodel.F_IsState = Convert.ToInt32(isstate);
                        ivrbll.Add(ivrmodel);
                        return Success("保存成功！");
                    }
                }
                else
                    return Error("存在已启动的IVR欢迎词在此有效期间，请查看记录后另外选择有效期！");
            }
            return Error("无操作权限！");

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult Delete(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idstr = string.Join(",", ids);
                if (ivrbll.DeleteList(idstr))
                    return Success("删除成功！");
                else return Error("删除失败！");
            }
            else
            {
                return Error("请选择要删除的记录");
            }
        }

        /// <summary>
        /// //将超过有效期的设置为失效状态
        /// </summary>
        public void SetNoUser()
        {
            string strsql = $" F_IsDelete=0 and F_IsState=1 and  datediff(second,F_EndTime,'{DateTime.Now}')>=0";
            var modelist = ivrbll.GetModelList(strsql);
            if (modelist.Count > 0)
            {
                int[] idarray = modelist.Select(t => t.F_Id).ToArray();
                string ids = string.Join(",", idarray);
                string updatesql = $" update T_Sys_IVRWords set F_IsState=2 where F_Id in({ids})";
                DbHelperSQL.ExecuteSql(updatesql);
            }
        }

        /// <summary>
        /// 获取ivr欢迎词是否有添加/修改权限
        /// </summary>
        /// <param name="id"></param>
        /// <param name="sdate"></param>
        /// <param name="edate"></param>
        /// <returns></returns>
        public int CheckTime(string sdate, string edate, int id=0)
        {
            string strsql = $"F_IsDelete=0 and F_IsState=1";
            if (string.IsNullOrEmpty(sdate) && string.IsNullOrEmpty(edate))
            {
                strsql += $" and  datediff(second,F_StartTime,'{DateTime.Now}')>=0 and datediff(second,F_EndTime,'{DateTime.Now}')<=0";
            }
            else
            {
                if (!string.IsNullOrEmpty(sdate))
                {
                    strsql += $" and  datediff(second,F_StartTime,'{sdate}')>=0 and datediff(second,F_EndTime,'{sdate}')<=0";
                }
                if (!string.IsNullOrEmpty(edate))
                {
                    strsql += $" and  datediff(second,F_StartTime,'{edate}')>=0 and datediff(second,F_EndTime,'{edate}')<=0";
                }
            }
            if (id > 0)
            {
                strsql += $" and  F_ID<>{id} ";
            }

            var modelist = ivrbll.GetModelList(strsql);
            return modelist.Count;
        }



    }
}