using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using HySoft.Common;
using System.IO;

namespace HySoft.BaseCallCenter.Web.faxmanage
{
    public partial class FaxSend : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindBase();
            }
        }

        /// <summary>
        /// 时间绑定
        /// </summary>
        private void BindBase()
        {
            txtDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
            selectHour.Items.Clear();
            for (int i = 0; i < 24; i++)
            {
                selectHour.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            selectHour.Value = DateTime.Now.Hour.ToString();
            selectMin.Items.Clear();
            for (int i = 0; i < 60; i++)
            {
                selectMin.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            selectMin.Value = DateTime.Now.Minute.ToString();
        }

        public void Button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtTelephone.Value))
            {
                SaveSendFax();
            }

        }

        #region 验证传真号码
        public string[] CheckFaxTelephone(string arrtelephone)
        {
            string[] res = new string[3];
            res[0] = "";
            res[1] = "";
            res[2] = "";
            DataTable dt = new DataTable();
            try
            {
                //全角转半角
                arrtelephone = Common.StringUtil.ToDBC(arrtelephone).Replace("?", "").Replace("-", "");
                arrtelephone += "!@#";
                arrtelephone = arrtelephone.Replace(";!@#", "").Replace("!@#", "");
                if (arrtelephone.Trim() != "")
                {
                    string[] arrtel = arrtelephone.Split(',');
                    for (int arrindex = 0; arrindex < arrtel.Length; arrindex++)
                    {
                        string tel = arrtel[arrindex];
                        if (VerificationFax(tel))
                        {
                            if (tel.Length > 6)
                            {
                                dt = new BLL.T_Cus_CustomerBase().GetList("F_Fax like '%" + tel + "%' ").Tables[0];
                                if (dt.Rows.Count > 0)
                                {
                                    res[0] += tel + ",";
                                    res[1] += dt.Rows[0]["F_CustomerID"].ToString().Replace(",", "") + ",";
                                    res[2] += dt.Rows[0]["F_CustomerName"].ToString().Replace(",", "") + ",";
                                }
                                else
                                {
                                    res[0] += tel + ",";
                                    res[1] += ",";
                                    res[2] += ",";
                                }
                                dt.Clear();
                                dt.Dispose();
                            }
                            else
                            {
                                res[0] += tel + ",";
                                res[1] += ",";
                                res[2] += ",";
                            }
                        }
                    }
                }
            }
            catch
            { }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }
            return res;
        }
        public static string RegexStringFax = "^[0-9]*$";
        public bool VerificationFax(string fax)
        {
            bool bl = false;
            bl = System.Text.RegularExpressions.Regex.IsMatch(fax, RegexStringFax, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            return bl;
        }
        #endregion

        /// <summary>
        /// 保存传真
        /// </summary>
        private void SaveSendFax()
        {
            try
            {
                string path = txtF_FilePath.Value;
                if (path.Trim() == "")
                {
                    MessageBoxToWindow("请选择传真文件", "提示！", "catch");
                }
                else
                {
                    string arrtelephone = "";
                    string arrcustomerid = "";
                    string arrcustomername = "";

                    //验证传真格式及获取客户信息
                    var res = CheckFaxTelephone(txtTelephone.Value);
                    if (res[0] != "")
                    {
                        arrtelephone = res[0];
                        arrcustomerid = res[1];
                        arrcustomername = res[2];

                        string remark = txtRemark.Value;
                        string filetype = tishi1.Value;
                        string filesize = tishi2.Value;
                        string type = "0";
                        string date = "";
                        if (rbSendType_1.Checked)
                        {
                            type = "1";
                            date = txtDate.Value + " " + selectHour.Value + ":" + selectMin.Value + ":00";
                        }
                        arrtelephone += "!@#";
                        arrtelephone = arrtelephone.Replace(",!@#", "").Replace("!@#", "");
                        arrcustomerid += "!@#";
                        arrcustomerid = arrcustomerid.Replace(",!@#", "").Replace("!@#", "");
                        arrcustomername += "!@#";
                        arrcustomername = arrcustomername.Replace(",!@#", "").Replace("!@#", "");
                        string[] arrtel = arrtelephone.Split(',');
                        string[] arrid = arrcustomerid.Split(',');
                        string[] arrname = arrcustomername.Split(',');


                        DataTable dt = new DataTable();
                        try
                        {
                            byte[] filebytes = null;
                            string filePath = null;
                            try
                            {
                                string _FaxFileName = "";
                                string _Path = "\\FaxSourceFile\\" + DateTime.Now.ToString("yyyyMM");
                                string _SavePath = AppDomain.CurrentDomain.BaseDirectory + _Path;
                                if (!Directory.Exists(_SavePath))
                                {
                                    Directory.CreateDirectory(_SavePath);
                                }
                                filetype = path.Substring(path.LastIndexOf(".") + 1);
                                string _xdPath = _Path + "\\" + Guid.NewGuid().ToString().Replace("-", "") + "." + filetype;
                                _FaxFileName = AppDomain.CurrentDomain.BaseDirectory + _xdPath;

                                //获得上传文件的大小
                                filesize = txtF_FilePath.PostedFile.ContentLength.ToString();
                                string sext = spanExt.InnerHtml.Trim();
                                sext += "!@#";
                                sext = sext.Replace(";!@#", "").Replace("!@#", "");
                                string[] temp = sext.Split(';');
                                //设置上传的文件是否是允许的格式
                                bool flag = false;
                                //判断上传的文件是否是允许的格式
                                foreach (string data in temp)
                                {
                                    if (data.ToLower() == filetype.ToLower())
                                    {
                                        flag = true;
                                        break;
                                    }
                                }
                                if (!flag)
                                {
                                    MessageBoxToWindow("传真文件格式不正确，请选择正确格式文件" + spanExt.InnerHtml.Trim().ToUpper(), "提示！", "catch");
                                }
                                else
                                {
                                    int l = Convert.ToInt32(spanSize.InnerHtml.Trim()) * 1024;
                                    if (Convert.ToInt32(filesize) < l)
                                    {
                                        txtF_FilePath.PostedFile.SaveAs(_FaxFileName);
                                        filePath = _FaxFileName;
                                        if (!string.IsNullOrEmpty(filePath))
                                        {
                                            FileInfo _file = new FileInfo(filePath);
                                            if (!_file.Exists)
                                            {
                                                MessageBoxToWindow("当前传真文件已不存在", "提示！", "catch");
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                                                    byte[] data = new byte[fs.Length];
                                                    fs.Read(data, 0, data.Length);
                                                    filebytes = data;

                                                    #region 上传传真文件
                                                    int start = path.LastIndexOf("\\") + 1;
                                                    int end = path.Length;
                                                    string filename = path.Substring(start, end - start).Replace("|", "");
                                                    //上传文件

                                                    WebReferenceFax.FaxService ws = new WebReferenceFax.FaxService();
                                                    string newfilepath = "";
                                                    string newtiffilepath = "";
                                                    string wsres = ws.UploadFile(filename, filebytes);
                                                    if (wsres != "")
                                                    {
                                                        string[] arr = wsres.Split('|');
                                                        if (arr.Length > 0)
                                                        {
                                                            if (arr[0] == "0")
                                                            {
                                                                newfilepath = arr[1];
                                                                newtiffilepath = newfilepath.Substring(0, newfilepath.LastIndexOf(".")) + ".tif";
                                                                newtiffilepath = newtiffilepath.Replace("\\LocalFile\\", "\\TifFile\\");

                                                                int MaxSendCounts = 3;
                                                                for (int arrindex = 0; arrindex < arrtel.Length; arrindex++)
                                                                {
                                                                    string tel = arrtel[arrindex];
                                                                    string customerid = arrid[arrindex];
                                                                    string customername = arrname[arrindex];
                                                                    Model.T_Fax_SendFaxTask model = new Model.T_Fax_SendFaxTask();
                                                                    model.FaxID = 0;
                                                                    model.TelNum = tel;
                                                                    model.FilePath = newfilepath;
                                                                    model.TifFilePath = newtiffilepath;
                                                                    model.CommitTime = DateTime.Now;
                                                                    model.State = 0;
                                                                    model.SendTime = DateTime.Now;
                                                                    model.Info = "立即传真";
                                                                    if (type == "1")
                                                                    {
                                                                        model.SendTime = Convert.ToDateTime(date);
                                                                        model.Info = "定时传真";
                                                                    }
                                                                    model.LastSentTime = null;
                                                                    model.CurSentCount = 0;
                                                                    model.MaxSendCount = MaxSendCounts;
                                                                    model.F_UserID = null;
                                                                    LoginUser p_LoginUser = new LoginUser(this.Context);
                                                                    if (p_LoginUser != null)
                                                                    {
                                                                        model.F_UserID = p_LoginUser.UserID;
                                                                    }
                                                                    model.F_CustomerID = null;
                                                                    if (customerid.Trim() != "")
                                                                    {
                                                                        model.F_CustomerID = Convert.ToInt32(customerid);
                                                                    }
                                                                    model.F_Name = customername;
                                                                    model.FileSize = Convert.ToInt32(filesize);
                                                                    model.FileType = filetype;
                                                                    model.FileState = 0;
                                                                    model.Remark = remark;
                                                                    model.FileName = filename;
                                                                    int r = new BLL.T_Fax_SendFaxTask().Add(model);
                                                                }
                                                                MessageBoxToWindow("新增成功", "新增提示！", "success");
                                                            }
                                                            else
                                                            {
                                                                MessageBoxToWindow("上传传真文件失败:" + arr[1], "新增提示！", "error");
                                                            }
                                                        }
                                                        else
                                                        {
                                                            MessageBoxToWindow("上传传真文件失败:返回失败", "新增提示！", "error");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        MessageBoxToWindow("上传传真文件失败:请求服务失败", "新增提示！", "error");
                                                    }
                                                    if (newfilepath == "" || newtiffilepath == "")
                                                    {
                                                        MessageBoxToWindow("上传传真文件失败:无法获取路径", "新增提示！", "error");
                                                    }
                                                    #endregion
                                                }
                                                catch
                                                {
                                                    MessageBoxToWindow("读取传真文件失败", "提示！", "error");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            MessageBoxToWindow("读取文件失败", "提示！", "error");
                                        }
                                    }
                                    else
                                    {
                                        MessageBoxToWindow("当前传真文件不能大于" + spanSize.InnerHtml.Trim() + "KB", "提示！", "catch");
                                    }
                                }
                            }
                            catch
                            {
                                //异常
                            }
                        }
                        catch
                        {
                            MessageBoxToWindow("发送传真异常:查看传真服务是否启动", "提示！", "catch");
                        }
                        finally
                        {
                            dt.Clear();
                            dt.Dispose();
                        }
                    }
                    else
                    {
                        MessageBoxToWindow("没有正确格式的传真号码", "提示！", "catch");
                    }

                }
            }
            catch (Exception ex)
            {
                Common.SysLog.WriteLog(ex);
                MessageBoxToWindow("发送传真异常", "提示！", "catch");
            }
        }

        #region 弹出对话框
        /// <summary>
        /// 弹出对话框
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        public void MessageBoxToWindow(string title, string content, string type)
        {
            string script = "";
            switch (type)
            {
                case "error"://失败
                    type = "error";
                    script = "<script type='text/javascript'>  $.ligerDialog.alert('" + title + "','" + content + "','" + type + "');</script>";
                    break;
                case "success"://成功
                    type = "info";
                    script = "<script type='text/javascript'> $.ligerDialog.alert('" + title + "','" + content + "','" + type + "');</script>";
                    break;
                case "catch"://异常
                    type = "warning";
                    script = "<script type='text/javascript'>  $.ligerDialog.alert('" + title + "','" + content + "','" + type + "');</script>";
                    break;
                default:
                    type = "question";
                    break;
            }
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", script);
        }
        #endregion
    }
}