using com.hnshituo.core.webapp.vo;
using Common;
using iCore.Rtdb.RtdbTable;
using MeterModuleLibrary.uc;
using MeterPlugInLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CarMonitor
{
    public partial class frmProductVoice : Form
    {
        #region 语音对讲
        /// <summary>
        /// 硬盘录像机登录
        /// </summary>
        DhCameraShot cameraShotMain = new DhCameraShot();

        /// <summary>
        /// 必须先打开连接
        /// </summary>
        private bool GetIPVideo(MeterBaseVideoinfo video)
        {
            try
            {
                cameraShotMain.ip = video.videoip;
                cameraShotMain.port = video.vdoPort;
                cameraShotMain.uid = video.vdoUser;
                cameraShotMain.pwd = video.vdoPwd;
                cameraShotMain.Connection();
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开视频连接失败：" + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 关闭视频
        /// </summary>
        private void IPVideoClose()
        {
            try
            {
                for (int i = 1; i <= plImg.Controls.Count; i++)
                {
                    cameraShotMain.StopRealPlay(i);
                    plImg.Controls.RemoveByKey("pb" + i);
                }
            }
            catch { }
            try
            {
                //退出视频及语音登录
                cameraShotMain.Close();
            }
            catch (Exception exp)
            {
                MessageBox.Show("关闭视频失败" + exp.Message);
            }
        }
        #endregion

        /// <summary>
        /// 用于防止跳闪选中
        /// </summary>
        bool chkFlag = false;

        public frmProductVoice()
        {
            InitializeComponent();
        }

        private void frmProductVoice_Load(object sender, EventArgs e)
        {
            timer1.Start();
            bd.getSpot();
            GetIPVideo(PbCacheMonitor.videoInfo);
            setPicBoxSet();
        }

        public ucCarMonitoring _uc = null;
        public MeterWorkMonitor drOldData = null;
        BaseDbCls bd = new BaseDbCls();
        MemoryTableDataSocket MemoClass = new MemoryTableDataSocket(PbCacheMonitor.collect_no);//内存表
        PbModelDbService<string> PbModelDbService = new PbModelDbService<string>();
        MeterMonitorNoteService noteService = new MeterMonitorNoteService();
        MeterWorkMonitorService monitorService = new MeterWorkMonitorService();
        public DbHelper db = null;

        /// <summary>
        /// 主界面调用的按钮事件
        /// </summary>
        public event EventHandler ucMonitoringEvent;


        #region 对讲代码
        private void setPicBoxSet()
        {
            if (PbCacheMonitor.videoChild != null && PbCacheMonitor.videoChild.Count > 0)
            {
                int i = 0;
                foreach (MeterBaseVideoChild child in PbCacheMonitor.videoChild)
                {
                    i++;
                    //if (i < 4 || i == 6) //只开启4个视频 1-3通道 左右上  6通道室内
                   if (i < 5) //只开启4个视频 1-3通道 左右上  6通道室内
                   {
                        PictureBox pb = new PictureBox();
                        pb.Name = "pb" + i;
                        pb.Dock = DockStyle.Top;
                        pb.Height = 235;
                        pb.DoubleClick += new EventHandler(PictureBoxDoubleClick);
                        pb.BorderStyle = BorderStyle.FixedSingle;
                        plImg.Controls.Add(pb);
                        cameraShotMain.RealPlay(pb, i);
                    }
                }
            }
        }

        int iPic = 0;
        /// <summary>
        /// 视频放大操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PictureBoxDoubleClick(object sender, EventArgs e)
        {
            if (iPic != 0)
            {
                cameraShotMain.StopRealPlay(iPic);
            }
            PictureBox picture = (PictureBox)sender;
            iPic = Convert.ToInt32(picture.Name.Substring(picture.Name.Length - 1, 1));
            plImgShow.Visible = true;
            cameraShotMain.RealPlay(pictureShow, iPic);
        }

       
        
        #endregion

        #region time事件
        /// <summary>
        /// 记录终端是否掉线
        /// </summary>
        int iTimeCnt = 0;

        /// <summary>
        /// 初始载入一次数据
        /// </summary>
        bool flagLoad = true;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (flagLoad)
            {
                lbPntName.Text = _uc.sPointName;
                flagLoad = false;
            }

            if (_uc.btnVoiceText != btnIpVoice.Text.Trim())
            {
                btnIpVoice.Text = _uc.btnVoiceText;
                btnIpVoice.BackColor = _uc.btnVoiceText == "挂断" ? Color.Red : Color.DodgerBlue;
            }
            
            if (_uc.rowPointInfo  != null)
            {
                if (drOldData != null && _uc.rowPointInfo.lastTime == drOldData.lastTime)
                {
                    iTimeCnt++;
                    if (iTimeCnt > 30)
                    {
                        setButtonColor(bcZD, "2");//终端掉线
                        setLoadBtnColor();
                        return;
                    }
                    else
                    {
                        iTimeCnt = 0;
                        setButtonColor(bcZD, "1");
                    }
                }
                drOldData = _uc.rowPointInfo;

                txtWeight.Text = drOldData.wgt == null ? "0kg" : drOldData.wgt.Value + "kg";

                List<LiveData> ll = MemoClass.getWarnInfo(_uc.rowPointInfo.collectionCode);
                if (ll != null)
                {
                    foreach (LiveData lv in ll)
                    {
                        switch (lv.Tagname.Replace(drOldData.collectionCode, ""))
                        {
                            case "StaticStatus"://车辆检测	"0、东西方向激光均无报警；否则报警
                                setButtonColor(bcAreaWarm, ((lv.Value ?? "0") + "") == "0" ? "1" : "2");
                                break;
                            case "SwitchLight"://PLC红绿灯控制模式状态	"PLC有三种控制模式：1、自动、2、远控；3、检修
                                setButtonColor(btnTakrOver, ((lv.Value ?? "1") + "") == "1" ? "0" : "2");
                                break;
                            case "LightWest"://红绿灯：1、为绿灯；2、为红灯；"
                                setButtonColor(btnRedLight, ((lv.Value ?? "1") + "") == "1" ? "2" : "0");
                                setButtonColor(btnGreenLight, ((lv.Value ?? "1") + "") == "1" ? "0" : "2");
                                break;
                            case "ZeroWeightStatus": //0、其它，1、零点报警，红绿灯变红，
                                setButtonColor(bcZeroWarn, ((lv.Value ?? "0") + "") != "1" ? "1" : "2");
                                break;
                        }
                    }
                }

                if (!chkFlag)
                {
                    chkVALID_WGT.Checked = drOldData.validWgt == "1" ? false : true;
                    chkVALID_TIME_INTERVAL.Checked = drOldData.validTimeInterval == "1" ? false : true;
                    chkVALID_PREDICTION_DIFF.Checked = drOldData.validPredictionDiff == "1" ? false : true;
                    chkVALID_PARK_STATUS.Checked = drOldData.validParkStatus == "1" ? false : true;
                    chkVALID_CARNO.Checked = drOldData.validCarno == "1" ? false : true;
                    chkVALID_TARE_TIME.Checked = drOldData.validTareTime == "1" ? false : true;
                    chkVALID_EXCEED_WGT.Checked = drOldData.validExceedWgt == "1" ? false : true;
                    chkLED_KEEP.Checked = drOldData.ledKeep == "1" ? true : false;

                    chkVALID_LIANDA.Checked = drOldData.validLianda == "1" ? false : true;
                    chkVALID_MAT_CLICK.Checked = drOldData.validMatClick == "1" ? false : true;
                    chkVALID_METER_AREA.Checked = drOldData.validMeterArea == "1" ? false : true;

                    //txtReplacePaper
                    chkFlag = false;
                }


                if (!string.IsNullOrEmpty(drOldData.setCar) && txtCarNo.Text.Trim() == "")
                {
                    cbCarNo.Text = drOldData.setCar.Substring(0, 1);
                    if (drOldData.setCar.Length > 1)
                        txtCarNo.Text = drOldData.setCar.Substring(1, drOldData.setCar.Length - 1);
                }


                txtMsgInfo.Text = drOldData.msgInfo;
                txtReplacePaper.Value = drOldData.printNum == null ? 0 : (drOldData.printNum.Value < 0 ? 0 : drOldData.printNum.Value);
                txtRfidCarNo.Text = drOldData.rfidCar;
                txtPhotoCarNo.Text = drOldData.photoCar;
                txtScanCarNo.Text = drOldData.scanCar;
                txtEditCarNo.Text = drOldData.editCar;
                setButtonColor(bcCarWarm, drOldData.carErr == "1" ? "2" : "1");//车号异常
                setButtonColor(bcWgtWarm, drOldData.wgtErr == "1" ? "2" : "1");//重量异常
                setButtonColor(bcTimed, drOldData.stopOverTime == "1" ? "2" : "1");//停留超时


                if (drOldData.isHelp == "1") //0未呼叫，1呼叫待接听，2呼叫已接听
                {
                    setButtonColor(bcHelpWarm, "2");//现场求助
                    setButtonColor(bcIpVoice, "2");//IP语音
                }
                else if (drOldData.isHelp == "2")
                {
                    //setButtonColor(bcHelpWarm, "3");//现场求助
                    setButtonColor(bcIpVoice, "3");//IP语音
                }
                else
                {
                    setButtonColor(bcHelpWarm, "1");//现场求助
                    setButtonColor(bcIpVoice, "1");//IP语音
                }

                if (drOldData.isTakeOver == "0")
                {
                    setButtonColor(bcAutoState, "3");//终端计量
                    setButtonColor(bcYcStatWarm, "1");//远程计量
                    setButtonColor(btnYc, "0");
                    //setButtonColor(btnPW, "0");
                    btnYc.Text = "远程计量";
                }
                else if (drOldData.isTakeOver == "1")
                {
                    //setButtonColor(btnPW, "2");
                    if (string.IsNullOrEmpty(drOldData.userNo))
                    {
                        setButtonColor(bcAutoState, "3");//终端计量
                        setButtonColor(bcYcStatWarm, "1");//远程计量
                    }
                    else
                    {
                        setButtonColor(bcAutoState, "1");//终端计量
                        setButtonColor(bcYcStatWarm, "3");//远程计量
                    }

                }
                /*
                else if (drOldData.isTakeOver == "2")
                {
                    setButtonColor(bcAutoState, "1");//终端计量
                    setButtonColor(bcYcStatWarm, "3");//远程计量
                    //setButtonColor(btnPW, "0");
                    setButtonColor(btnYc, "2");
                }
                //*/
                else
                {
                    setButtonColor(bcAutoState, "1");//终端计量
                    setButtonColor(bcYcStatWarm, "1");//远程计量
                    setButtonColor(btnYc, "0");
                    //setButtonColor(btnPW, "0");
                    btnYc.Text = "远程计量";
                }
            }
        }


        private void UpdateCarijeg(MeterWorkMonitor monitor, string content)
        {
            if (DialogResult.Yes == MessageBox.Show("确实要进行该操作吗？", "提示", MessageBoxButtons.YesNo))
            {
                RESTfulResult<string> rm = monitorService.doUpdateWf(monitor);
                if (rm.Succeed)
                {
                    WriteMonitorNote(content);
                    MessageBox.Show("操作成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    MessageBox.Show("操作失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }

        #region 按钮事件
        private void btnSend_Click(object sender, EventArgs e)
        {
            UpdateCarijeg(new MeterWorkMonitor { pointNo = _uc.sPoint, ledWriter = txtLed.Text.Trim() }, "写入LED信息：" + txtLed.Text.Trim());
        }


        #endregion

        private void btnSee_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnZero_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("确实要执行清零操作吗？", "提示", MessageBoxButtons.YesNo))
            {
                if (!string.IsNullOrEmpty(txtWeight.Text.Replace("kg", "")))
                {
                    int iValue = Convert.ToInt32(txtWeight.Text.Replace("kg", ""));
                    MeterBaseScaleRange mbsr = PbCacheMonitor.ltRange.Where(s => s.baseSpotNo == _uc.sPoint).FirstOrDefault();
                    if (mbsr != null)
                    {
                        if (mbsr.upperLimitClearZero < iValue || mbsr.lowerLimitClearZero > iValue)
                        {
                            MessageBox.Show("当前清零值不在允许范围");
                            return;
                        }
                    }
                }

                string msgInfo = "";
                MemoClass.writeWarnInfo(_uc.rowPointInfo.collectionCode, "ClearZero", "1", _uc.sUserId, out msgInfo);
                MessageBox.Show(msgInfo != "" ? msgInfo : "清零成功");
                WriteMonitorNote(_uc.sPointName + "执行清零操作，执行" + (msgInfo != "" ? "失败" + msgInfo : "清零成功"));
            }
        }

        private void btnIpVoice_Click(object sender, EventArgs e)
        {
            EventArgs arg = new EventArgs();
            if (ucMonitoringEvent != null)
            {
                ucMonitoringEvent(sender, arg);
            }
        }

        private void btnYc_Click(object sender, EventArgs e)
        {
            if (btnYc.Text == "远程计量")
            {
                UpdateCarijeg(new MeterWorkMonitor { pointNo = _uc.sPoint, isTakeOver = "1", userNo = "" }, "写入远程计量信息：" + btnYc.Text.Trim());
                btnYc.Text = "智能计量";
                btnYc.BackColor = Color.Red;
            }
            else
            {
                UpdateCarijeg(new MeterWorkMonitor { pointNo = _uc.sPoint, isTakeOver = "0", userNo = "" }, "远程计量切回智能计量：" + btnYc.Text.Trim());
                btnYc.Text = "远程计量";
                btnYc.BackColor = Color.DodgerBlue;
            }
        }

        private void btnTakrOver_Click(object sender, EventArgs e)
        {
            string strError = "";
            chkFlag = true;

            string sValue = "2";
            if (btnTakrOver.BackColor == Color.Red)
            {
                sValue = "1";
            }

            //切换为远程控制
            if (MemoClass.writeWarnInfo(_uc.rowPointInfo.collectionCode, "SwitchLight", sValue, _uc.sUserId, out strError))
            {
                WriteMonitorNote(_uc.sPointName + "设置远程接管");
            }
        }

        private void btnRedLight_Click(object sender, EventArgs e)
        {
            string strError = "";
            chkFlag = true;

            //红灯
            if (MemoClass.writeWarnInfo(_uc.rowPointInfo.collectionCode, "LightWest", "1", _uc.sUserId, out strError) && MemoClass.writeWarnInfo(_uc.rowPointInfo.collectionCode, "LightEast", "1", _uc.sUserId, out strError))
            {
                WriteMonitorNote(_uc.sPointName + "设置红绿灯为红灯");
            }
        }

        private void btnGreenLight_Click(object sender, EventArgs e)
        {
            string strError = "";
            chkFlag = true;

            //绿灯
            if (MemoClass.writeWarnInfo(_uc.rowPointInfo.collectionCode, "LightWest", "2", _uc.sUserId, out strError) && MemoClass.writeWarnInfo(_uc.rowPointInfo.collectionCode, "LightEast", "2", _uc.sUserId, out strError))
            {
                WriteMonitorNote(_uc.sPointName + "设置红绿灯为绿灯");
            }
        }

        private void btnReplacePaper_Click(object sender, EventArgs e)
        {
            UpdateCarijeg(new MeterWorkMonitor { pointNo = _uc.sPoint, printNum = Convert.ToInt32(txtReplacePaper.Value) }, "换纸：" + txtReplacePaper.Value);
        }

        private void btnCarSet_Click(object sender, EventArgs e)
        {
            UpdateCarijeg(new MeterWorkMonitor { pointNo = _uc.sPoint, setCar = cbCarNo.Text + txtCarNo.Text.Trim() }, "重置车号为：" + cbCarNo.Text.Trim() + txtCarNo.Text.Trim());
        }

        private void frmProductVoice_FormClosing(object sender, FormClosingEventArgs e)
        {
            IPVideoClose();
            timer1.Stop();
        }


        /// <summary>
        /// 双击关闭大图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureShow_DoubleClick(object sender, EventArgs e)
        {
            plImgShow.Visible = false;
            cameraShotMain.StopRealPlay(iPic);
            iPic = 0;
        }

        private void WriteMonitorNote(string content)
        {
            RESTfulResult<string> rm = noteService.doAddWf(new MeterMonitorNote
            {
                baseSpotNo = _uc.sPoint,
                baseSpotName = _uc.sPointName,
                operationContent = content,//str + chk.Text,
                carNo = cbCarNo.Text.Trim() + txtRfidCarNo.Text.Trim(),
                meterManNo = _uc.sUserId,
                meterManName = _uc.sName,
                meterNoteSource = "2"
            });

            if (!rm.Succeed)
            {
                WriteLog("写入操作日志异常：" + content);
            }
        }

        #region
        private void chkVALID_PARK_STATUS_CheckedChanged(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkVALID_WGT_CheckedChanged(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkVALID_TIME_INTERVAL_CheckedChanged(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkVALID_TARE_TIME_CheckedChanged(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkVALID_EXCEED_WGT_CheckedChanged(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkVALID_PREDICTION_DIFF_CheckedChanged(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkLED_KEEP_CheckedChanged(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkVALID_CARNO_CheckedChanged(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }


        /// <summary>
        /// 点击事件公共方法：更新METER_WORK_MONITOR表中字段为“控件名”的值为 1 
        /// </summary>
        /// <param name="chk"></param>
        private void chkEvent(CheckBox chk)
        {
            string str = "取消勾选";
            if (chk.Checked)
            {
                str = "勾选";
            }

            string sql = string.Format("update METER_WORK_MONITOR set {0} = '{1}' where POINT_NO='{2}'", chk.Name.Replace("chk", ""), chk.Checked ? "0" : "1", _uc.sPoint);
            RESTfulResult<string> rm = PbModelDbService.executeSqlDataWf(sql);
            if (rm.Succeed)
            {
                WriteMonitorNote(str + chk.Text);
            }
        }
        #endregion


        private void setLoadBtnColor()
        {
            bcZeroWarn.BackColor = Color.Green;
            bcWgtWarn.BackColor = Color.Green;

            foreach (Control cn in groupBox3.Controls)
            {
                if (cn.Name.Contains("bc"))
                {
                    if (cn.Name != "bcZD")
                    {
                        cn.BackColor = Color.Green;
                    }
                }
            }

            btnIpVoice.BackColor = Color.DodgerBlue;
            btnRedLight.BackColor = Color.DodgerBlue;
            btnGreenLight.BackColor = Color.DodgerBlue;
        }
        /// <summary>
        /// 按钮颜色设置
        /// </summary>
        /// <param name="button">按钮</param>
        /// <param name="sColor">0：DodgerBlue 1：Green  2：Red</param>
        private void setButtonColor(Button button, string sColor)
        {
            switch (sColor)
            {
                case "0":
                    button.BackColor = Color.DodgerBlue;
                    break;
                case "1":
                    button.BackColor = Color.Green;
                    break;
                case "2":
                    button.BackColor = Color.Red;
                    break;
                case "3":
                    button.BackColor = Color.Orange;
                    break;
            }
        }
        #endregion


        #region 日志
        public void WriteLog(string str)
        {
            try
            {
                string strLogName = "计量监控_";
                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 + "\\" + strLogName + 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 (Exception ex)
            {

            }
        }
        #endregion

        private void btnPW_Click(object sender, EventArgs e)
        {
            /*
            if (btnYc.BackColor != Color.Red)
            {
                if (btnPW.BackColor == Color.DodgerBlue)
                {
                    UpdateCarijeg(new MeterWorkMonitor { pointNo = _uc.sPoint, isTakeOver = "1" }, "进行派位处理");
                    btnPW.BackColor = Color.Red;
                }
                else
                {
                    UpdateCarijeg(new MeterWorkMonitor { pointNo = _uc.sPoint, isTakeOver = "0" }, "取消派位处理");
                    btnPW.BackColor = Color.DodgerBlue;
                }
            }
            else
            {
                MessageBox.Show("请先释放请先释放远程终端接管");
            }
            //*/
        }

        private void chkVALID_MAT_TIME_Click(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkVALID_LIANDA_Click(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        private void chkVALID_MAT_CLICK_Click(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }

        /// <summary>
        /// 不验证计量区域
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkVALID_METER_AREA_Click(object sender, EventArgs e)
        {
            chkFlag = true;
            chkEvent((CheckBox)sender);
        }
    }
}
