using Common;
using MeterPlugInLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CarMeterSystem
{
    public class CamerEs
    {
        #region
        private bool m_bInitSDK = false;
        private uint iLastErr = 0;
        private Int32 m_lUserID = -1;
        private Int32 m_lRealHandle = -1;
        private Int32 i = 0;
        private string str;
        private long iSelIndex = 0;
        private int[] iChannelNum = new int[96];

        private CHCNetSDK.NET_DVR_DEVICEINFO_V30 DeviceInfo;
        private CHCNetSDK.NET_DVR_IPPARACFG_V40 m_struIpParaCfgV40;
        private CHCNetSDK.NET_DVR_IPCHANINFO m_struChanInfo;
        private CHCNetSDK.NET_DVR_IPCHANINFO_V40 m_struChanInfoV40;
        public delegate void MyDebugInfo(string str);
        #endregion


        internal loginParam _lg = null;
        public CamerEs(loginParam lg) 
        {
            _lg = lg;

            m_bInitSDK = CHCNetSDK.NET_DVR_Init();
            if (m_bInitSDK == false)
            {
                MessageBox.Show("NET_DVR_Init error!");
                return;
            }
            else
            {
                //保存SDK日志 To save the SDK log
                CHCNetSDK.NET_DVR_SetLogToFile(3, "C:\\SdkLog\\", true);
                for (int i = 0; i < 64; i++)
                {
                    iChannelNum[i] = -1;
                }
            }
        }

        public void Login(PictureBox pb)
        {
            List<loginParam> lt = new List<loginParam>();
            if (_lg == null )
            {
                DebugInfo("请先载入摄像头信息");
            }

            if (m_lUserID < 0)
            {
                string DVRIPAddress = _lg.ip; //设备IP地址或者域名 Device IP
                Int16 DVRPortNumber = (Int16)_lg.port;
                string DVRUserName = _lg.userId;//设备登录用户名 User name to login
                string DVRPassword = _lg.pwd;//设备登录密码 Password to login

                //登录设备 Login the device
                m_lUserID = CHCNetSDK.NET_DVR_Login_V30(DVRIPAddress, DVRPortNumber, DVRUserName, DVRPassword, ref DeviceInfo);
                if (m_lUserID < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号 Failed to login and output the error code
                    DebugInfo(str);
                    return;
                }
                else
                {
                    //登录成功
                    DebugInfo("NET_DVR_Login_V30 succ!");

                    //加载预览信息
                    CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
                    lpPreviewInfo.hPlayWnd = pb.Handle;//预览窗口 live view window
                    lpPreviewInfo.lChannel = 1;//预览的设备通道 the device channel number
                    lpPreviewInfo.dwStreamType = 1;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
                    lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
                    lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
                    lpPreviewInfo.dwDisplayBufNum = 15; //播放库显示缓冲区最大帧数

                    IntPtr pUser = IntPtr.Zero;//用户数据 user data 
                    m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(m_lUserID, ref lpPreviewInfo, null/*RealData*/, pUser);
                }
            }
        }

        public void LoginOut()
        {
            //注销登录 Logout the device
            if (m_lRealHandle >= 0)
            {
                DebugInfo("Please stop live view firstly"); //登出前先停止预览 Stop live view before logout
                return;
            }

            if (!CHCNetSDK.NET_DVR_Logout(m_lUserID))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_Logout failed, error code= " + iLastErr;
                DebugInfo(str);
                return;
            }
            DebugInfo("NET_DVR_Logout succ!");
            m_lUserID = -1;
        }

        public void CapturePictrue(string fileUrl)
        {
            Log.GetInstance().WriteLog(35, "完成快速仪表拍照    成功标识：" + PbCache.shotSuccess.ToString() + "车号：" + PbCache.lockCarNo + "；重量：" + PbCache.lockWgt + "；时间：" + DateTime.Now.ToLongTimeString());
            if (!CHCNetSDK.NET_DVR_CapturePictureBlock(m_lRealHandle, fileUrl, 100))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_CaptureJPEGPicture failed, error code= " + iLastErr;
                DebugInfo(str);
                return;
            }
            Log.GetInstance().WriteLog(35, "结束快速仪表拍照    成功标识：" + PbCache.shotSuccess.ToString() + "车号：" + PbCache.lockCarNo + "；重量：" + PbCache.lockWgt + "；时间：" + DateTime.Now.ToLongTimeString());

        }

        #region
        protected void DebugInfo(string strMsg)
        {
            try
            {
                string m_szRunPath;
                m_szRunPath = System.Environment.CurrentDirectory;
                if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
                {
                    System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
                }
                string strDate = System.DateTime.Now.ToString("yyyyMMdd");
                string strPathFile = m_szRunPath + "\\log\\" + strDate;
                if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(strPathFile);
                }
                System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\视频_" + strDate + ".log", true);

                tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                tw.WriteLine(str);
                tw.WriteLine("\r\n");

                tw.Close();
            }
            catch { }
        }
        #endregion

    }
}
