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

namespace CallCenterApi.Interface.Controllers
{
    public class IVRWordsController : BaseController
    {
        BLL.T_Sys_IVRWords dBLL = new BLL.T_Sys_IVRWords();
        //获取IVR欢迎词列表
        public ActionResult GetList()
        {
            string sql = " and F_IsDel = 0 ";
            upstate();//更新过期的为失效状态
            DataTable dt = new DataTable();

            string key = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strbtime = HttpUtility.UrlDecode(RequestString.GetQueryString("btime"));
            string stretime = HttpUtility.UrlDecode(RequestString.GetQueryString("etime"));

            string strybtime = HttpUtility.UrlDecode(RequestString.GetQueryString("bytime"));
            string stryetime = HttpUtility.UrlDecode(RequestString.GetQueryString("eytime"));
            string state = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));

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

            if (key.Trim() != "" && key != "undefined")
            {
                sql += " and (F_Title like '%" + key.Trim() + "%' or F_Content like '%" + key.Trim() + "%' )";
            }
            if (strbtime.Trim() != "" && strbtime != "undefined")
            {
                sql += " and F_CreateTime >= '" + Convert.ToDateTime(strbtime.Trim()).ToString("yyyy-MM-dd 00:00:00") + "' ";
            }
            if (stretime.Trim() != "" && stretime != "undefined")
            {
                sql += " and F_CreateTime <= '" + Convert.ToDateTime(stretime.Trim()).ToString("yyyy-MM-dd 23:59:59") + "' ";
            }
            if (state.Trim() != "" && state != "undefined")
            {
                //0未启动，1生效中，2已失效
                sql += " and F_IsState=" + state;
            }
            #region 有效期添加
            var sqlwb = "";
            var sqlwe = "";
            if (strybtime.Trim() != "" && strybtime != "undefined")
            {
                sqlwb = "  ('" + strybtime.Trim() + "' between F_StartDate and F_EndDate) ";
            }
            if (stryetime.Trim() != "" && stryetime != "undefined")
            {
                sqlwe = "  ('" + stryetime.Trim() + "' between F_StartDate and F_EndDate) ";
            }

            if (sqlwb != "" && sqlwe != "")
            {
                sql += " and (" + sqlwb + " or " + sqlwe + ")";
            }
            else
            {
                if (sqlwb != "")
                {
                    sql += " and (" + sqlwb + ")";
                }
                else if (sqlwe != "")
                {
                    sql += " and (" + sqlwe + ")";
                }
            }
            #endregion

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
           "T_Sys_IVRWords",
           "F_ID",
           "*",
           sql,
           "ORDER BY F_ID desc",
           pagesize,
           pageindex,
           true,
           out recordCount);

            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='IVRWavPath' ").FirstOrDefault();
            foreach (DataRow dr in dt.Rows)
            {
                string path = dr["F_WavNewName"] != null ? dr["F_WavNewName"].ToString() : "";
                if (path != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                {
                    dr["F_WavPath"] = config.F_ParamValue + dr["F_WavNewName"].ToString();
                }
            }

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

            return Content(obj.ToJson());

        }

        //获取IVR欢迎词
        public ActionResult GetIVRWords(string id)
        {
            if (id != null && id.Trim() != "")
            {

                Model.T_Sys_IVRWords dModel = dBLL.GetModel(int.Parse(id.Trim()));
                var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='IVRWavPath' ").FirstOrDefault();

                if (dModel.F_WavNewName != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                {
                    dModel.F_WavPath = config.F_ParamValue + dModel.F_WavNewName;
                }

                if (dModel != null)
                {
                    return Success("获取IVR欢迎词成功", dModel);
                }
                else
                {
                    return Error("获取IVR欢迎词失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        //添加IVR欢迎词
        public ActionResult AddIVRWords(string id, string title, string content,
            string isstate, string sdate, string edate, string remark, int type,
            string oldname, string newname, string path)
        {
            bool res = false;
            int iss = returnisadd(id, sdate, edate);
            if (iss <= 0)
            {
                Model.T_Sys_IVRWords dModel = new Model.T_Sys_IVRWords();
                if (id != null && id.Trim() != "")
                {
                    dModel = dBLL.GetModel(int.Parse(id.Trim()));
                    if (dModel == null)
                    {
                        return Error("此对象获取失败，请稍后再试！");
                    }
                }
                dModel.F_Title = title.Trim();
                dModel.F_Content = content.Trim();
                dModel.F_IsState = Utils.StrToInt(isstate, 0);
                dModel.F_StartDate = Utils.StrToDateTime(sdate, DateTime.Now);
                dModel.F_EndDate = Utils.StrToDateTime(edate, DateTime.Now);
                dModel.F_Remark = remark.Trim();
                dModel.F_Type = type;//1文本，2语音文件
                if (type == 2)
                {
                    dModel.F_WavOldName = oldname;
                    dModel.F_WavNewName = newname;
                    dModel.F_WavPath = path;
                }
                if (id != null && id.Trim() != "")
                {
                    res = dBLL.Update(dModel);
                }
                else
                {
                    dModel.F_IsDel = 0;
                    dModel.F_CreateUser = CurrentUser.UserData.F_UserCode;
                    dModel.F_CreateTime = DateTime.Now;
                    int b = dBLL.Add(dModel);
                    res = b > 0;
                }
            }
            if (res)
            {
                return Success("保存IVR欢迎词成功");
            }
            else
            {
                if (iss > 0)
                {
                    return Error("存在已启动的IVR欢迎词在此有效期间，请查看记录后另外选择有效期！");
                }
                else
                {
                    return Error("保存IVR欢迎词失败");
                }
            }
        }

        //删除IVR欢迎词
        public ActionResult DelIVRWords(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (dBLL.DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("请选择要删除的记录");
            }

        }

        //获取ivr欢迎词是否有添加权限
        private int returnisadd(string id, string sdate, string edate)
        {

            DateTime ssdate = Utils.StrToDateTime(sdate, DateTime.Now);
            DateTime eedate = Utils.StrToDateTime(edate, DateTime.Now);
            string sql = " isnull(F_IsState,0)=1 and F_IsDel = 0 ";//生效中状态
            if (id != null && id != "")
            {
                sql += " and F_ID<>" + id;
            }
            sql += " and( "
                + "('" + ssdate.ToString("yyyy-MM-dd HH:mm:ss") + "' between F_StartDate and F_EndDate) "
                + "or ('" + eedate.ToString("yyyy-MM-dd HH:mm:ss") + "' between F_StartDate and F_EndDate) "
                + ")";
            return dBLL.GetRecordCount(sql);
        }

        private void upstate()
        {
            string sql = " update T_Sys_IVRWords set F_IsState=2 ";
            sql += " where isnull(F_IsState,0)=1 and F_IsDel = 0 ";//启动状态
            sql += " and F_EndDate<getdate()";
            DbHelperSQL.ExecuteSql(sql);
        }
        #region
        //上传音频文件，并修改为系统需要的格式
        //public ActionResult UploadWav()
        //{
        //    HttpPostedFile _upFile = RequestString.GetFile("upFile");
        //    if (_upFile != null)
        //    {

        //        string datename = DateTime.Now.ToString("yyyyMMddHHMMss");
        //        string fullFileName = datename + "_" + _upFile.FileName;
        //        string ffmpegLocation = Server.MapPath("~/");

        //        #region 读取配置的上传路径-原文件和修改过格式的文件均上传至此
        //        string savedir = Configs.GetValue("saveloc");
        //        if (!System.IO.Directory.Exists(savedir))
        //        {
        //            System.IO.Directory.CreateDirectory(savedir);
        //        }
        //        #endregion

        //        #region 保存原文件到项目中
        //        string path = this.Request.ApplicationPath + "/auoupload/" + fullFileName;
        //        if (!System.IO.Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "/auoupload/")))
        //        {
        //            System.IO.Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "/auoupload/"));
        //        }
        //        string physicalpath = Server.MapPath(path);
        //        _upFile.SaveAs(physicalpath);
        //        #endregion

        //        #region 修改音频格式并保存新文件到指定目录中和项目中
        //        if (!string.IsNullOrEmpty(physicalpath))
        //        {
        //            # region 修改音频格式
        //            //通过cmd执行ffmpeg改变音频采样率
        //            Process p = new Process();
        //            p.StartInfo.FileName = "cmd.exe";
        //            p.StartInfo.UseShellExecute = false;
        //            p.StartInfo.RedirectStandardOutput = true;
        //            p.StartInfo.RedirectStandardInput = true;
        //            p.StartInfo.RedirectStandardError = true;
        //            p.StartInfo.CreateNoWindow = true;

        //            string temp_filename = physicalpath.Split('\\').Last().Split('.')[0] + "_temp";
        //            string path1 = this.Request.ApplicationPath + "/auoupload/";
        //            string physicalpath1 = Server.MapPath(path1);

        //            p.Start();
        //            p.StandardInput.WriteLine("cd " + ffmpegLocation);
        //            p.StandardInput.WriteLine(ffmpegLocation.Split('\\').First());
        //            p.StandardInput.WriteLine("ffmpeg.exe");
        //            string changefile = "ffmpeg -i " + physicalpath + " -acodec pcm_u8 -ab 64 -ar 8000 -ac 1 " + savedir + temp_filename + ".wav";
        //            string changefile1 = "ffmpeg -i " + physicalpath + " -acodec pcm_u8 -ab 64 -ar 8000 -ac 1 " + physicalpath1 + temp_filename + ".wav";
        //            p.StandardInput.WriteLine(changefile);
        //            p.StandardInput.WriteLine(changefile1);
        //            while (true)
        //            {
        //                if (System.IO.File.Exists(physicalpath1 + temp_filename + ".wav"))
        //                    break;
        //            }
        //            Thread.Sleep(3000);
        //            p.StandardInput.WriteLine("exit");
        //            ////p.WaitForExit();//等待程序执行完退出进程
        //            //p.Close();//关闭进程
        //            ////Kill 是终止没有图形化界面的进程的唯一方法。
        //            //p.Dispose();//释放资源
        //            p.Kill();
        //            #endregion
        //            #region 上传
        //            uploadFile upfile = new uploadFile();
        //            //通过读取配置文件，获取数据库
        //            string _ftp = Configs.GetValue("ftp");
        //            string _acc = Configs.GetValue("account");
        //            string _pwd = Configs.GetValue("password");

        //            upfile.ftpPath = _ftp;
        //            upfile.ftpUserID = _acc;
        //            upfile.ftpPassword = _pwd;
        //            //20180207 原文件同时保存
        //            //string uploadres = upfile.UploadLocalToFtp(physicalpath1 + temp_filename + ".wav");
        //            string uploadBeforres = upfile.UploadLocalToFtp(physicalpath);
        //            //if (uploadres == "上传成功！" && uploadBeforres == "上传成功！")
        //            if (uploadBeforres == "上传成功！")
        //            {
        //                //写入日志
        //                //string logfile = Server.MapPath("~/log.txt");
        //                //if (!System.IO.File.Exists(logfile))
        //                //{
        //                //    System.IO.File.Create(logfile);
        //                //}
        //                ////开始写入
        //                //string str = DateTime.Now.ToString() + " 文件" + fullFileName + "上传成功";
        //                //System.IO.File.AppendAllLines(logfile, new string[] { str }, Encoding.GetEncoding("gb2312"));


        //                //删除本地文件
        //                //System.IO.File.Delete(savedir + fullFileName);
        //                //System.IO.File.Delete(savedir + temp_filename + ".wav");
        //                //System.IO.File.Delete(physicalpath);
        //                var obj = new
        //                {
        //                    oldname = fullFileName,
        //                    newname = temp_filename + ".wav",
        //                    wavpath = savedir + temp_filename + ".wav"
        //                };
        //                return Success("文件上传成功", obj);
        //            }
        //            else
        //                return Error("文件上传失败，请重新上传::::::::uploadBeforres::" + uploadBeforres);
        //            #endregion
        //        }
        //        else
        //            return Error("格式修改出错，请重新上传");
        //        #endregion
        //    }
        //    return Error("参数传入失败");
        //}
        #endregion
    }
}