using com.hnshituo.core.webapp.vo;
using Common;
using Infragistics.Win.UltraWinGrid;
using MeterConditionLibrary;
using MeterModuleLibrary;
using MeterPlugInLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using JC_MeasuringSystem;
using MeterSceneLibrary;
using Infragistics.Win;
using MeterModelLibrary;

namespace CarRemoteMeter
{
    public partial class Form2 : Form
    {
        //图片控制器含图片压缩及上传sftp
        ImageControl imageControl = new ImageControl();

        /// <summary>
        /// 基础数据载入
        /// </summary>
        private BaseDbCls bd = new BaseDbCls();
        Log l = Log.GetInstance();
        string userId = "", userName = "";
        CoreAppUser appUser = null;

        //实时表数据采集
        DataCollectionControl collection = new DataCollectionControl();
        bool bCollectionStart = false;

        #region 服务查询
        //预报查询
        PreTrackScaleService service = new PreTrackScaleService();
        PreTrackScale preTack = null;


        //与监控界面对接的表
        MeterWorkMonitorService monitorService = new MeterWorkMonitorService();

        //实时在线写入，每隔2秒一次
        MeterWorkOnlineService onlineService = new MeterWorkOnlineService();


        //验证是否可留期限皮
        validTermTareCar termTareCar = new validTermTareCar();

        //留期限皮操作
        MeterBaseTermTareDataService termTareDate = new MeterBaseTermTareDataService();

        //内倒业务处理
        InnerRemoteMeter inner = new InnerRemoteMeter();

        //非内倒业务处理
        SceneControl scene = new SceneControl();

        //历史皮重数据
        MeterBaseHisTareDataService meterBaseHisTareData = new MeterBaseHisTareDataService();

        //计量实绩
        MeterWorkCarActualService mwas = new MeterWorkCarActualService();

        //校秤记录
        MeterWorkCalibrationMainService mainService = new MeterWorkCalibrationMainService();

        //附加重量
        PerAddWeightService perAddWeight = new PerAddWeightService();

        //一次计量重量
        MeterWorkCarActualFirst first = null;

        MeterMonitorWeightService monitorWeightService = new MeterMonitorWeightService();

        string sPreNo = ""; //记录重量曲线变化
        int preWgt = 0;//前一次重量，用于重量曲线
        #endregion

        string preCarNo = "";//上次车号
        string editCarNo = "";//修正车号

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                timer1.Stop();
                timer2.Stop();
            }
            catch { }

            try
            {
                Clean();
            }
            catch { }

            try
            {
                imageControl.Stop();
            }
            catch { }
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            //setMsgInfo(btnInnerQuery, "false", "1");
            setMsgInfo(btnCheck, "false", "1");
            setMsgInfo(btnSave, "false", "1");
            setMsgInfo(btnTareWgt, "false", "1");
            setMsgInfo(btnCheckBalance, "false", "1");

            ValueList vlist = new ValueList();
            vlist.ValueListItems.Add("0", "批次预报");
            vlist.ValueListItems.Add("1", "单次预报");
            vlist.ValueListItems.Add("2", "联运预报");
            vlist.ValueListItems.Add("3", "分检预报");
            ultraGridYb.DisplayLayout.Bands[0].Columns["predictionType"].ValueList = vlist;

            timer1.Start();
            collection.EventDataCollectionArgs += new EventDataCollection(EventData);//数据采集

            userId = ((ST_MainForm)(this.MdiParent)).UserID;
            userName = ((ST_MainForm)(this.MdiParent)).UserName;
            appUser = ((ST_MainForm)(this.MdiParent)).AppUser;

            if (bd.setBaseDb() && bd.getBaseDb())
            {
                timer2.Start();
                lbPointName.Text = "";
                lbMeterMan.Text = userName;
                PbCache.isNotValid = true;
                imageControl.Start();
            }
            else
            {
                MessageBox.Show("基础数据载入失败，请稍后重试，或联系管理员");
                this.Close();
            }

            //txtCarNo.LostFocus += new EventHandler(txtCarNo_KeyDown);
            lbWgt.LostFocus+= new EventHandler(lbWgt_ValueChanged);
        }


        #region 数据采集部分
        int iCounts = 0; //计数器
        bool iWgtChange = true; //重量初次大于500

        //车号修正
        CarNoModfiy modfiy = new CarNoModfiy();

        /// <summary>
        /// 数据采集
        /// </summary>
        private void EventData(object o, DataCollectionArgs e)
        {
            //这里每隔0.5秒执行一次
            try
            {
                if (iCounts < 1200)
                {
                    iCounts++;
                }
                else
                {
                    iCounts = 0;
                    try
                    {
                        //秤上没有车时，每隔10分钟获取一次基础数据
                        if (e.weight < 500)
                        {
                            editCarNo = "";
                            preCarNo = "";
                            if (bd.setBaseDb())
                            {
                                l.WriteLog(0, "十分钟获取基础数据成功");
                            }
                            else
                            {
                                l.WriteLog(0, "十分钟获取基础数据失败");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        l.WriteLog(0, "十分钟获取基础数据失败：" + ex.Message);
                    }
                }

                #region
                PbCache.collect.pointid = PbCache.sportInfo.baseSpotNo;

                #if DEBUG
                //*
                if (iCounts > 10 && bTest)
                {
                    bTest = false;
                    Random rd = new Random();
                    e.carno = "湘A01234";
                    e.weight = iTestWgt;//rd.Next(40000, 50000);
                }
                else
                {
                    e.weight = iTestWgt;
                }
                //*/
                #endif

                PbCache.collect.weight = e.weight;
                PbCache.collect.weightStatus = e.weightStatus;
                PbCache.collect.parkStatus = e.parkStatus;
                PbCache.collect.datetime = e.datetime;
                PbCache.collect.licType = e.licType;

                #region 车号设置
                getFocusInfo(txtCarNo);
                if (!isFocus) //光标不在里面
                {
                    if (strCbCarNo == "" || strTxtCarNo == "")
                    {
                        PbCache.collect.carno = e.carno;
                        if (!string.IsNullOrEmpty(e.carno) && e.carno.Length > 1)
                        {
                            if (preCarNo == "")
                            {
                                preCarNo = e.carno;
                                string methods = "";
                                for (int i = 0; i <= PbCache.monitor.carMonitorLvl; i++)
                                {
                                    methods += "CarNoTrustCorrect" + i + ",";
                                }
                                editCarNo = modfiy.CarNoCorrect(e.carno, methods.Substring(0, methods.Length - 1));
                            }
                            e.carno = editCarNo;


                            setTxtCarNo(e.carno.Substring(1, e.carno.Length - 1));
                            setCbCarNoInfo(e.carno.Substring(0, 1));
                            QueryCarNo();
                        }
                    }
                    else
                    {
                        if (!flagCarNo && (strCbCarNo + strTxtCarNo) != e.carno) //没有按回车，且车号不等于的时候
                        {
                            if (!string.IsNullOrEmpty(e.carno) && e.carno.Length > 1)
                            {
                                if (preCarNo == "" || preCarNo != e.carno)
                                {
                                    preCarNo = e.carno;
                                    string methods = "";
                                    for (int i = 0; i <= PbCache.monitor.carMonitorLvl; i++)
                                    {
                                        methods += "CarNoTrustCorrect" + i + ",";
                                    }
                                    editCarNo = modfiy.CarNoCorrect(e.carno, methods.Substring(0, methods.Length - 1));
                                }
                                e.carno = editCarNo;


                                PbCache.collect.carno = e.carno;
                                setTxtCarNo(e.carno.Substring(1, e.carno.Length - 1));
                                setCbCarNoInfo(e.carno.Substring(0, 1));
                                QueryCarNo();
                            }
                        }
                        else if (flagCarNo)
                        {
                            PbCache.collect.carno = strCbCarNo + strTxtCarNo;
                        }
                    }
                }
                #endregion


                //重量大于500的情况下
                if (e.weight > 500)
                {
                    if (!PbCache.isLockFrm)
                    {
                        ucWeightT1.setWgt(PbCache.collect.weight);
                        ucWeightT1.setStable(PbCache.collect.weightStatus != 1 ? true : false);
                        ucWeightT1.setExceed(PbCache.collect.weight > PbCache.range.upperRange ? false : true);

                        PbCache.addWgt = dAddWgt;
                        if (first != null)
                        {
                            if (PbCache.collect.weight < first.meterWeight.Value)
                            {
                                setMsgInfo(txtTare, PbCache.collect.weight + "", "");
                                setMsgInfo(txtGroess, first.meterWeight.Value + "", "");
                            }
                            else
                            {

                                setMsgInfo(txtGroess, PbCache.collect.weight + "", "");
                                setMsgInfo(txtTare, first.meterWeight.Value + "", "");
                            }
                            double dbAddWgt = 0;
                            if (first.addWeight != null && first.addWeight.Value > 0)
                            {
                                dbAddWgt = first.addWeight.Value;
                            }
                            else
                            {
                                dbAddWgt = dAddWgt;
                            }
                            //PbCache.addWgt = dbAddWgt;
                            setMsgInfo(txtNet, Math.Abs(PbCache.collect.weight - first.meterWeight.Value) - dbAddWgt + "", "");
                        }
                    }

                    if (iWgtChange)
                    {
                        setMsgInfo(btnInnerQuery, "true", "1");
                        setMsgInfo(btnSave, "true", "1");
                        setMsgInfo(btnTareWgt, "true", "1");
                        setMsgInfo(btnCheckBalance, "true", "1");
                        setMsgInfo(btnCheck, "true", "1");
                        setReadOnlyInfo(txtPREDICTION_NO, "false", "0");
                    }

                    if (PbCache.dtStartTime == null)
                        PbCache.dtStartTime = DateTime.Now;

                    //每隔1秒刷一次计量实时监控表数据值
                    if (iCounts % 2 == 0)
                    {
                        #region 每隔1秒写入一次重量曲线
                        try
                        {
                            if (preWgt != e.weight)
                            {
                                sPreNo = PbCache.sportInfo.baseSpotNo + DateTime.Now.ToString("yyyyMMddHHmmssfff");

                                monitorWeightService.doAddWf(new MeterMonitorWeight
                                {
                                    weightNo = sPreNo,
                                    baseSpotNo = PbCache.sportInfo.baseSpotNo,
                                    baseSpotName = PbCache.sportInfo.baseSpotName,
                                    collectWeight = e.weight + "",
                                    collectStartTime = PbCache.dtStartTime.Value,
                                    collectEndTime = DateTime.Now,
                                    spotTypeNo = "001002001",
                                    spotTypeName = "汽车衡",
                                    actualFirstNo = PbCache.actualFirstNo
                                });
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(sPreNo))
                                {
                                    monitorWeightService.doUpdateWf(new MeterMonitorWeight
                                    {
                                        weightNo = sPreNo,
                                        collectEndTime = DateTime.Now
                                    });
                                }
                            }
                        }
                        catch { }
                        #endregion

                        switch (e.parkStatus)
                        {
                            case 1:
                                setPicQRed(true);
                                setPicHRed(false);
                                break;
                            case 2:
                                setPicQRed(false);
                                setPicHRed(true);
                                break;
                            case 3:
                                setPicQRed(true);
                                setPicHRed(true);
                                break;
                            default:
                                setPicQRed(false);
                                setPicHRed(false);
                                break;
                        }
                    }
                    iWgtChange = false;
                }
                else
                {
                    if (flagStart && strIsRemote == "0")
                    {
                        Clean();
                    }
                    else
                    {
                        CleanForm();
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                l.WriteLog(0, "frmMeterMain.EventData异常2：" + ex.Message);
            }
        }
        #endregion

        #region 从接管到未的时候清理下数据
        //清理一次数据
        private void Clean()
        {
            if (PbCache.sportInfo == null || string.IsNullOrEmpty(PbCache.sportInfo.baseSpotNo)) return;
            MeterWorkMonitor mwmUpdate = new MeterWorkMonitor
            {
                pointNo = PbCache.sportInfo.baseSpotNo,
                validWgt = "1",
                validCarno = "1",
                validTareTime = "1",
                validMatTime = "1",
                validTimeInterval = "1",
                validParkStatus = "1",
                validExceedWgt = "1",
                validPredictionDiff = "1",
                setCar = "",
                rfidCar = "",
                photoCar = "",
                scanCar = "",
                editCar = "",
                carErr = "0",
                wgtErr = "0",
                stopOverTime = "0",
                msgInfo = "",
                //isTakeOver = "0",
                //userNo = "",
                ledWriter = ""
            };

            if (bVoice)
            {
                mwmUpdate.isHelp = "0";
            }
            //如果为1则是监控点击的远程计量，这个时候是不能清理的
            if (strIsRemote == "0")
            {
                mwmUpdate.userNo = "";
                mwmUpdate.isTakeOver = "0";
            }

            RESTfulResult<string> rm = monitorService.doUpdateWf(mwmUpdate);
            if (!rm.Succeed)
            {
                l.WriteLog(5, "初始化远程计量信息失败");
            }
            else
            {
                RESTfulResult<string> rmx = onlineService.doSaveWf(new MeterWorkOnline { userId = userId, workFlag = "0" });
                if (rmx.Succeed)
                {
                    CleanForm();
                    CleanCloseDb();
                }
                else
                {
                    l.WriteLog(5, "初始化在线接管状态失败");
                }
            }
        }

        //如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        public void setMsgInfo(Control control, string ResultMessage, string sType)
        {
            setMsgMsg(control, ResultMessage, sType);
        }

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable  3为check
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setMsgMsg(Control control, string ResultMessage, string sType)
        {
            if (control.InvokeRequired)
            {
                Action<Control, string, string> action = new Action<Control, string, string>(setMsgInfo);
                Invoke(action, new object[] { control, ResultMessage, sType });
            }
            else
            {
                if (ResultMessage != "true" && ResultMessage != "false")
                {
                    control.Text = ResultMessage == null ? "" : ResultMessage.Replace("请远程求助", "").Replace("，请点击语音求助", "");
                }
                else
                {
                    switch (sType)
                    {
                        case "1":
                            control.Enabled = ResultMessage == "true" ? true : false;
                            ; break;
                        case "2":
                            control.Visible = ResultMessage == "true" ? true : false;
                            ; break;
                        case "3":
                            ((CheckBox)control).Checked = ResultMessage == "true" ? true : false;
                            break;
                        default: break;
                    }
                }
            }
        }

        public void setListBoxInfo(ListBox control)
        {
            setListBoxMsg(control);
        }

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setListBoxMsg(ListBox control)
        {
            if (control.InvokeRequired)
            {
                Action<ListBox> action = new Action<ListBox>(setListBoxInfo);
                Invoke(action, new object[] { control });
            }
            else
            {
                control.Items.Clear();
            }
        }

        /// <summary>
        /// 设置readonly
        /// </summary>
        /// <param name="control"></param>
        /// <param name="sType">0为textbox 1为button</param>
        public void setReadOnlyInfo(Control control, string resultMsg, string sType)
        {
            setReadOnlyMsg(control, resultMsg, sType);
        }

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setReadOnlyMsg(Control control, string resultMsg, string sType)
        {
            if (control.InvokeRequired)
            {
                Action<Control, string, string> action = new Action<Control, string, string>(setReadOnlyInfo);
                Invoke(action, new object[] { control, resultMsg, sType });
            }
            else
            {
                switch (sType)
                {
                    case "0":
                        ((TextBox)control).ReadOnly = resultMsg == "true" ? true : false;
                        break;
                }
            }
        }


        public void setPanelRemovenfo(Panel control)
        {
            setPanelRemoveMsg(control);
        }

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setPanelRemoveMsg(Panel p)
        {
            if (p.InvokeRequired)
            {
                Action<Panel> action = new Action<Panel>(setPanelRemovenfo);
                Invoke(action, new object[] { p });
            }
            else
            {
                for (int i = p.Controls.Count - 1; i >= 0; i--)
                {
                    p.Controls.RemoveAt(i);
                }
            }
        }

        public void setGridInfo(UltraGrid control, DataTable dt1, DataTable dt2)
        {
            setGridMsg(control, dt1, dt2);
        }

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setGridMsg(UltraGrid p, DataTable dt1, DataTable dt2)
        {
            if (p.InvokeRequired)
            {
                Action<UltraGrid, DataTable, DataTable> action = new Action<UltraGrid, DataTable, DataTable>(setGridInfo);
                Invoke(action, new object[] { p, dt1, dt2 });
            }
            else
            {
                ClsControlPack.CopyDataToDatatable(ref dt1, ref dt2, true);
                ClsControlPack.RefreshAndAutoSize(p);
            }
        }


        private void CleanCloseDb()
        {
            //*****************这里需要将语音对讲/视频都关闭*******************
            //退出语音登录
            try
            {
                VoiceClose();
                IPVideoClose();
            }
            catch (Exception ex)
            {

            }

            ls = null;
            //*****************************************************************
            flagCarNo = false;
            setMsgInfo(plImgShow, "false", "2");


            DataTable dtJld = dtJGPointInfo.Clone();
            setGridInfo(ultraGridPW, dtJld, this.dtJGPointInfo);
            setMsgInfo(lbPointName, "", "");
            setMsgInfo(lbMeterMan, "", "");


            PbCache.Load();
            PbCache.sportInfo = null;
            PbCache.videoInfo = null;
            PbCache.videoChild = null;
            CarCache.cameraShots = null;
            PbCache.range = null;
            PbCache.relations = null;

            setPanelRemovenfo(panel1);

            bCollectionStart = false;
            //关闭采集进程
            collection.Stop();
        }

        private void CleanForm()
        {
            editCarNo = "";
            preCarNo = "";

            sPreNo = "";
            preWgt = 0;

            ls = null;
            preTack = null;
            iWgtChange = true;
            PbCache.dtStartTime = null;
            PbCache.isTermTare = false;
            PbCache.addWgt = 0;
            dAddWgt = 0;
            first = null;
            PbCache.isLockFrm = false;
            PbCache.lockWgt = 0;
            PbCache.lockCarNo = "";
            strCbCarNo = "";
            strTxtCarNo = "";
            strType = "0";
            PbCache.ResultMessage = "";

            setMsgInfo(btnInnerQuery, "false", "1");
            setMsgInfo(btnCheck, "false", "1");
            setMsgInfo(btnSave, "false", "1");
            setMsgInfo(btnTareWgt, "false", "1");
            setMsgInfo(btnCheckBalance, "false", "1");
            setMsgInfo(txtGroess, "", "");
            setMsgInfo(txtTare, "", "");
            setMsgInfo(txtNet, "", "");
            setMsgInfo(lbWgt, "", "");
            setMsgInfo(txtPage, "", "");

            setTxtCarNoInfo("");
            setCbCarNoInfo("");


            ucWeightT1.setWgt(0);
            ucWeightT1.setStable(true);
            ucWeightT1.setExceed(true);
            setPicQRed(false);
            setPicHRed(false);
            setPreTrackInfo(new PreTrackScale());
            setHistWgt(null, null);

            setReadOnlyInfo(txtPREDICTION_NO, "true", "0");

            setListBoxInfo(lb1);
            setListBoxInfo(lb2);
            setMsgInfo(txtMsgInfo, "", "");




            DataTable dtYb = dtPreTrackScale.Clone();
            setGridInfo(ultraGridYb, dtYb, this.dtPreTrackScale);

            DataTable dtSj = dataTable1.Clone();
            setGridInfo(ultraGridSj, dtSj, this.dataTable1);

            DataTable dtQxp = dtTare.Clone();
            setGridInfo(ultraGridTare, dtQxp, this.dtTare);

            DataTable dtJl = dtCalibration.Clone();
            setGridInfo(ultraGridJl, dtJl, this.dtCalibration);

        }
        #endregion



        #region button按钮事件
        bool flagStart = true;
        /// <summary>
        /// 自动派位
        /// </summary>
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (btnStart.Text == "自动派位")
            {
                if (PbCache.sportInfo != null)
                {
                    btnStart.BackColor = Color.Red;
                    btnStart.Text = "取消接管";
                    timer2.Stop();
                    flagStart = false;
                }
            }
            else
            {
                strIsRemote = "0";
                if (PbCache.sportInfo != null)
                {
                    Clean();
                }

                try
                {
                    bCollectionStart = false;
                    btnStart.BackColor = Color.DodgerBlue;
                    btnStart.Text = "自动派位";
                    timer2.Start();
                    flagStart = true;
                }
                catch { }
            }
        }

        bool bGQ = false;
        private void btnGQ_Click(object sender, EventArgs e)
        {
            if (btnGQ.Text == "挂起")
            {
                btnGQ.Text = "取消挂起";
                btnGQ.BackColor = Color.Red;
                bGQ = true;
                btnStart.Enabled = false;

                btnStart.BackColor = Color.DodgerBlue;
                btnStart.Text = "自动派位";
                timer2.Stop();
                flagStart = false;

                strIsRemote = "0";
                if (PbCache.sportInfo != null)
                {
                    Clean();
                }

                try
                {
                    //让用户处于掉线状态
                    string sql = @"update Meter_Work_Online set last_time=sysdate-1 where user_id='" + appUser.userid + "'";
                    PbModelDbService<string> pb = new PbModelDbService<string>();
                    RESTfulResult<string> rm = pb.executeSqlDataWf(sql);
                }
                catch { }
            }
            else
            {
                bCollectionStart = false;
                btnGQ.Text = "挂起"; //改为非挂起状态
                btnGQ.BackColor = Color.DodgerBlue;
                bGQ = false;
                btnStart.Enabled = true;

                timer2.Start();
                flagStart = true;
            }
        }


        List<string> ls = new List<string>();
        double dAddWgt = 0;
        /// <summary>
        /// 选择器具
        /// </summary>
        private void btnCheck_Click(object sender, EventArgs e)
        {
            double dWgt = 0;
            //if (PbCache.collect.weightStatus == 0 && PbCache.collect.weight > 500)
            {
                frmApplianceCheck fac = new frmApplianceCheck();
                fac.ltAddWeightNo = ls == null ? null : ls;
                if (fac.ShowDialog() == DialogResult.OK)
                {
                    dAddWgt = 0;
                    lbUTENSIL_UTENSIL_NAME.Text = "";
                    lbWgt.Text = "0";
                    lb1.Items.Clear();
                    lb2.Items.Clear();

                    DataTable dt = fac.dtChecked;
                    ls = fac.ltAddWeightNo;
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (lbUTENSIL_UTENSIL_NAME.Text == "")
                            {
                                lbUTENSIL_UTENSIL_NAME.Text = dr["utensilUtensilName"].ToString();
                            }
                            if (lb1.Items.Count < 7)
                            {
                                lb1.Items.Add(dr["utensilNo"].ToString());
                            }
                            else
                            {
                                lb2.Items.Add(dr["utensilNo"].ToString());
                            }

                            dWgt += Convert.ToDouble(dr["utensilWeight"].ToString());
                        }
                        lbWgt.Text = dWgt + "";
                        dAddWgt = dWgt;
                    }
                }

                if (txtGroess.Text.Trim() != "" && txtTare.Text.Trim() != "")
                {
                    txtNet.Text = (Convert.ToInt32(txtGroess.Text.Trim()) - Convert.ToInt32(txtTare.Text.Trim()) - dWgt) + "";
                }
            }
        }

        #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)
            {
                setMsgInfo(txtMsgInfo, "视频连接打开失败：" + ex.Message, "");
                //MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }


        bool bVoice = false;
        /// <summary>
        ///  必须先打开视频，然后再打开语音
        /// </summary>
        private void VoiceOpen()
        {
            try
            {
                if (cameraShotMain.StartTalk())
                {
                    btnOpenVoice.Text = "关闭对讲";
                    bVoice = true;
                }
            }
            catch (Exception ex)
            {
                setMsgInfo(txtMsgInfo, "打开语音失败：" + ex.Message, "");
                //MessageBox.Show("打开语音失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 关闭语音对讲
        /// </summary>
        private void VoiceClose()
        {
            try
            {
                if (cameraShotMain.StopTalk())
                {
                    setMsgInfo(btnOpenVoice, "打开对讲", "");
                    bVoice = false;
                }
            }
            catch (Exception ex)
            {
                setMsgInfo(txtMsgInfo, "打开对讲失败：" + ex.Message, "");
                //MessageBox.Show(ex.Message);
            }

        }

        /// <summary>
        /// 关闭视频
        /// </summary>
        private void IPVideoClose()
        {
            try
            {
                cameraShotMain.Close();
            }
            catch (Exception ex)
            {
                setMsgInfo(txtMsgInfo, "关闭对讲失败：" + ex.Message, "");
                //MessageBox.Show(ex.Message);
            }

        }
        #endregion


        /// <summary>
        /// 对讲
        /// </summary>
        private void btnOpenVoice_Click(object sender, EventArgs e)
        {
            if (panel1.Controls.Count > 0)
            {
                if (btnOpenVoice.Text == "打开对讲")
                {
                    VoiceOpen();
                }
                else
                {
                    VoiceClose();
                }
            }
        }

        /// <summary>
        /// 校秤
        /// </summary>
        private void btnCheckBalance_Click(object sender, EventArgs e)
        {
            //if (PbCache.collect.weightStatus == 0 && PbCache.collect.weight > 500)
            {
                PbCache.isLockFrm = true;
                if (PbCache.collect != null)
                {
                    PbCache.lockWgt = PbCache.collect.weight;

                    frmCalibration fc = new frmCalibration();
                    fc.userId = userId;
                    fc.userName = userName;
                    if (fc.ShowDialog() == DialogResult.OK)
                    {
                        txtMsgInfo.Text = "校秤完成";
                        PbCache.isLockFrm = false;
                        //Clean();
                    }
                    else
                    {
                        PbCache.isLockFrm = false;
                    }
                }
            }
        }

        /// <summary>
        /// 期限皮
        /// </summary>
        private void btnTareWgt_Click(object sender, EventArgs e)
        {
            //if (PbCache.collect.weightStatus == 0 && PbCache.collect.weight > 500)
            {
                if (string.IsNullOrEmpty(strCbCarNo + strTxtCarNo))
                {
                    MessageBox.Show("请先输入一个车号");
                    return;
                }

                PbCache.lockWgt = PbCache.collect.weight;
                //是否可留期限皮
                if (!termTareCar.ValidMethod(PbCache.collect.carno))
                {
                    if (PbCache.ResultMessage.Contains("无法留期限皮"))
                    {
                        DialogResult drs = MessageBox.Show(PbCache.ResultMessage.Replace("无法留期限皮", "") + " 确认留期限皮吗？", "提示", MessageBoxButtons.OKCancel);
                        if (drs != DialogResult.OK)
                            return;
                    }
                    else
                    {
                        txtMsgInfo.Text = PbCache.ResultMessage;
                        //MessageBox.Show(PbCache.ResultMessage);
                        return;
                    }
                }


                if (termTareCar.ValidMethod(PbCache.collect.carno))
                {
                    DialogResult dr = MessageBox.Show("确认留期限皮吗？", "提示", MessageBoxButtons.OKCancel);
                    if (dr != DialogResult.OK)
                        return;
                }
                txtMsgInfo.Text = "称重保存中，请稍等......";

                PbCache.isLockFrm = true;
                PbCache.lockCarNo = strCbCarNo + strTxtCarNo;


                MeterBaseTermTareData mbttd = new MeterBaseTermTareData();
                mbttd.baseSpotNo = PbCache.sportInfo.baseSpotNo;
                mbttd.baseSpotName = PbCache.sportInfo.baseSpotName;
                mbttd.carNo = PbCache.collect.carno;
                mbttd.meterWeight = PbCache.lockWgt;
                mbttd.valueFlag = "0";
                mbttd.createTime = DateTime.Now;
                mbttd.createManNo = PbCache.sportInfo.baseSpotNo;
                mbttd.createManName = PbCache.sportInfo.baseSpotName;
                mbttd.meterTime = mbttd.createTime.Value;
                mbttd.startTime = mbttd.createTime.Value;

                //操作日志
                MeterMonitorNote monitorNote = new MeterMonitorNote();
                monitorNote.baseSpotNo = mbttd.baseSpotNo;
                monitorNote.baseSpotName = mbttd.baseSpotName;
                monitorNote.operationContent = string.Format("保存期限皮重");
                monitorNote.operationTime = mbttd.createTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                monitorNote.carNo = mbttd.carNo;
                monitorNote.meterNoteSource = "4";
                monitorNote.meterManNo = userId;
                monitorNote.meterManName = userName;

                //期限皮重数据保存
                RESTfulResult<string> RESTfulResult = termTareDate.doSaveWf(mbttd, monitorNote);
                if (RESTfulResult.Succeed)
                {
                    txtMsgInfo.Text = "期限皮重保存成功！";
                    //MessageBox.Show("期限皮重保存成功！");
                    //Clean();
                }
                else
                {
                    txtMsgInfo.Text = "期限皮重保存失败！" + RESTfulResult.ResultMessage;
                    //MessageBox.Show("保存失败：" + RESTfulResult.ResultMessage);
                }
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            //if (PbCache.collect.weightStatus == 0 && PbCache.collect.weight > 500)
            {
                if (string.IsNullOrEmpty(strCbCarNo + strTxtCarNo)) 
                {
                    MessageBox.Show("请先输入一个车号");
                    return;
                }

                PbCache.isLockFrm = true;
                PbCache.lockWgt = PbCache.collect.weight;
                PbCache.lockCarNo = strCbCarNo + strTxtCarNo;
                btnSave.Enabled = false;
                DialogResult dr = MessageBox.Show("是否确认保存当前计量数据？", "提示", MessageBoxButtons.OKCancel);

                //PbCache.addWgt = lbWgt.Text.Trim() == "" ? 0 : Convert.ToDouble(lbWgt.Text.Trim());
                PbCache.addWgt = Convert.ToDouble(string.IsNullOrEmpty(lbWgt.Text) ? 0 : lbWgt.Value);
                if (dr == DialogResult.OK)
                {
                    txtMsgInfo.Text = "称重保存中，请稍等......";

                    btnSave.Enabled = false;
                    try
                    {
                        bool flag = false;
                        string strMsg = "";

                        //没有业务编号或者业务编号不是非内倒业务则认为是内倒
                        if (strType == "0")
                        {
                            rtInfo ri = null;
                            //获取稳定的重量，车号，计量信息等，然后进行计量业务操作
                            if (preTack != null)
                            {
                                ri = inner.MeterMethod(new InnerMeterInfo
                                {
                                    carNo = cbCarNo.Text.Trim() + txtCarNo.Text.Trim(),
                                    batchNo = "",
                                    forwardingUnitNo = preTack.forwardingUnitNo,
                                    forwardingUnitName = preTack.forwardingUnitName,
                                    matterNo = preTack.matterNo,
                                    matterName = preTack.matterName,
                                    receivingUintName = preTack.receivingUintName,
                                    receivingUintNo = preTack.receivingUintNo,
                                    meterTypeNo = "001006003",
                                    meterTypeName = PbCache.businessType.Where(s => s.baseCode == "001006003").FirstOrDefault().baseName,
                                    predictionNo = ""
                                }, appUser);
                            }
                            else
                            {
                                ri = inner.MeterMethod(new InnerMeterInfo
                                {
                                    carNo = cbCarNo.Text.Trim() + txtCarNo.Text.Trim(),
                                    batchNo = "",
                                    forwardingUnitNo = "",
                                    forwardingUnitName = "",
                                    matterNo = "",
                                    matterName = "",
                                    receivingUintName = "",
                                    receivingUintNo = "",
                                    meterTypeNo = "001006003",
                                    meterTypeName = PbCache.businessType.Where(s => s.baseCode == "001006003").FirstOrDefault().baseName,
                                    predictionNo = ""
                                }, appUser);
                            }
                            flag = ri.result;
                            strMsg = PbCache.ResultMessage;
                        }
                        else if (strType == "1")//存在业务编号且是非内倒计量业务 
                        {
                            //将卡控条件设置为0，放过所有卡控
                            PbCache.isNotValid = true;

                            flag = false;
                            if (scene.WeightMeter(preTack, appUser, out strMsg))  //meterTypeNo  "001006001","001006002"
                            {
                                flag = true;
                            }
                        }
                        else
                        {
                            flag = false;
                            PbCache.ResultMessage = "请输入正确的业务编号之后按回车";
                        }


                        if (flag)
                        {
                            #region 截取图片信息
                            try
                            {
                                //*
                                //截取屏幕信息
                                Point screenPoint = this.PointToScreen(new Point());
                                Rectangle rect = new Rectangle(screenPoint, this.Size);
                                Image img = new Bitmap(rect.Width, rect.Height);
                                Graphics g = Graphics.FromImage(img);
                                g.CopyFromScreen(rect.X - 1, rect.Y - 1, 0, 0, rect.Size);//"D://file/1.jpg"
                                img.Save(string.Format("{0}imgShort\\tempImg\\{1}_{2}_{3}.jpg",
                                    AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                                    PbCache.sportInfo.baseSpotNo,
                                    "C" + PbCache.actualFirstNo,
                                    (PbCache.videoChild.Count + 1)), System.Drawing.Imaging.ImageFormat.Jpeg);

                                //*
                                //最后进行截图操作
                                CameraShotCls cameraShot = new CameraShotCls();
                                cameraShot.CapMethod(PbCache.actualFirstNo);
                                //*/

                            }
                            catch (Exception ex)
                            {
                                l.WriteLog(5, PbCache.lockCarNo + "截图失败");
                            }
                            #endregion

                            #region LED写入
                            PbCache.ledInfo = string.Format("计量完成，车号：{0}，车重：{1}，物资：{2}", PbCache.lockCarNo, PbCache.lockWgt, txtMATTER_NAME.Text.Trim());
                            #endregion
                            //Clean();

                            try
                            {
                                QueryCarNo();
                            }
                            catch { }
                        }
                        else
                        {
                            PbCache.isLockFrm = false;
                            btnSave.Enabled = true;
                        }

                        txtMsgInfo.Text = PbCache.ResultMessage;
                        if (!string.IsNullOrEmpty(PbCache.ResultMessage))
                        {
                            txtMsgInfo.Text = PbCache.ResultMessage;
                            //MessageBox.Show(PbCache.ResultMessage);
                        }
                    }
                    catch (Exception ex)
                    {
                        btnSave.Enabled = true;
                        PbCache.isLockFrm = false;

                        txtMsgInfo.Text = "保存失败：" + ex.Message.Trim();
                        l.WriteLog(5, "保存失败：" + ex.Message.Trim());
                        //MessageBox.Show("保存失败：" + ex.Message.Trim());
                    }

                }
                else
                {
                    txtMsgInfo.Text = PbCache.ResultMessage;
                    btnSave.Enabled = true;
                    PbCache.isLockFrm = false;
                }
            }
        }

        /// <summary>
        /// 0为内倒  1为非内倒
        /// </summary>
        string strType = "0";

        /// <summary>
        /// 回车时触发查询
        /// </summary>
        private void txtPREDICTION_NO_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                QueryInnerInfo();
            }
        }

        private void QueryInnerInfo()
        {
            txtFORWARDING_UNIT_NAME.Text = "";
            txtMATTER_NAME.Text = "";
            txtRECEIVING_UINT_NAME.Text = "";

            preTack = null;
            string strM = txtPREDICTION_NO.Text.Trim();
            PbCache.strCode = strM;
            setPreTrackInfo(new PreTrackScale());
            if (strM.Length == 9)
            {
                strType = "0";
                //内部物料，需确认车辆是否为内倒车辆
                string sql = @"select t1.load_point_no as id, t1.load_point_name text, t1.meter_code text2
                                  from meter_base_load_point t1
                                 where t1.meter_code = '" + strM.Substring(3, 3) + @"'
                                   and t1.valid_Flag = '1'
                                union all
                                select t1.load_point_no as id, t1.load_point_name text, t1.meter_code text2
                                  from meter_base_load_point t1
                                 where t1.meter_code = '" + strM.Substring(6, 3) + @"'
                                   and t1.valid_Flag = '1'
                                union all
                                select t2.matter_no as id, t2.matter_name text, t2.meter_code text2
                                  from meter_base_matter_info t2
                                 where t2.meter_code = '" + strM.Substring(0, 3) + @"'
                                   and t2.valid_Flag = '1'";

                PbModelDbService<List<PbModelDb>> pb = new PbModelDbService<List<PbModelDb>>();
                RESTfulResult<List<PbModelDb>> rm = pb.executeSqlDataWf(sql);
                if (rm.Succeed && rm.Data.Count == 3)
                {
                    txtMsgInfo.Text = "";

                    txtFORWARDING_UNIT_NAME.Text = rm.Data[0].text;
                    txtMATTER_NAME.Text = rm.Data[2].text;
                    txtRECEIVING_UINT_NAME.Text = rm.Data[1].text;
                    preTack = new PreTrackScale
                    {
                        predictionNo = strM,
                        forwardingUnitNo = rm.Data[0].id,
                        forwardingUnitName = rm.Data[0].text,
                        matterNo = rm.Data[2].id,
                        matterName = rm.Data[2].text,
                        receivingUintNo = rm.Data[1].id,
                        receivingUintName = rm.Data[1].text,
                        meterTypeNo = "001006003",
                        meterTypeName = ""
                    };

                    setPreTrackInfo(preTack);
                    seValidWhp();


                    txtMETER_TYPE.Text = "内倒";

                    #region 是否可用期限皮
                    PbCache.isTermTare = false;
                    sql = @"select matter_no id, 
                                   allowed_tare_weight text, 
                                   allowed_add_weight text2
                              from meter_base_matter_info
                             where valid_Flag = '1' and matter_no = '" + rm.Data[2].id + "'";

                    RESTfulResult<List<PbModelDb>> rmT = pb.executeSqlDataWf(sql);
                    if (rmT.Succeed)
                    {
                        if (rmT.Data != null && rmT.Data.Count > 0 && rmT.Data[0].text == "1")
                        {
                            PbCache.isTermTare = true;
                        }
                    }
                    #endregion
                }
                else
                {
                    txtMsgInfo.Text = "不存在该业务编码，请确定输入的信息是否有错";
                    //MessageBox.Show("不存在该业务编码，请确定输入的信息是否有错");
                }
            }
            else if (strM.Length > 0)
            {
                strType = "2";
                RESTfulResult<List<PreTrackScale>> rm = service.doQueryWf(new PreTrackScale { predictionNo = strM });
                if (rm.Succeed)
                {
                    if (rm.Data == null || rm.Data.Count == 0)
                    {
                        txtMsgInfo.Text = "未找到预报信息，请确定输入的信息是否有错";
                    }
                    else
                    {
                        if (rm.Data[0].valueFlag != "1" && rm.Data[0].valueFlag != "4") //1未使用，4正使用
                        {
                            txtMsgInfo.Text = "请确保当前预报已配车且未使用或正使用";
                        }
                        else
                        {
                            preTack = rm.Data[0];
                            setPreTrackInfo(preTack);
                            seValidWhp();
                            strType = "1";
                            btnSave.Visible = validPredictionNo(preTack.predictionNo);
                        }
                    }
                }
            }
            txtPREDICTION_NO.Text = strM;
        }
        #endregion

        #region 数据设置及清空
        /// <summary>
        /// 清空或设置预报信息
        /// </summary>
        private void setPreTrackInfo(PreTrackScale pts)
        {
            setMsgInfo(txtPREDICTION_NO, pts.predictionNo == null ? "" : pts.predictionNo, "");
            setMsgInfo(txtBATCH_NO, pts.batchNo == null ? "" : pts.batchNo, "");
            setMsgInfo(txtBATCH_NO, pts.batchNo == null ? "" : pts.batchNo, "");
            setMsgInfo(txtMATTER_NAME, pts.matterName == null ? "" : pts.matterName, "");
            setMsgInfo(txtMETER_TYPE, pts.meterTypeName == null ? "" : pts.meterTypeName, "");
            setMsgInfo(txtFORWARDING_UNIT_NAME, pts.forwardingUnitName == null ? "" : pts.forwardingUnitName, "");
            setMsgInfo(txtRECEIVING_UINT_NAME, pts.receivingUintName == null ? "" : pts.receivingUintName, "");
            setMsgInfo(txtLOAD_POINT_NAME, pts.loadPointName == null ? "" : pts.loadPointName, "");
            setMsgInfo(txtCARRIER_UNIT_NAME, pts.carrierUnitName == null ? "" : pts.carrierUnitName, "");
            setMsgInfo(txtRemark, pts.memo == null ? "" : pts.memo, "");
            setMsgInfo(txtSHIPMENT_NET_WEIGHT, pts.shipmentNetWeight == null ? "" : pts.shipmentNetWeight.Value + "", "");
            setMsgInfo(txtSHIPMENT_GROSS_WEIGHT, pts.shipmentGrossWeight == null ? "" : pts.shipmentGrossWeight.Value + "", "");

            setMsgInfo(chkSample, string.IsNullOrEmpty(pts.sampleNo) ? "false" : "true", "3");
            setMsgInfo(chkChemical, "false", "3");
        }

        private void setHistWgt(double? dHisTareWgt, int? iCount)
        {
            setMsgInfo(txtHisTare, dHisTareWgt == null ? "" : dHisTareWgt.Value + "", "");
            setMsgInfo(txtCount, iCount == null ? "" : iCount.Value + "", "");
        }


        string strCbCarNo = "";
        public void setCbCarNoInfo(string ResultMessage)
        {
            setCbCarNo(ResultMessage);
        }

        private void setCbCarNo(string ResultMessage)
        {
            if (cbCarNo.InvokeRequired)
            {
                Action<string> action = new Action<string>(setCbCarNoInfo);
                Invoke(action, new object[] { ResultMessage });
            }
            else
            {
                if (string.IsNullOrEmpty(ResultMessage))
                {
                    cbCarNo.SelectedIndex = -1;
                }
                cbCarNo.Text = ResultMessage;
                strCbCarNo = cbCarNo.Text.Trim();
            }
        }

        string strTxtCarNo = "";
        public void setTxtCarNoInfo(string ResultMessage)
        {
            setTxtCarNo(ResultMessage);
        }

        private void setTxtCarNo(string ResultMessage)
        {
            if (txtCarNo.InvokeRequired)
            {
                Action<string> action = new Action<string>(setTxtCarNoInfo);
                Invoke(action, new object[] { ResultMessage });
            }
            else
            {
                txtCarNo.Text = ResultMessage;
                strTxtCarNo = txtCarNo.Text.Trim();
            }
        }

        public void setPicQRed(bool bRed)
        {
            setQRed(bRed);
        }

        private void setQRed(bool bRed)
        {
            if (picQRed.InvokeRequired)
            {
                Action<bool> action = new Action<bool>(setPicQRed);
                Invoke(action, new object[] { bRed });
            }
            else
            {
                if (bRed)
                {
                    picQRed.Load(PbCache.path + "\\image\\icon\\red.gif");
                }
                else
                {
                    picQRed.Load(PbCache.path + "\\image\\icon\\green.gif");
                }
            }
        }

        public void setPicHRed(bool bRed)
        {
            setHRed(bRed);
        }

        private void setHRed(bool bRed)
        {
            if (picHRed.InvokeRequired)
            {
                Action<bool> action = new Action<bool>(setPicHRed);
                Invoke(action, new object[] { bRed });
            }
            else
            {
                if (bRed)
                {
                    picHRed.Load(PbCache.path + "\\image\\icon\\red.gif");
                }
                else
                {
                    picHRed.Load(PbCache.path + "\\image\\icon\\green.gif");
                }
            }
        }
        #endregion

        int iCnt = 0, iTimes = 0;

        private void timer1_Tick(object sender, EventArgs e)
        {
            iCnt++;
            if (iCnt % 3 == 0)
            {
                //未挂起则3秒写入一次在线状态
                if (!bGQ)
                {
                    RESTfulResult<string> rm = onlineService.doSaveWf(new MeterWorkOnline { userId = userId });
                }
                iCnt = 0;
            }
            iTimes++;
            if (iTimes > 600 && !bCollectionStart)
            {
                //没有远程接管的情况下十分钟载入一次基础数据
                iTimes = 0;
                bd.setBaseDb();
            }
        }

        private void cbCarNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PbCache.collect != null && PbCache.collect.weight > 0)
            {
                if (cbCarNo.SelectedIndex > -1)
                {
                    strCbCarNo = cbCarNo.Text.Trim();
                    QueryCarNo();
                    flagCarNo = true;
                }
            }
        }

        bool flagCarNo = false, isFocus = false;

        private void txtCarNo_KeyDown(object sender, EventArgs e)
        {
            /*
            if (PbCache.collect != null && PbCache.collect.weight > 0)
            {
                strTxtCarNo = txtCarNo.Text.Trim();
                QueryCarNo();
                flagCarNo = true;
            }
            //*/
        }

        private void getFocusInfo(Control control)
        {
            if (txtCarNo.InvokeRequired)
            {
                Action<Control> action = new Action<Control>(getFocusInfo);
                Invoke(action, new object[] { control });
            }
            else
            {
                isFocus = control.Focused;
            }
        }



        private void QueryCarNo()
        {
            if (PbCache.sportInfo != null)
            {
                if (strTxtCarNo != "" && strCbCarNo != "") //&& PbCache.collect.weightStatus == 0)
                {
                    PbCache.collect.carno = strCbCarNo + strTxtCarNo;
                    first = null;

                    //setHistWgt(null, null);
                    //METER_BASE_HIS_TARE_DATA
                    RESTfulResult<List<MeterBaseHisTareData>> rmH = meterBaseHisTareData.doQueryWf(new MeterBaseHisTareData { carNo = PbCache.collect.carno, valueFlag = "0" });
                    if (rmH.Succeed && rmH.Data != null && rmH.Data.Count > 0)
                    {
                        string HisTareWgt = PbCache.tareCount != null ? (PbCache.tareCount.contrastTypeNo == "001012001" ? rmH.Data[0].upWeight.Value : rmH.Data[0].avgWeight.Value) + "" : rmH.Data[0].avgWeight.Value + "";
                        setMsgInfo(txtHisTare, HisTareWgt, "");
                        setMsgInfo(txtCount, rmH.Data[0].meterNum + "", "");
                    }

                    //通过车号查询计量预报
                    RESTfulResult<List<PreTrackScale>> rmx = service.doQueryTenWf(new PreTrackScale { carNo = PbCache.collect.carno });
                    dtPreTrackScale.Clear();
                    DataTable dt = dtPreTrackScale.Clone();
                    if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                    {
                        dt = rmx.Data.ListToDataTable<PreTrackScale>();
                    }
                    ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtPreTrackScale, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridYb);

                    //计量实绩
                    CommonPage<MeterWorkCarActual> cpc = new CommonPage<MeterWorkCarActual>();
                    MeterWorkCarActual mwca = new MeterWorkCarActual();
                    mwca.carNo = PbCache.collect.carno;
                    cpc.param = mwca;
                    cpc.pageNum = 1;
                    cpc.pageSize = 10;

                    RESTfulResult<DataTable> rm = mwas.doQueryWf(cpc);
                    if (rm.Succeed)
                    {
                        //WriteLog("二次计量数据查询失败！" + rm.ResultMessage);
                        dataTable1.Clear();
                        DataTable dts = dataTable1.Clone();
                        if (rm.Data != null && rm.Data.Rows.Count > 0)
                        {
                            dts = rm.Data;
                        }

                        ClsControlPack.CopyDataToDatatable(ref dts, ref this.dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridSj);
                    }

                    //期限皮重
                    RESTfulResult<List<MeterBaseTermTareData>> rmTerm = termTareDate.doQueryWf(new MeterBaseTermTareData { carNo = PbCache.collect.carno, valueFlag = "0" });
                    dtTare.Clear();
                    DataTable dtTerm = dtTare.Clone();
                    if (rmTerm.Succeed && rmTerm.Data != null && rmTerm.Data.Count > 0)
                    {
                        dtTerm = rmTerm.Data.ListToDataTable<MeterBaseTermTareData>();
                    }
                    ClsControlPack.CopyDataToDatatable(ref dtTerm, ref this.dtTare, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridTare);

                    //校秤记录
                    RESTfulResult<List<MeterWorkCalibrationMain>> rmMain = mainService.doQueryWf(new MeterWorkCalibrationMain { baseSpotNo = PbCache.sportInfo.baseSpotNo });
                    dtCalibration.Clear();
                    DataTable dtMain = dtCalibration.Clone();
                    if (rmMain.Succeed && rmMain.Data != null && rmMain.Data.Count > 0)
                    {
                        dtMain = rmMain.Data.ListToDataTable<MeterWorkCalibrationMain>();
                    }
                    ClsControlPack.CopyDataToDatatable(ref dtMain, ref this.dtCalibration, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridJl);

                    //剩余纸张数 meter_work_monitor
                    RESTfulResult<List<MeterWorkMonitor>> rmMonitor = monitorService.doQueryOneWf(new MeterWorkMonitor { validFlag = "1", pointNo = PbCache.sportInfo.baseSpotNo });
                    if (rmMonitor.Succeed)
                    {
                        if (rmMonitor.Data != null && rmMonitor.Data.Count > 0)
                        {
                            //txtPage.Text = rmMonitor.Data[0].printNum == null ? "0" : (rmMonitor.Data[0].printNum.Value + "");
                            setMsgInfo(txtPage, rmMonitor.Data[0].printNum == null ? "0" : (rmMonitor.Data[0].printNum.Value + ""), "");
                        }
                    }

                    //是否存在一次计量数据，存在则毛皮净写入界面
                    MeterWorkCarActualFirstService workCarActualFirstService = new MeterWorkCarActualFirstService();
                    RESTfulResult<List<MeterWorkCarActualFirst>> RESTfulResult = workCarActualFirstService.doQueryWf(new MeterWorkCarActualFirst { carNo = PbCache.collect.carno, valueFlag = "1" });
                    if (RESTfulResult.Succeed)
                    {
                        if (RESTfulResult.Data != null && RESTfulResult.Data.Count > 0)
                        {
                            first = RESTfulResult.Data[0];
                            PbCache.strCode = first.predictionNo;
                            //setMsgInfo(lbWgt, (first.addWeight == null ? 0 : first.addWeight.Value) + "", ""); //一次附加重量作为附加重量显示

                            if (first.meterTypeNo == "001006003")
                            {
                                strType = "0"; //如果是内倒计量
                                //setMsgInfo(txtPREDICTION_NO, first.predictionNo, "");
                                setMsgInfo(txtMATTER_NAME, first.matterName, "");
                                setMsgInfo(txtMETER_TYPE, first.meterTypeName, "");
                                setMsgInfo(txtFORWARDING_UNIT_NAME, first.forwardingUnitName, "");
                                setMsgInfo(txtRECEIVING_UINT_NAME, first.receivingUintName, "");
                            }
                            else
                            {
                                setAddWgt(first.predictionNo); //非内倒才有这款逻辑

                                strType = "1"; //非内倒计量，此时计量预报中存在编号与一次一致的情况，则认为是非一车联运，或者一车联运互锁的方式或者最后一车一车联运预报，此时可将一次的信息填充到界面
                                if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                                {
                                    PreTrackScale ptsQ = rmx.Data.Where(s => s.predictionNo == RESTfulResult.Data[0].predictionNo).FirstOrDefault();
                                    if (ptsQ != null && ptsQ.predictionNo != "")
                                    {
                                        setMsgInfo(txtPREDICTION_NO, ptsQ.predictionNo, "");
                                        setMsgInfo(txtBATCH_NO, ptsQ.batchNo, "");
                                        setMsgInfo(txtMATTER_NAME, ptsQ.matterName, "");
                                        setMsgInfo(txtMETER_TYPE, ptsQ.meterTypeName, "");
                                        setMsgInfo(txtCount, ptsQ.shipmentNum == null ? "" : ptsQ.shipmentNum.Value + "", "");
                                        setMsgInfo(txtFORWARDING_UNIT_NAME, ptsQ.forwardingUnitName, "");
                                        setMsgInfo(txtRECEIVING_UINT_NAME, ptsQ.receivingUintName, "");
                                        setMsgInfo(txtCARRIER_UNIT_NAME, ptsQ.carrierUnitName, "");
                                        setMsgInfo(txtLOAD_POINT_NAME, ptsQ.loadPointName, "");
                                        setMsgInfo(txtSHIPMENT_GROSS_WEIGHT, ptsQ.shipmentGrossWeight == null ? "" : ptsQ.shipmentGrossWeight.Value + "", "");
                                        setMsgInfo(txtSHIPMENT_NET_WEIGHT, ptsQ.shipmentNetWeight == null ? "" : ptsQ.shipmentNetWeight.Value + "", "");

                                        preTack = ptsQ;
                                    }
                                }
                            }
                        }
                    }

                    seValidWhp();
                }
            }
        }

        /// <summary>
        /// 验证当前物料是否是危化品
        /// </summary>
        private void seValidWhp()
        {
            if (txtCarNo.Text.Trim() != "" && cbCarNo.Text.Trim() != "" && preTack != null && preTack.matterNo != "")
            {
                string strCarNo = cbCarNo.Text.Trim() + txtCarNo.Text.Trim();
                if (PbCache.limit != null && PbCache.limit.Count > 0)
                {
                    List<MeterBaseLimitChemical> mblc = PbCache.limit.Where(s => s.matterNo == preTack.matterNo).ToList();
                    //该物料是危化品
                    if (mblc.Count > 0)
                    {
                        chkChemical.Checked = true;
                    }
                }
            }
        }

        private void ultraGridYb_DoubleClick(object sender, EventArgs e)
        {
            UltraGridRow ugr = ultraGridYb.ActiveRow;
            if (ugr != null)
            {
                DataRow[] dr = dtPreTrackScale.Select("predictionNo='" + ugr.Cells["predictionNo"].Text.Trim() + "'"); //Select(" CAR_NO = '" + strCarNO + "'")
                if (dr != null && dr.Length > 0)
                {
                    preTack = dr[0].CreateItem<PreTrackScale>();
                    setPreTrackInfo(preTack);
                    seValidWhp();
                    strType = "1";

                    lbWgt.Text = string.IsNullOrEmpty(dr[0]["addWeightSum"].ToString().Trim()) ? "" : dr[0]["addWeightSum"].ToString().Trim();
                    setAddWgt(preTack.predictionNo);
                    PbCache.strCode = preTack.predictionNo;

                    btnSave.Visible = validPredictionNo(ugr.Cells["predictionNo"].Text.Trim());
                }
            }
        }

        //
        private void setAddWgt(string predictionNo)
        {
            try
            {
                setMsgInfo(lbUTENSIL_UTENSIL_NAME, "", "");

                ls = new List<string>();
                setListBoxInfo(lb1, "", "1");
                setListBoxInfo(lb2, "", "1");
                dAddWgt = 0;


                RESTfulResult<List<PerAddWeight>> rm = perAddWeight.doQueryWf(new PerAddWeight { predictionNo = predictionNo });
                if (rm.Succeed)
                {
                    if (rm.Data != null && rm.Data.Count > 0)
                    {
                        int i = 0;
                        foreach (PerAddWeight per in rm.Data)
                        {
                            setMsgInfo(lbUTENSIL_UTENSIL_NAME, per.utensilUtensilName, "");
                            ls.Add(per.addWeightNo);
                            i++;
                            if (i < 8)
                            {
                                setListBoxInfo(lb1, per.utensilNo, "2");
                            }
                            else
                            {
                                setListBoxInfo(lb2, per.utensilNo, "2");
                            }
                            dAddWgt += string.IsNullOrEmpty(per.utensilWeight) ? 0 : Convert.ToDouble(per.utensilWeight);
                        }
                    }
                }
                //PbCache.addWgt = dAddWgt;
                setMsgInfo(lbWgt, dAddWgt + "", "");
            }
            catch (Exception ex)
            {
                l.WriteLog(1, ex.Message.Trim());
            }
        }

        public void setListBoxInfo(ListBox control, string ResultMessage, string sType)
        {
            setListBoxMsg(control, ResultMessage, sType);
        }
        private void setListBoxMsg(ListBox control, string ResultMessage, string sType)
        {
            if (control.InvokeRequired)
            {
                Action<ListBox, string, string> action = new Action<ListBox, string, string>(setListBoxInfo);
                Invoke(action, new object[] { control, ResultMessage, sType });
            }
            else
            {
                switch (sType)
                {
                    case "1":
                        control.Items.Clear();
                        ; break;
                    case "2":
                        control.Items.Add(ResultMessage);
                        ; break;
                    case "3":
                        control.Items.Remove(ResultMessage);
                        break;
                    default: break;
                }
            }
        }

        private bool validPredictionNo(string predictionNo)
        {
            bool flag = true;
            txtMsgInfo.Text = "";
            #region 如果存在一次信息，且当前预报编号与一次的不一样
            if (first != null && !string.IsNullOrEmpty(first.predictionNo) && !string.IsNullOrEmpty(predictionNo))
            {
                if (PbCache.strCode != first.predictionNo)
                {
                    if (first.predictionType != "2")//一次计量的计量预报如果不是联运预报，那么当前扫的码必须与前面那个一致
                    {
                        txtMsgInfo.Text = "当前计量预报【" + predictionNo + "】与上次未结净数据预报【" + first.predictionNo + "】不一致，请重新扫码或语音求助!";
                        flag = false;
                    }
                    else //如果一次计量是联运预报，且预报的使用状态为4(正使用)则认为走了互锁式计量，因为非互锁的情况计量一次预报状态会变为2
                    {
                        RESTfulResult<List<PreTrackScale>> rm = service.doQueryWf(new PreTrackScale { predictionNo = first.predictionNo, valueFlag = "4" });
                        if (rm.Succeed)
                        {
                            if (rm.Data != null && rm.Data.Count > 0)
                            {
                                txtMsgInfo.Text = "当前计量预报【" + predictionNo + "】与上次未结净数据预报【" + first.predictionNo + "】不一致，请重新扫码或语音求助!";
                                flag = false;
                            }
                            else //非互锁的情况计量，此时编号应该存在在一次计量中的编号中
                            {
                                string sCode = first.predictionCombination.Split(',').ToList().Where(s => s.CompareTo(predictionNo) == 0).FirstOrDefault();
                                if (string.IsNullOrEmpty(sCode))
                                {
                                    txtMsgInfo.Text = "当前计量预报【" + predictionNo + "】不在上次计量联运预报【" + first.predictionCombination + "】中，请重新扫码或语音求助!";
                                    flag = false;
                                }
                            }
                        }
                        else
                        {
                            l.WriteLog(0, "查询预报编号异常");
                            txtMsgInfo.Text = "获取一次计量时的预报失败，请稍后再试，预报编号【" + first.predictionNo + "】!";
                            flag = false;
                        }
                    }
                }
            }
            #endregion
            return flag;
        }

        private void ultraGridSj_DoubleClick(object sender, EventArgs e)
        {
            UltraGridRow ugr = ultraGridSj.ActiveRow;
            if (ugr != null)
            {
                strType = "0";
                preTack = new PreTrackScale
                {
                    predictionNo = ugr.Cells["predictionNo"].Text.Trim(),
                    forwardingUnitNo = ugr.Cells["forwardingUnitNo"].Text.Trim(),
                    forwardingUnitName = ugr.Cells["forwardingUnitName"].Text.Trim(),
                    matterNo = ugr.Cells["matterNo"].Text.Trim(),
                    matterName = ugr.Cells["matterName"].Text.Trim(),
                    receivingUintNo = ugr.Cells["receivingUintNo"].Text.Trim(),
                    receivingUintName = ugr.Cells["receivingUintName"].Text.Trim()
                };

                setPreTrackInfo(preTack);
                seValidWhp();
            }
        }

        string strIsRemote = "0";
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (!bCollectionStart)
            {
                RESTfulResult<List<MeterWorkMonitor>> rm = monitorService.doQueryOneWf(new MeterWorkMonitor { userNo = userId });
                if (rm.Succeed)
                {
                    if (rm.Data != null && rm.Data.Count > 0)
                    {
                        strIsRemote = rm.Data[0].isRemote;

                        #region 将按钮设置为接管的状态
                        btnStart.BackColor = Color.Red;
                        btnStart.Text = "取消接管";
                        timer2.Stop();
                        flagStart = false;
                        #endregion


                        lbPointName.Text = "";
                        lbMeterMan.Text = "";

                        txtPREDICTION_NO.ReadOnly = false;
                        cbCarNo.Enabled = true;
                        txtCarNo.ReadOnly = false;

                        DataTable dt = dtJGPointInfo.Clone();
                        DataRow dr = dt.NewRow();
                        PbCache.sportInfo = PbCache.sportInfos.Where(s => s.baseSpotNo == rm.Data[0].pointNo).FirstOrDefault();

                        dr["baseSpotNo"] = rm.Data[0].pointNo;
                        dr["baseSpotName"] = rm.Data[0].pointName;
                        dt.Rows.Add(dr);

                        ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtJGPointInfo, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridPW);
                        PbCache.collect_no = rm.Data[0].collectionCode;
                        bd.getSpot();

                        //=====如果此时的远程接管状态是2，则说明是监控端点击的远程接管，此时将自动派位改为挂起状态===========
                        /*
                        if (rm.Data[0].isTakeOver == "2")
                        {
                            btnStart.BackColor = Color.Red;
                            btnStart.Text = "挂起";
                            timer2.Enabled = false;
                            flagStart = false;
                        }
                        //*/
                        //===================================================================================================
                        collection.Start(rm.Data[0].pointNo, rm.Data[0].pointName);

                        GetIPVideo(PbCache.videoInfo);
                        setPicBoxSet();
                        bCollectionStart = true;

                        lbPointName.Text = rm.Data[0].pointName;
                        lbMeterMan.Text = userName;
                        //放开按钮
                        /*
                        btnOpenVoice.Enabled = true;
                        btnCheckBalance.Enabled = true;
                        btnTareWgt.Enabled = true;
                        btnSave.Enabled = true;
                        //*/
                    }
                }
            }
            else
            {
                /*
                if (btnOpenVoice.Enabled) 
                {
                    //禁用按钮
                    btnOpenVoice.Enabled = false;
                    btnCheckBalance.Enabled = false;
                    btnTareWgt.Enabled = false;
                    btnSave.Enabled = false;
                }
                //*/
            }
        }

        List<PictureBox> ltPicBoxs = new List<PictureBox>();
        private void setPicBoxSet()
        {
            if (PbCache.videoChild != null && PbCache.videoChild.Count > 0)
            {
                int i = 0;
                foreach (MeterBaseVideoChild child in PbCache.videoChild.OrderByDescending(s => s.p_ip))
                {
                    i++;

                    if (i < 2) //只开启2个视频 1-3通道 左右上  6通道室内
                    {
                        PictureBox pb = new PictureBox();
                        pb.Name = "pb" + i;
                        pb.Dock = DockStyle.Top;
                        pb.Height = 245;
                        pb.DoubleClick += new EventHandler(PictureBoxDoubleClick);
                        pb.BorderStyle = BorderStyle.FixedSingle;
                        panel1.Controls.Add(pb);
                        cameraShotMain.RealPlay(pb, i);
                    }
                }
            }
        }


        private void lbWgt_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                dAddWgt = Convert.ToDouble(string.IsNullOrEmpty(lbWgt.Text) ? 0 : lbWgt.Value);
            }
            catch
            {
                dAddWgt = 0;
            }
        }

        bool bTest = true;
        int iTestWgt = 0;
        private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                iTestWgt = (int)numericUpDown1.Value;
            }
        }

        private void txtCarNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (PbCache.collect != null && PbCache.collect.weight > 0)
                {
                    strTxtCarNo = txtCarNo.Text.Trim();
                    QueryCarNo();
                    flagCarNo = true;
                }
            }
        }

        private void btnInnerQuery_Click(object sender, EventArgs e)
        {
            frmMatCompanyInfo frmM = new frmMatCompanyInfo();
            if (frmM.ShowDialog() == DialogResult.OK)
            {
                txtPREDICTION_NO.Text = frmM.PreNo;
                QueryInnerInfo();
            }
        }

        int iPic = 0;

        /// <summary>
        /// 不显示大图
        /// </summary>
        private void pictureShow_DoubleClick(object sender, EventArgs e)
        {
            plImgShow.Visible = false;
            cameraShotMain.StopRealPlay(iPic);
            iPic = 0;
        }

        /// <summary>
        /// 放大图像
        /// </summary>
        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);
        }
    
    }
}
