using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    //自动外呼的最新的controller
    public class AutomaticCallController : BaseController
    {
        BLL.T_AutomaticCall_Task taskbll = new BLL.T_AutomaticCall_Task();

        BLL.T_AutomaticCall_Phone phonebll = new BLL.T_AutomaticCall_Phone();

        public ActionResult GetTaskList(string key, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and  taskName like '%" + key + "%'   ");
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_AutomaticCall_Task",
                    "taskId",
                    "*",
                    " and isDelete=0 " + sb.ToString(),
                    "ORDER BY taskId desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        public ActionResult CreateOrUpdateTask(string question1,string question2,string question3, string name = "",int id = 0 )
        {
            var model = new Model.T_AutomaticCall_Task();
            if (string.IsNullOrWhiteSpace(name))
                return Error("请填写名称" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            if (id <= 0)
            {
                model.taskName = name;
                model.createBy = CurrentUser.UserData.F_UserCode;
                if (!string.IsNullOrEmpty(question1))
                {
                    model.question1 = question1;
                    string path1 = TtsHelper.GetAudioPath(question1, name + "-1");
                    model.path1 = path1.Replace('\\', '/');
                }

                if (!string.IsNullOrEmpty(question2))
                {
                    model.question2 = question2;
                    string path2 = TtsHelper.GetAudioPath(question2, name + "-2");
                    model.path2 = path2.Replace('\\', '/');
                }

                if (!string.IsNullOrEmpty(question3))
                {
                    model.question3 = question3;
                    string path3 = TtsHelper.GetAudioPath(question3, name + "-3");
                    model.path3 = path3.Replace('\\', '/');
                }
           


                int taskid = taskbll.Add(model);
                if (taskid > 0)
                {
                    return Success("添加成功" + ",操作人：" + CurrentUser.UserData.F_UserCode);
                }
                return Error("添加失败" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            }

            model = taskbll.GetModel(id);
            model.taskName = name;
            if (taskbll.Update(model))
                return Success("修改成功" + ",操作人：" + CurrentUser.UserData.F_UserCode);
            return Error("修改失败" + ",操作人：" + CurrentUser.UserData.F_UserCode);
        }


        // 导入号码读取填入数据库
        public ActionResult TelInput(int taskid)
        {
            DataTable dtres = new DataTable();
            string errres = "";
            int i = 0;
            int count = 0;//导入成功的条数
            string Excelsource = "";
            int rcount = 0;
            int ccount = 0;
            System.Text.StringBuilder strBuilder = null;

            Excelsource = uploadexcel();

            try
            {
                //************************将文件中的数据导入数据库*************************//
                DataSet dt = ReadEcxel(Excelsource, 0);
                try
                {
                    if (dt != null && dt.Tables[0].Rows.Count != 0)
                    {
                        rcount = dt.Tables[0].Rows.Count;
                        ccount = dt.Tables[0].Columns.Count;
                        strBuilder = new System.Text.StringBuilder();//用于如果导入失败，删除已经导入过的

                        DataTable dtInputData = dt.Tables[0];//要导入的电话号码
                        List<string> sqlList = new List<string>();
                        List<string> lstsql = new List<string>();
                        int ilns = dt.Tables[0].Columns.Count;
                        DataSet dsnew = new DataSet();
                        using (SqlConnection coon = new SqlConnection(DbHelperSQL.connectionString))
                        {
                            try
                            {
                                coon.Open();
                                int colscount = dtInputData.Columns.Count;//列数
                                int rowscount = dtInputData.Rows.Count;//行数
                       
                                Model.T_AutomaticCall_Phone modelPhoneImport = new Model.T_AutomaticCall_Phone();

                              


                                if (rowscount > 0)
                                {
                                    count = dtInputData.Rows.Count;



                                    // 添加一个名为 "taskId" 的列，类型为 int
                                    dtInputData.Columns.Add("callState", typeof(int));
                                    dtInputData.Columns.Add("taskId", typeof(int));
                                    dtInputData.Columns.Add("createBy", typeof(string));
                                    dtInputData.Columns.Add("createTime", typeof(DateTime));

                                    // 为每一行添加 taskId 值为 3
                                    foreach (DataRow row in dtInputData.Rows)
                                    {
                                        row["callState"] = 0;
                                        row["taskId"] = taskid;
                                        row["createBy"] = CurrentUser.UserData.F_UserCode;
                                        row["createTime"]  = DateTime.Now;
                                    }


                                    dtInputData.Columns["目标分类0"].ColumnName = "orderNature";
                                    dtInputData.Columns["营业部1"].ColumnName = "salesOffice";
                                    dtInputData.Columns["号码2"].ColumnName = "phone";
                                    dtInputData.Columns["宽带账号3"].ColumnName = "broadbandAccount";
                                    dtInputData.Columns["地址4"].ColumnName = "address";
                                    dtInputData.Columns["入网时间5"].ColumnName = "accessTime";
                                    dtInputData.Columns["入网渠道6"].ColumnName = "channel";
                                    dtInputData.Columns["营服7"].ColumnName = "service";
                                    dtInputData.Columns["套餐8"].ColumnName = "package";
                                    dtInputData.Columns["是否融合9"].ColumnName = "fusion";
                                    dtInputData.Columns["状态10"].ColumnName = "phoneState";
                                 

                                    DbHelperSQL.SqlBulkCopyByDatatable("T_AutomaticCall_Phone", dtInputData);
                                    ////foreach (DataRow dr in dtInputData.Rows)
                                    //{
                                    //    sqlList.Clear();
                                    //    lstsql.Clear();
                                    //    if (dr[2].ToString() != "")
                                    //    {
                                         
                                    //        #region 导入表内容
                                    //        //目标分类、营业部、电话号码、宽带账号、地址、入网时间、入网渠道、营服、套餐、是否融合、状态
                                    //        modelPhoneImport.orderNature = dr[0].ToString();//目标分类


                                    //        modelPhoneImport.salesOffice = dr[1].ToString();//营业部
                                    //        modelPhoneImport.phone = dr[2].ToString();//电话号码
                                    //        modelPhoneImport.broadbandAccount = dr[3].ToString();//宽带账号
                                    //        modelPhoneImport.address = dr[4].ToString();//地址

                                    //        if (!string.IsNullOrEmpty(dr[5].ToString()))
                                    //        {
                                    //            modelPhoneImport.accessTime = dr[5].ToString();//入网时间
                                    //        }

                                    //        modelPhoneImport.channel = dr[6].ToString();//入网渠道
                                    //        modelPhoneImport.service = dr[7].ToString();//营服

                                    //        modelPhoneImport.package = dr[8].ToString();//taocan
                                    //        modelPhoneImport.fusion = dr[9].ToString();//是否融合
                                    //        modelPhoneImport.phoneState = dr[10].ToString();//状态
                                    //        modelPhoneImport.createTime = DateTime.Now;

                                    //        //自动外呼导入号码 去掉加前缀 因为小猛说现在导入的号码都是本地的，去掉判断 提高导入速度；外地加0 本地不加
                                    //        // string fix = getfix(dr[2].ToString());
                                    //        modelPhoneImport.fix = "";
                                    //        #endregion

                                    //        //#region 查重 一个月内未接通的可以再导入  
                                    //        //string strwhere = " taskId='" + taskid + "' and phone='" + modelPhoneImport.phone + "' and isconnect=1 and   DATEDIFF(day, calltime, GETDATE()) <= 30;";
                                    //        //DataSet ds = phonebll.GetList(strwhere);
                                    //        //if (ds != null && ds.Tables.Count > 0)
                                    //        //{
                                    //        //    if (ds.Tables[0].Rows.Count > 0)
                                    //        //    {
                                    //        //        rcount = rcount - 1;
                                    //        //        continue;
                                                  
                                    //        //    }
                                    //        //}
                                    //        //#endregion

                                    //        int rmw = phonebll.Add(modelPhoneImport);
                                    //        if (rmw > 0)
                                    //        {
                                    //            count += 1;//导入成功，+1
                                    //        }
                                    //    }

                                    //}
                                    dtres = dtInputData;

                                }
                                else
                                {
                                    errres += "该文档的内容为空";
                                }
                            }
                            catch (Exception ex)
                            {

                                LogFactory.GetLogger("TelInput").Error("导入失败", ex);
                                if (coon.State == ConnectionState.Open)
                                {
                                    coon.Close();
                                }
                                i++;
                                errres += i.ToString() + ".导入出现异常，共导入" + count + "条数据，请从第" + (count + 2).ToString() + "行开始导入;\n";
                                //if (strBuilder.Length > 0)
                                //{
                                //    errres += "重复的号码为：" + strBuilder.ToString() + "\n";
                                //}
                            }
                            finally
                            {
                                if (coon.State == ConnectionState.Open)
                                {
                                    coon.Close();
                                }
                            }


                        }//****************using*********



                    }
                    else
                    {
                        i++;
                        errres += i.ToString() + ".Excel中无数据;\n";
                    }

                }
                catch
                {
                    i++;
                    errres += i.ToString() + ".导入出现异常，导入失败;\n";
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }

            }
            catch
            {
                errres += i.ToString() + ".Excel格式不正确，系统错误，导入失败;\n";
            }


            if (errres != "")
            {
                return Error("导入失败！错误信息：" + errres);
            }
            else
            {
                string info = "成功导入" + rcount.ToString() + "行数据";
                return Success("导入成功！" + info);
            }
        }

        private string uploadexcel()
        {
            string Excelsource = "";
            try
            {

                HttpPostedFile _upfile = RequestString.GetFile("upFile");
                if (_upfile != null)
                {
                    string imgPath = "";

                    string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
                    newFileName = newFileName + "_" + _upfile.FileName;
                    if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\TelExcelData")))
                    {
                        Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\TelExcelData"));
                    }

                    imgPath = this.Request.ApplicationPath + "/TelExcelData/" + newFileName.ToString();
                    string PhysicalPath = Server.MapPath(imgPath);
                    _upfile.SaveAs(PhysicalPath);

                    Excelsource = Server.MapPath(this.Request.ApplicationPath + "\\TelExcelData\\") + newFileName.ToString();


                    Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    model_T_Sys_Accessories.F_FileName = _upfile.FileName;//附件名称
                    model_T_Sys_Accessories.F_FileType = _upfile.FileName.Substring(_upfile.FileName.LastIndexOf('.') + 1); //附件类型
                    model_T_Sys_Accessories.F_FileUrl = Excelsource;//附件地址

                    model_T_Sys_Accessories.F_UserCode = CurrentUser.UserData.F_UserCode;//上传人  
                    int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);

                }
            }
            catch (Exception ex) { }
            return Excelsource;
        }


        private DataSet ReadEcxel(string FileName, int Rows)
        {
            return ToDataTable(FileName);
        }
        /// <summary>
        /// 读取Excel文件到DataSet中
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        private DataSet ToDataTable(string filePath)
        {
            DataSet ds = new DataSet();
            DataTable dt = null;

            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                NPOI.SS.UserModel.IWorkbook book = null;
                if (filePath.IndexOf(".xlsx") > 0) // 2007版本
                    book = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
                else if (filePath.IndexOf(".xls") > 0) // 2003版本
                    book = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);


                NPOI.SS.UserModel.ISheet sheet = book.GetSheetAt(0);


                NPOI.SS.UserModel.IRow row = sheet.GetRow(0);


                int firstCellNum = row.FirstCellNum;
                int lastCellNum = row.LastCellNum;


                dt = new DataTable(sheet.SheetName);

                for (int i = firstCellNum; i < lastCellNum; i++)
                {
                    if (row.GetCell(i) != null)
                    {
                        dt.Columns.Add(row.GetCell(i).ToString() + i.ToString(), typeof(string));
                    }
                    else
                    {
                        dt.Columns.Add(i.ToString(), typeof(string));
                    }
                }

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    if (sheet.GetRow(i).GetCell(1) != null && sheet.GetRow(i).GetCell(1).ToString() != "")
                    {
                        DataRow newRow = dt.Rows.Add();
                        for (int j = firstCellNum; j < lastCellNum; j++)
                        {
                            if (sheet.GetRow(i).GetCell(j) != null)
                            {
                                ICell cell = sheet.GetRow(i).GetCell(j);

                                newRow[j] = cell.ToString();


                            }
                            else
                            {
                                newRow[j] = "";
                            }
                        }
                    }
                }

                ds.Tables.Add(dt);
            }
            catch (Exception ex)
            {

            }
            return ds;
        }

        public string getfix(string phone)
        {
            string fix = "";
            string zipcode = Configs.GetValue("zipcode");
            if (phone.Trim().Length == 11 && phone[0] == '1')
            {//号码为11位，首位是1，为手机号
                BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModelList("F_MobileNum='" + phone.Substring(0, 7) + "'").FirstOrDefault();
                if (mobileModel != null)
                {
                    if (!mobileModel.F_ZipCode.Equals(zipcode))
                    {
                        fix = "0";
                    }

                }
            }
            return fix;
        }

        //删除号码
        public ActionResult DeleteTels(string[] ids)
        {
            //BLL.T_AutoCall_PhoneRelate bll = new BLL.T_AutoCall_PhoneRelate();
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                  
                }
                LogFactory.GetLogger("DeleteTels").Warn("删除telid：" + idd + ",删除时间：" + DateTime.Now + ",删除人：" + CurrentUser.UserData.F_UserCode);
                if (phonebll.DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("请选择要删除的记录");
            }
           // return Error("删除号码失败,操作人：" + CurrentUser.UserData.F_UserCode);
        }

        //获取所有的任务
        public ActionResult GetExportTaskList()
        {
            var alllist = taskbll.GetModelList("1=1 order by taskId desc");
            return Success("获取任务列表下拉成功", alllist);
        }


        //通过任务id读取电话号码
   
        public ActionResult GetPhoneListByTaskId(string taskid, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(" and  callState = 0   ");
            if (!string.IsNullOrWhiteSpace(taskid))
            {
                sb.Append(" and  taskId = '" + taskid + "'   ");
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_AutomaticCall_Phone",
                    "F_Id",
                    "*",
                    sb.ToString(),
                    "ORDER BY F_Id ",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        private string[] col()
        {
            string[] ccc = {

                    "营业部","用户分类","电话号码","问题1","结果1","问题2","结果2","问题3","结果3","是否接通","呼叫时间" ,"通话时长"
            };
            return ccc;
        }

        public ActionResult GetListExpt(string phone,string orderNature,string sdate, string edate, string salesOffice,int? callstate,  int isexport = 0, int pageindex = 1, int pagesize = 10, int taskid = 0)
        {
            string sql = " and callState=1 "; 
            DataTable dt = new DataTable();
        

            if (phone != null && phone.Trim() != "")
            {
                sql += " and phone='" + phone + "'";
            }

            if (taskid != 0)
            {
                sql += " and  taskId='" + taskid + "'";

            }

            if (salesOffice != null && salesOffice.Trim() != "")
            {
                sql += " and salesOffice='" + salesOffice + "'";
            }

            if (orderNature != null && orderNature.Trim() != "")
            {
                sql += " and orderNature='" + orderNature + "'";
            }
            if (callstate!=null )
            {
                sql += " and  isconnect='" + callstate + "'";

            }


            if (!string.IsNullOrWhiteSpace(sdate))
                sql += " and DATEDIFF(day,calltime,'" + sdate.Trim() + "')<=0";
            if (!string.IsNullOrWhiteSpace(edate))
                sql += " and DATEDIFF(day,calltime,'" + edate.Trim() + "')>=0";
            if (isexport == 1)
            {
                string sql1 = " 1=1 " + sql;
                dt= phonebll.exportList(sql1).Tables[0];
                 dt.Columns.Remove("taskid");
                dt.Columns.Remove("isconnect");
                
                     dt.Columns.Remove("callState");

                NPOIHelper npoi = new NPOIHelper();
                if (npoi.ExportToExcel2003("问题结果数据", dt, col()) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            else
            {
                //   "营业部","电话号码","用户分类","问题","结果","日期"
                StringBuilder tablenew = new StringBuilder();
                tablenew.Append("(select callState , phone, salesOffice, orderNature,question1,F_Id,answerTime, ");
                tablenew.Append("result1,question2,result2,question3,result3, ");

                //tablenew.Append(" (case when isconnect = 1   then     case result1 when  '10' then '10'  when '9' then '9' when '8' then '8'    else '未评价' end else '' end ) result1,question2, ");
                //tablenew.Append(" ( case when isconnect = 1  then    case result2 when  '10' then '10'    when '9' then '9'   when '8' then '8'   else '未评价'     end     else '' end )result2,question3,");
                //  tablenew.Append(" case when isconnect = 1 then    case result3 when  1 then '十分满意'     when 2 then '满意'    when 3 then '不满意'   else '未评价'     end     else ''  end result3");
                // tablenew.Append(" (case when question3 IS NULL  then ''   else  case  result3 when  1 then '十分满意'     when 2 then '满意'    when 3 then '不满意'   else '未评价'     end    end    else ''   end  ) result3 ");

                //tablenew.Append("(case when question3 IS NULL  then ''  else    case when isconnect = 1 then    case  result3 when  '10' then '10'     when '9' then '9'    when '8' then '8'   else '未评价'   end  else ''  end end  ) result3  ,");
                tablenew.Append("  (case when isconnect =1 then '是' else '否' end ) connect, isconnect,calltime , phone.taskid ,Isnull(phone.totalTime,0) totalTime  from T_AutomaticCall_Phone  phone  left join T_AutomaticCall_Task  task on phone.taskid = task.taskid) as t");
                var recordCount = 0;
                dt = BLL.PagerBLL.GetListPager(
                   tablenew.ToString(),
                   "F_Id",
                   "*",
                   sql,
                   "order by calltime desc",
                   pagesize,
                   pageindex,
                   true,
                   out recordCount);
          
                dt.Columns.Add("FilePath", typeof(string));//语音文件路径
                 
                string path= ConfigurationManager.AppSettings["path"].ToString();
                string s = ConfigurationManager.AppSettings["starttime"].ToString();
                DateTime dtold = Convert.ToDateTime(s);
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["answerTime"] != null && !string.IsNullOrEmpty(dr["answerTime"].ToString()))
                    {
                        DateTime t2 = Convert.ToDateTime(dr["answerTime"].ToString());

                        if (DateTime.Compare(t2, dtold) > 0)
                        {


                            dr["FilePath"] = path + dr["F_Id"].ToString() + ".wav";


                        }
                    }

                   
                }

                var obj = new
                {
                    rows = dt,
                    total = recordCount
                };




                return Content(obj.ToJson());
            }

        }



        public ActionResult DeleteNoCall(int taskid=0)
        {
            if (taskid == 0)
            {
                return Error("taskid不能等于0");
            }

            string sql = "delete from   T_AutomaticCall_Phone where callState = 0 and taskId='" + taskid + "'";
           
           int n=  DbHelperSQL.ExecuteSql(sql);
            LogFactory.GetLogger("DeleteNoCall").Warn("自动外呼，taskid="+taskid+",删除没有呼叫的电话,操作人：" + CurrentUser.UserData.F_UserCode);
            return Success("删除没有呼叫的电话");
        }

      
        public ActionResult  ExportNoCall(int taskid = 0)
        {
            if (taskid == 0)
            {
                return Error("taskid不能等于0");
            }


            string sql = "select orderNature,salesOffice, phone, broadbandAccount,address,accessTime,channel,service,package,fusion,phoneState from   T_AutomaticCall_Phone where callState = 0 and taskId='" + taskid + "'";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];

            NPOIHelper npoi = new NPOIHelper();
            if (NPOIHelper.ExportToExcel2007("没有呼叫的号码", dt, nocallcol()) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
 
            LogFactory.GetLogger("exportNoCall").Warn("自动外呼，taskid=" + taskid + ",导出没有呼叫的电话,操作人：" + CurrentUser.UserData.F_UserCode);
            return Success("删除没有呼叫的电话");
        }

        private string[] nocallcol()
        {
            string[] ccc = {                

                    "目标分类","营业部","号码","宽带账号","地址","入网时间","入网渠道","营服","套餐","是否融合","状态" 
            };
            return ccc;
        }

    }
}