//*****************************************************************************
//
//   中国航天科工集团第二研究院
//    北京无线电计量测试研究所
//
// 项目名称: 嵌入式虹膜考勤系统
// 项目版本: 2019.11.27 识别产品化-开始
//
//*****************************************************************************
using System;
using System.Windows.Forms;
using System.Threading;
using irisRefactor.IrisCamera;
using System.Reflection;
using System.Drawing;
using irisRefactor.IrisSound;
using System.Data;
using System.Runtime.InteropServices;
using irisHelper;
using irisRefactor.IrisScoket;
using irisDataBase.Model;
using irisDataBase;
using irisPrint.service;
using irisPrint.Impl;
using IrisDoor;

namespace irisRefactor.FrmService
{
    public partial class Form2 : Form
    {
        private static Form2 _form2 = null;
        public static Form2 GetInstance()
        {
            if (_form2 == null)
                _form2 = new Form2();

            return _form2;
        }

        private Form2()
        {
            try
            {
                InitializeComponent();
              
                PictureBox.CheckForIllegalCrossThreadCalls = false;
                // 设置双缓冲
                SetStyle(ControlStyles.UserPaint, true);
                SetStyle(ControlStyles.AllPaintingInWmPaint, true);
                SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

                Form2.CheckForIllegalCrossThreadCalls = false;
            }
            catch (Exception e)
            {
                MessageBox.Show("fail: " + e);
            }
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                ProMemory.Close();
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "closeing..." + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region 外部调用方法
   
        public void ReInitialize()
        {
            try
            {
                if (this.IsHandleCreated)
                {
                    Invoke(new MethodInvoker(delegate ()
                    {
                        picLive.Visible = true;
                        pictureBox1.Visible = true;
                        pictureBox2.Visible = true;
                        pictureBox3.Visible = true;
                        pictureBox4.Visible = true;
                        pictureBox5.Visible = true;
                        pictureBox6.Visible = true;
                        pictureBox7.Visible = true;
                        pictureBox8.Visible = true;

                        name_label.Text = "";
                        gender_label.Text = "";
                        department_label.Text = "";
                        time_label.Text = "";

                        picFace.Image = null;

                        pictureBox9.Visible = false;

                    }));

                    ProMemory.IoControllService.YellowOff();
                    ProMemory.IoControllService.GreenOff();
                    ProMemory.IoControllService.RedOff();
                    ProMemory.IoControllService.YellowOn();

                    try
                    {
                        lock (ProMemory.irisConfig.QueueFace)
                        {
                            ProMemory.irisConfig.QueueFace.Clear();
                        }

                        lock (ProMemory.irisConfig.Q2)
                        {
                            ProMemory.irisConfig.Q2.Clear();
                        }

                        lock (ProMemory.irisConfig.Q3)
                        {
                            ProMemory.irisConfig.Q3.Clear();
                        }
                        lock (ProMemory.irisConfig.QueueIdentify)
                        {
                            ProMemory.irisConfig.QueueIdentify.Clear();
                        }
                    }
                    catch (Exception ee)
                    {
                        LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "errorerrorerror ： clear q1/q2/q3/q4 ：" + ee.Message);
                    }

                    ProMemory.irisConfig.IdentifyAccess = false;
                    // ProMemory.findingEyes = false;

                    Thread.Sleep(100);
                    ProMemory.irisConfig.Key_FindEyes = 0;
                    ProMemory.irisConfig.Key_Assess = 0;
                    ProMemory.irisConfig.Key_Identify = 0;
                    
                }
            }
            catch (Exception ex)
            {
                string msg = "初始化失败!" + ex.Message;
                LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, msg);
            }

        }

        public void ReInitializeToSleep()
        {
            try
            {
                if (this.IsHandleCreated)
                {
                    Invoke(new MethodInvoker(delegate ()
                    {
                        picLive.Visible = true;
                        name_label.Text = "";
                        gender_label.Text = "";
                        department_label.Text = "";
                        time_label.Text = "";
                        pictureBox9.Visible = false;

                    }));

                    ProMemory.IoControllService.YellowOff();
                    ProMemory.IoControllService.GreenOff();
                    ProMemory.IoControllService.RedOff();
                    try
                    {
                        lock (ProMemory.irisConfig.QueueFace)
                        {
                            ProMemory.irisConfig.QueueFace.Clear();
                        }
                        lock (ProMemory.irisConfig.Q2)
                        {
                            ProMemory.irisConfig.Q2.Clear();
                        }
                        lock (ProMemory.irisConfig.Q3)
                        {
                            ProMemory.irisConfig.Q3.Clear();
                        }
                        lock (ProMemory.irisConfig.QueueIdentify)
                        {
                            ProMemory.irisConfig.QueueIdentify.Clear();
                        }
                    }
                    catch (Exception ee)
                    {
                        LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "errorerrorerror ： clear q1/q2/q3/q4 ：" + ee.Message);
                    }


                    ProMemory.irisConfig.IdentifyAccess = false;
                    // ProMemory.findingEyes = false;

                    Thread.Sleep(100);
                    ProMemory.irisConfig.Key_FindEyes = 0;
                    ProMemory.irisConfig.Key_Assess = 0;
                    ProMemory.irisConfig.Key_Identify = 0;
                }
            }
            catch (Exception ex)
            {
                string msg = "初始化失败!" + ex.Message;
                LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, msg);
            }

        }

        public void Failure()
        {
            if (ProMemory.isSyning) return;

            try
            {
                Invoke(new MethodInvoker(delegate ()
                {
                    picLive.Visible = false;
                    pictureBox1.Visible = false;
                    pictureBox2.Visible = false;
                    pictureBox3.Visible = false;
                    pictureBox4.Visible = false;
                    pictureBox5.Visible = false;
                    pictureBox6.Visible = false;
                    pictureBox7.Visible = false;
                    pictureBox8.Visible = false;

                    pictureBox9.Visible = true;
                    pictureBox9.Dock = DockStyle.Fill;
                    //识别失败，请重试
                    PlaySound.recFailureRetry();
                }
                ));
                
                ProMemory.IoControllService.YellowOff();
                ProMemory.IoControllService.RedOn();

            }
            catch (Exception ex)
            {
            }
        }

        public void Success(string sPersonId)
        {
            if (ProMemory.isSyning) return;
            long personId = long.Parse(sPersonId);

            DatabaseLocal.OpenDB(ProMemory.appConfig.DbLocalConfig);
            PersonView personView = ProMemory.irisPersonViewService.getPersonViewByPersonIdLocal(personId);

            String name = personView.getName();
            String sex = personView.getSex();
            String deptName = personView.getDeptName();
            String idCardNo = personView.getIdCardNo();
            String photo = personView.getPhoto();

            //立思辰打印
            if (ProMemory.appConfig.AuthConfig.HasPrintAuthority)
            {
                PlaySound.recSuccess();
                PrintInterface print = new PrintHelper();
                print.Print(idCardNo, ProMemory.appConfig.AuthConfig.PrintDt.DeviceSN, ProMemory.appConfig.AuthConfig.PrintDt.DestIp,
                    ProMemory.appConfig.AuthConfig.PrintDt.DestPort);

                ProMemory.stringBuilder.Clear();
                ProMemory.stringBuilder.Append("print person：");
                ProMemory.stringBuilder.Append(name);

                LogHelper.WriteInfoLog(MethodBase.GetCurrentMethod().DeclaringType, ProMemory.stringBuilder.ToString());
            }

            Image image = null;
            //下载照片
            image = personView.getPhotoData();

            try
            {
                ProMemory.IoControllService.YellowOff();
                ProMemory.IoControllService.GreenOn();

                DateTime dtNow = DateTime.Now;

                //界面显示
                Invoke(new MethodInvoker(delegate ()
                {
                    name_label.Text = name;
                    gender_label.Text = sex;
                    department_label.Text = deptName;
                    time_label.Text = dtNow.ToString("yyyy-MM-dd HH:mm");

                    //照片
                    if (image != null)
                    {
                        picFace.Image = image;
                    }

                    picLive.Visible = false;
                    pictureBox1.Visible = false;
                    pictureBox2.Visible = false;
                    pictureBox3.Visible = false;
                    pictureBox4.Visible = false;
                    pictureBox5.Visible = false;
                    pictureBox6.Visible = false;
                    pictureBox7.Visible = false;
                    pictureBox8.Visible = false;
                }
                ));

                //写txt日志
                ProMemory.stringBuilder.Clear();
                ProMemory.stringBuilder.Append(name);
                ProMemory.stringBuilder.Append(",");
                ProMemory.stringBuilder.Append(sex);
                ProMemory.stringBuilder.Append(",");
                ProMemory.stringBuilder.Append(deptName);

                //门禁功能
                string devCode = "";
                string doorCode = "";
                string inoutType = "";


                if (ProMemory.hostIp != "" && ProMemory.hostIp != "127.0.0.1")
                {
                    devCode = ProMemory.irisDeviceService.getDevCode(ProMemory.hostIp);
                }

                //门禁功能
                if (ProMemory.appConfig.AuthConfig.HasOpenDoorAuthority)
                {
                    bool hasPermisson = ProMemory.irisPermisionService.GetOpenDoorPermision(ProMemory.appConfig.AuthConfig, personId,
                        devCode, out doorCode, out inoutType);

                    DoorSound(hasPermisson);
                }
                else
                    NoDoorSound();

                //考勤
                ProMemory.irisRecordsService.insertRecordsLocal(personId, dtNow, "",
                       devCode, doorCode, inoutType);

                LogHelper.WriteInfoLog(MethodBase.GetCurrentMethod().DeclaringType, ProMemory.stringBuilder.ToString());

            }
            catch (Exception e)
            {
                LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "success:" + e.Message);
            }
            finally
            {
                if (DatabaseLocal.mySqlConnect.State != ConnectionState.Closed)//本地数据库
                {
                    DatabaseLocal.CloseDB();
                }
            }

        }

        private void DoorSound(bool hasPermisson)
        {
            //有权限
            if (hasPermisson)
            {
                Thread openDoorTh = new Thread(DoorSystem.open);
                openDoorTh.Start();

                //识别成功亲开门
                PlaySound.successPass();
            }
            else
            {
                PlaySound.successsNoPower();
                //识别成功无权限
            }
        }

        private void NoDoorSound()
        {
            //识别成功
            PlaySound.recSuccess();
        }

        #endregion

        private void Form2_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keys.Escape == e.KeyCode)
            {
                // 按键ESC，则退出程序
                LogHelper.WriteWarnLog(MethodBase.GetCurrentMethod().DeclaringType, "按下ESC键，退出");
                System.Environment.Exit(0);
            }
        }
    }
}