using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ChuPiao.AutoPrint.Machine.Models;
using ChuPiao.AutoPrint.Services;
using ChuPiao.AutoPrint.Services.AutoPrint;
using ChuPiao.Common.Core.Utils;
using ChuPiao.Common.Enums;
using ChuPiao.Common.Models;
using ChuPiao.Common.Utils;

namespace ChuPiao.AutoPrint.Desktop.AutoPrint
{
    public partial class InputTicketCodeDialog : Form
    {
        public string MacNumber
        {
            get { return _macNumber; }
            set { _macNumber = value; }
        }
        public string ZxMacNumber
        {
            get { return _zxMacNumber; }
            set { _zxMacNumber = value; }
        }

        public string LogPath
        {
            get { return _logPath; }
            set { _logPath = value; }
        }

        public string TicketFilePath
        {
            get { return _ticketFilePath; }
            set { _ticketFilePath = value; }
        }

        public FileInfo CurrentFileInfo
        {
            get { return _currentFileInfo; }
            set { _currentFileInfo = value; }
        }

        private string _macNumber;
        private string _zxMacNumber;

        private string _logPath;

        private string _ticketFilePath;

        private FileInfo _currentFileInfo=null;
        private L_LotTicketEntity _currentTicketEntity;
        public InputTicketCodeDialog(AutoPrintService printService)
        {
            InitializeComponent();
            _currentTicketEntity = printService.CurrentTicket;
            _macNumber = printService.LotMachine.MachineInfo.M_Number;
            _zxMacNumber = printService.LotMachine.MachineInfo.M_ZxNumber;
            _logPath = printService.LotMachine.VirtualPrinter.LogPath;
        }

        public L_LotTicketEntity CurrentTicketEntity
        {
            get { return _currentTicketEntity; }
            set { _currentTicketEntity = value; }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string msg;
                string ticketCode = this.txtTicketCode.Text.Trim().Replace("-", "");
                string password = this.txtPassword.Text.Trim();
                string randomCode = this.txtRandomCode.Text.Trim();
                string ticketFilePath = this.txtTicketPath.Text.Trim();
                string prnText = "";
                if(File.Exists(ticketFilePath))
                {
                    prnText = File.ReadAllText(ticketFilePath);
                }
                if(string.IsNullOrEmpty(ticketCode))
                {
                    MessageService.ShowMessage("票号不得为空", "操作提示");
                    return;
                }
                Regex regex;
                if(CurrentTicketEntity.LotId==(int)Lottype.Bd)
                {
                    if(ticketCode.Replace("-","").Length!=24)
                    {
                        MessageService.ShowMessage("票号长度错误，请检查(北单票号为24位数字)", "操作提示");
                        return;
                    }
                    regex = new Regex(@"[0-9]{6}-[0-9]{6}-[0-9]{6}-[0-9]{6}");
                }
                else
                {
                    //if (ticketCode.Length != 23)
                    //{
                    //    MessageService.ShowMessage("票号长度错误，请检查(票号为23位数字)", "操作提示");
                    //    return;
                    //}
                    regex = new Regex(@"[0-9-]{20,24}");
                }
                Match match = regex.Match(ticketCode);
                if(!match.Success)
                {
                    MessageService.ShowMessage("票号格式错误，请检查", "操作提示");
                    return;
                }

                //L_LotTicketService lotTicketService=new L_LotTicketService();
                //L_LotTicketEntity entity = lotTicketService.GetTicketByTicketCode(CurrentTicketEntity.LotId, CurrentTicketEntity.L_Expect, ticketCode);
                //if(entity!=null)
                //{
                //    msg = string.Format("票号[{0}]在数据库中已经存在，请确认！",ticketCode);
                //    MessageService.ShowMessage(msg,"操作提示");
                //    return;
                //}
                //decimal maxgetmoney = 0;
                //decimal.TryParse(this.txtMaxGetMoney.Text.Trim(), out maxgetmoney);
                //L_PrintTicketEntity printTicketEntity=new L_PrintTicketEntity();
                //printTicketEntity.P_Lid = CurrentTicketEntity.L_Id;
                //printTicketEntity.P_Money = CurrentTicketEntity.L_Money;
                //printTicketEntity.P_Mutiple = CurrentTicketEntity.L_Mutiple;
                //printTicketEntity.L_CodeRate = this.txtCodeRate.Text;
                //printTicketEntity.L_CodeReference = this.txtCodeReference.Text;
                //printTicketEntity.L_MaxGetMoney = maxgetmoney;
                //printTicketEntity.P_AddTime = DateTime.Now;
                //printTicketEntity.P_Code = CurrentTicketEntity.L_Code;
                //printTicketEntity.P_Expect = CurrentTicketEntity.L_Expect;
                //printTicketEntity.P_SaleAddress = ZxMacNumber;
                //printTicketEntity.P_SingleZhuShu = CurrentTicketEntity.L_SingleZhuShu;
                //printTicketEntity.P_SucTime = DateTime.Now;
                //printTicketEntity.P_TicketCode = ticketCode;
                //printTicketEntity.P_Password = password;
                //printTicketEntity.P_RandomCode = randomCode;
                //printTicketEntity.P_PrnText = prnText;


                //CurrentTicketEntity.L_TicketCode = printTicketEntity.P_TicketCode;
                //CurrentTicketEntity.L_RandomCode = printTicketEntity.P_RandomCode;
                //CurrentTicketEntity.L_Password = printTicketEntity.P_Password;
                //CurrentTicketEntity.L_SucTime = printTicketEntity.P_SucTime;
                //CurrentTicketEntity.L_SaleAddress = printTicketEntity.P_SaleAddress;
                //CurrentTicketEntity.L_CodeRate = printTicketEntity.L_CodeRate;
                //CurrentTicketEntity.L_MaxGetMoney = printTicketEntity.L_MaxGetMoney;
                //CurrentTicketEntity.L_CodeReference = printTicketEntity.L_CodeReference;
                //CurrentTicketEntity.L_Status = (int)TicketStatus.Suc;
                //CurrentTicketEntity.L_NotifyStatus = (int)NotifyStatus.NotifyAble;

                //System.Windows.Forms.DialogResult dialogResult = MessageBox.Show(this, string.Concat("确认输入吗？", Environment.NewLine, "生产流水号：", CurrentTicketEntity.L_TicketSn, " 票号：", CurrentTicketEntity.L_TicketCode, " 密码：", CurrentTicketEntity.L_Password, " 彩种：", CurrentTicketEntity.L_LotName, " 玩法：",
                //                    CurrentTicketEntity.L_PlayName, " 投注号码：", CurrentTicketEntity.L_Code, " 金额：", CurrentTicketEntity.L_Money.ToString("0"), " 倍数：", CurrentTicketEntity.L_Mutiple), "操作提示",
                //                                                                 MessageBoxButtons.YesNo,
                //                                                                 MessageBoxIcon.Question,
                //                                                                 MessageBoxDefaultButton.Button2);
                //if(dialogResult==DialogResult.No)
                //    return;
                //lotTicketService.AddPrintTicket(CurrentTicketEntity, printTicketEntity);
                
                //msg = string.Concat("手工输入票号完成。生产流水号：", CurrentTicketEntity.L_TicketSn," 票号：",CurrentTicketEntity.L_TicketCode," 密码：",CurrentTicketEntity.L_Password," 彩种：", CurrentTicketEntity.L_LotName, " 玩法：",
                //                    CurrentTicketEntity.L_PlayName, " 投注号码：", CurrentTicketEntity.L_Code, " 金额：", CurrentTicketEntity.L_Money.ToString("0"), " 倍数：", CurrentTicketEntity.L_Mutiple);
                //MessageService.ShowMessage(msg, "操作提示");


                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("手工输入票号异常。错误信息：", exception.Message));
            }
        }


        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog=new OpenFileDialog();
                openFileDialog.Filter = "电子票文件(*.prn)|*.prn";
                //string path = @"d:\data\logs\"+MacNumber+"\";
                string path = Path.Combine(LogPath + DateTime.Now.ToString("yyyy-MM-dd"), "last");
                if (Directory.Exists(path))
                {
                    openFileDialog.InitialDirectory = path;
                }
                DialogResult dialogResult = openFileDialog.ShowDialog(this);
                if(dialogResult==DialogResult.OK)
                {
                    ShowTicketContent(openFileDialog.FileName);
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("打开文件异常。错误信息：", exception.Message));
            }
        }
        private void FindLastTicket()
        {
            try
            {
                string TicketFilePath = Path.Combine(LogPath + DateTime.Now.ToString("yyyy-MM-dd"), "last");
                if (!Directory.Exists(TicketFilePath))
                {
                    MessageService.ShowMessage(string.Concat("路径", TicketFilePath, "不存在！"));
                    return;
                }
                DirectoryInfo directoryInfo = new DirectoryInfo(TicketFilePath);
                FileInfo[] fileInfoList = directoryInfo.GetFiles("*.prn");
                LastTicketFileComparer fileComparer = new LastTicketFileComparer();
                Array.Sort(fileInfoList, fileComparer);
                if(fileInfoList.Length>0)
                {
                    CurrentFileInfo = fileInfoList[0];
                    ShowTicketContent(CurrentFileInfo.FullName);
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("查找最后一条出票记录异常。错误信息：", exception.Message));
            }
        }

        private void ShowTicketContent(string filename)
        {
            this.txtTicketPath.Text = filename;
            string content = File.ReadAllText(filename);
            byte[] arr;
            if(filename.IndexOf("alldata")<0)
            {
                arr = TicketTextUtil.DecryptAndDecompress(content);
            }
            else
            {
                arr = File.ReadAllBytes(content);
            }
            
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(arr, 0, arr.Length);
                ms.Position = 0;
                this.richTextBoxTicket.LoadFile(ms, RichTextBoxStreamType.PlainText);
            }

            try
            {
                DecodePrintData decodePrintData = new DecodePrintData();
                decodePrintData.InputData.CaptureDataBytes = arr;
                decodePrintData.InputData.CaptureDataString = Encoding.GetEncoding("gb2312").GetString(arr);
                LotMachineService.LotMachineList[MacNumber].TestDecodeTicket(CurrentTicketEntity,decodePrintData);
                if(decodePrintData.DecodeSuccess)
                {
                    CurrentTicketEntity.L_TicketCode = decodePrintData.L_PrintTicketEntity.P_TicketCode;
                    CurrentTicketEntity.L_RandomCode = decodePrintData.L_PrintTicketEntity.P_RandomCode;
                    CurrentTicketEntity.L_Password = decodePrintData.L_PrintTicketEntity.P_Password;
                    CurrentTicketEntity.L_SucTime = decodePrintData.L_PrintTicketEntity.P_SucTime;
                    CurrentTicketEntity.L_SaleAddress = decodePrintData.L_PrintTicketEntity.P_SaleAddress;
                    CurrentTicketEntity.L_CodeRate = decodePrintData.L_PrintTicketEntity.L_CodeRate;
                    CurrentTicketEntity.L_MaxGetMoney = decodePrintData.L_PrintTicketEntity.L_MaxGetMoney;
                    CurrentTicketEntity.L_CodeReference = decodePrintData.L_PrintTicketEntity.L_CodeReference;

                    this.txtTicketCode.Text = CurrentTicketEntity.L_TicketCode;
                    this.txtRandomCode.Text = CurrentTicketEntity.L_RandomCode;
                    this.txtPassword.Text = CurrentTicketEntity.L_Password;
                    this.txtCodeRate.Text = CurrentTicketEntity.L_CodeRate;
                    this.txtMaxGetMoney.Text = CurrentTicketEntity.L_MaxGetMoney.ToString("0.00");
                    this.txtCodeReference.Text = CurrentTicketEntity.L_CodeReference;
                }
                else
                {
                    MessageService.ShowMessage(string.Concat("自动提取票号失败，请核对票面信息与软件投注信息是否一致后手工输入票号！解析错误：", decodePrintData.ErrorMessage));
                }
            }
            catch (Exception e)
            {
                MessageService.ShowMessage(string.Concat("自动提取票号失败，请核对票面信息与软件投注信息是否一致后手工输入票号！错误信息：", e.Message));
            }
        }

        private void InputTicketCodeDialog_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = string.Format("手工输入票号[{0}]", MacNumber);
                FindLastTicket();
                if(CurrentTicketEntity!=null)
                {
                    this.txtAddTime.Text = CurrentTicketEntity.L_AddTime.ToString("yyyy-MM-dd HH:mm:ss");
                    this.txtCode.Text = CurrentTicketEntity.L_Code;
                    this.txtDataRequestId.Text = CurrentTicketEntity.L_DataRequestId.ToString();
                    this.txtExpect.Text = CurrentTicketEntity.L_Expect;
                    this.txtMacNumber.Text = CurrentTicketEntity.L_MacNumber;
                    this.txtMoney.Text = CurrentTicketEntity.L_Money.ToString("0");
                    this.txtMultiple.Text = CurrentTicketEntity.L_Mutiple.ToString();
                    this.txtOrderSn.Text = CurrentTicketEntity.L_OrderSn;
                    this.txtPlay.Text = CurrentTicketEntity.L_LotName + CurrentTicketEntity.L_PlayName;
                    this.txtSingleZhuShu.Text = CurrentTicketEntity.L_SingleZhuShu.ToString();
                    this.txtTicketSn.Text = CurrentTicketEntity.L_TicketSn;
                    //this.txtTicketCode.Text = "";
                    //this.txtPassword.Text = "";

                    if(CurrentTicketEntity.LotId==(int)Lottype.Jz||CurrentTicketEntity.LotId==(int)Lottype.Jl||CurrentTicketEntity.LotId==(int)Lottype.Jm)
                    {
                        this.groupBox1.Enabled = true;
                    }
                    else
                    {
                        this.groupBox1.Enabled = false;
                    }
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("手工输入票号对话框初始化异常。错误信息：", exception.Message));
            }
            
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentFileInfo != null)
                {
                    bool isencrypt = CurrentFileInfo.FullName.ToLower().IndexOf("alldata") < 0;
                    LotMachineService.PrintETicket(MacNumber,CurrentFileInfo.FullName,isencrypt);
                    //LotMachineService.PrinterClient.AddFile(CurrentFileInfo.FullName);
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowError(string.Concat("打印电子票异常。错误信息：", exception.Message));
            }
        }

    }
}