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

namespace RailMeterSystem
{
    public partial class frmMotoriaMaincs : Form
    {
        #region
        PreRailwayScaleService PreService = new PreRailwayScaleService();//查询预报信息
        MeterWorkRailwayActFirstService actFirstService = new MeterWorkRailwayActFirstService(); //
        MeterBaseRailwayWeightService baseRailwayWgt = new MeterBaseRailwayWeightService(); 
        MeterWorkRailwayActualService actualService = new MeterWorkRailwayActualService();
        #endregion

        public frmMotoriaMaincs()
        {
            InitializeComponent();
        }

        List<MeterBaseVideoinfo> ltMbV = new List<MeterBaseVideoinfo>();

        CoreAppUser appUser = null;
        private void frmMotoriaMaincs_Load(object sender, EventArgs e)
        {
            appUser = ((ST_MainForm)(this.MdiParent)).AppUser;

            cbTimeType.SelectedIndex = 1;

            ValueList vlist1 = new ValueList();
            vlist1.ValueListItems.Add("1", "未使用");
            vlist1.ValueListItems.Add("2", "已使用");
            ultraGridRecive.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vlist1;

            ValueList vlist2 = new ValueList();
            vlist2.ValueListItems.Add("1", "正常结净");
            vlist2.ValueListItems.Add("2", "匹配结净");
            ultraGridNet.DisplayLayout.Bands[0].Columns["netMode"].ValueList = vlist2;

            ValueList vlist3 = new ValueList();
            vlist3.ValueListItems.Add("0", "待审核");
            vlist3.ValueListItems.Add("1", "已审核");
            vlist3.ValueListItems.Add("2", "已上传");
            ultraGridNet.DisplayLayout.Bands[0].Columns["uploadFlag"].ValueList = vlist3;

            dtStartTime.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            dtEndTime.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");

            #region 计量点数据
            DataTable dtPw = dtJGPointInfo.Clone();
            MeterBaseSpotInfoService service = new MeterBaseSpotInfoService();
            RESTfulResult<List<MeterBaseSpotInfo>> rms = service.doQueryWf(new MeterBaseSpotInfo { validFlag = "1", spotTypeNo = "001002002" });
            if (rms.Succeed && rms.Data != null && rms.Data.Count > 0)
            {
                foreach (MeterBaseSpotInfo mbs in rms.Data) 
                {
                    if (mbs.baseSpotName.Contains("动")) 
                    {
                        DataRow dr = dtPw.NewRow();
                        dr["baseSpotNo"] = mbs.baseSpotNo;
                        dr["baseSpotName"] = mbs.baseSpotName;
                        dtPw.Rows.Add(dr);
                    }
                }
                ClsControlPack.CopyDataToDatatable(ref dtPw, ref this.dtJGPointInfo, true);
                ClsControlPack.RefreshAndAutoSize(ultraGridPW);


                #region 获取视频信息
                try 
                {
                    MeterBaseVideoinfoService mbvs = new MeterBaseVideoinfoService();
                    RESTfulResult<List<MeterBaseVideoinfo>> rm = mbvs.doQueryWf(new MeterBaseVideoinfo { });
                    if (rm.Succeed && rm.Data != null && rm.Data.Count > 0)
                    {
                        ltMbV = rm.Data;
                    }
                } catch { }
                #endregion
            }
            else
            {
                MessageBox.Show("基础数据载入失败，请关闭界面并稍后打开，或联系管理员");
                return;
            }
            #endregion    

            //ClsControlPack.SetUltraGridRowFilter(ref ultraGridNet, true);
        }

        #region 按钮事件
        private void GridPw() 
        {
            UltraGridRow ugr = ultraGridPW.ActiveRow;
            if (ugr != null)
            {
                foreach (UltraGridRow ur in ultraGridPW.Rows)
                {
                    ur.Appearance.BackColor = Color.White;
                }

                if (strBaseSpotNo != ugr.Cells["baseSpotName"].Text.Trim())
                {
                    if (strBaseSpotNo != "")
                    {
                        //先关闭视频，再打开视频
                        IPVideoClose();
                    }
                    MeterBaseVideoinfo mbv = ltMbV.Where(s => s.pointid == ugr.Cells["baseSpotNo"].Text.Trim()).FirstOrDefault();
                    GetIPVideo(mbv);
                }

                strBaseSpotNo = ugr.Cells["baseSpotNo"].Text.Trim();
                ugr.Appearance.BackColor = Color.Red;


            }
        }
        private void btnQuery() 
        {
            GridPw();

            dtRecevice.Clear();
            DataTable dtV = dtRecevice.Clone();
            ClsControlPack.CopyDataToDatatable(ref dtV, ref this.dtRecevice, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridRecive);

            QueryVoice();
            QueryNetDb();
            QueryFirstDb();
            QueryPre();
        }

        private void btnSubmit() 
        {
            ultraGridRecive.UpdateData();

            UltraGridRow ugrPre = ultraGridPre.ActiveRow;
            UltraGridRow ugrRec = ultraGridRecive.ActiveRow;
            UltraGridRow ugrPw = ultraGridPW.ActiveRow;
            UltraGridRow ugrV = ultraGridVoice.ActiveRow;

            UltraGridRow ugrFirs = ultraGridFirst.ActiveRow;

            PreRailwayScale prs = new PreRailwayScale();

            if (ugrPre != null && ugrPre.Appearance.BackColor == Color.Red)
            {
                DataRow[] drPre = dtRailwayScale.Select("predictionNo='" + ugrPre.Cells["predictionNo"].Text.Trim() + "'");
                DataTable dtPre = dtRailwayScale.Clone();
                dtPre.Rows.Add(drPre[0].ItemArray);
                List<PreRailwayScale> lp = dtPre.TableToDataList<PreRailwayScale>();
                prs = lp[0];
                prs.noticeNo = ugrV.Cells["actualNo"].Text.Trim();
            }
            else
            {
                MessageBox.Show("请选择预报信息");
                return;
            }

            MeterBaseRailwayWeight mbaseWeight = new MeterBaseRailwayWeight();
            if (ugrRec == null)
            {
                MessageBox.Show("请选择期限皮重信息");
                return;
            }
            else
            {
                DataRow[] drPre = dtRailwayActFirst.Select("railwayPk='" + ugrFirs.Cells["railwayPk"].Text.Trim() + "'");
                DataTable dtPre = dtRailwayActFirst.Clone();
                dtPre.Rows.Add(drPre[0].ItemArray);
                List<MeterBaseRailwayWeight> lp = dtPre.TableToDataList<MeterBaseRailwayWeight>();
                lp[0].railwayWeight = lp[0].railwayWeight == null ? 0 : lp[0].railwayWeight.Value * 1000;
                mbaseWeight = lp[0];
            }
            

            List<MeterWorkRailwayActFirst> lmwrf = new List<MeterWorkRailwayActFirst>();
            foreach (UltraGridRow ugr in ultraGridRecive.Rows) 
            {
                if (ugr.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE" && ugr.Cells["valueFlag"].Value.ToString() == "1")
                {
                    MeterWorkRailwayActFirst actFirst = new MeterWorkRailwayActFirst();
                    EntityBase<PreRailwayScale> entityBase = new EntityBase<PreRailwayScale>();
                    actFirst = entityBase.format<MeterWorkRailwayActFirst>(prs, actFirst);
                    actFirst.actualFirstNo = ugr.Cells["actualFirstNo"].Text;
                    actFirst.baseSpotNo = ugrPw.Cells["baseSpotNo"].Text;
                    actFirst.baseSpotName = ugrPw.Cells["baseSpotName"].Text;
                    //actFirst.railwayNo = ugrRec.Cells["railwayNo"].Text;
                    actFirst.railwaySpeed = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["railwaySpeed"].Text) ? "0" : ugr.Cells["railwaySpeed"].Text);
                    actFirst.meterWeight = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["meterWeight"].Text) ? "0" : ugr.Cells["meterWeight"].Text);
                    actFirst.createTime = Convert.ToDateTime(ugr.Cells["createTime"].Text);
                    actFirst.railwayCarriageNo = ugr.Cells["railwayCarriageNo"].Text;
                    actFirst.meterClass = appUser.userClass;
                    actFirst.meterGroup = appUser.userGroup;
                    actFirst.createManName = appUser.username;
                    actFirst.createManNo = appUser.userid;
                    actFirst.waterNum = (double) txtWaterNum.Value;
                    lmwrf.Add(actFirst);
                }
            }

            if (lmwrf.Count > 0)
            {
                if (int.Parse(prs.railwayCarriageNo) < lmwrf.Count)
                {
                    MessageBox.Show("当前勾选的过磅数据条数超过了预报可用次数，请重新选择");
                    return;
                }

                FrmMessage frmMessage = FrmMess($"当前选中了【{lmwrf.Count}】条过磅数据\n\r期限皮重为【{mbaseWeight.railwayWeight/1000}】\n\r是否进行匹配！", "匹配");
                if (frmMessage.ShowDialog(this) != DialogResult.OK) 
                {
                    return;
                }

                //下面先保存，保存成功则使用下面的清理predictionNo的代码
                RESTfulResult<string> rES = actFirstService.doAddMotoriaWf(prs, lmwrf, mbaseWeight);
                if (rES.Succeed)
                {
                    QueryPre();
                    QueryNetDb();

                    UltraGridRow ugr = ultraGridVoice.ActiveRow;
                    if (ugr != null)
                    {
                        QueryReceived(ugr.Cells["actualNo"].Text.Trim());
                    }
                    MessageBox.Show("匹配成功");
                }
                else
                {
                    MessageBox.Show("匹配失败：" + rES.Message);
                }
            }
            else
            {
                MessageBox.Show("请勾选未使用的过磅数据");
            }
        }

        private static FrmMessage FrmMess(string strMess, string strBtnSaveInfo)
        {
            FrmMessage frmMessage = new FrmMessage();
            frmMessage.StartPosition = FormStartPosition.Manual;
            frmMessage.Location = new Point(350, 450);
            frmMessage.ShowMessage = strMess;
            frmMessage.BtnSaveText = strBtnSaveInfo;
            frmMessage.BtnCancelText = "取消";
            return frmMessage;
        }

        private void btnPlay() 
        {
            UltraGridRow ugr = ultraGridPW.ActiveRow;
            if (ugr != null)
            {
                string sBaseSpotNo= ugr.Cells["baseSpotNo"].Text.Trim();
                MeterBaseVideoinfo mbv = ltMbV.Where(s => s.pointid == ugr.Cells["baseSpotNo"].Text.Trim()).FirstOrDefault();
                if (mbv != null && mbv.videoip != null && mbv.videoip != "")
                {
                    System.Diagnostics.Process.Start("chrome", string.Format("http://{0}", mbv.videoip));//指定浏览器
                    MessageBox.Show(string.Format("登录账号：{0}\n\r登录密码：{1}", "admin", "hk123456"));
                }
            }

            
            //"C:\\Users\\eason\\Desktop\\测试.mp4"; ftp://172.22.42.2/pub/2020-12-28/00001_Voice_1.mp4;
            //axWindowsMediaPlayer1.URL = @"\\168.168.45.55\11\测试.mp4";
            //axWindowsMediaPlayer1.Ctlcontrols.play();

        }

        private void btnTare() 
        {
            if (ultraGridRecive.Rows.Count > 0)
            {
                MeterBaseRailwayWeight mbrw = new MeterBaseRailwayWeight();
                int i = 0;
                decimal dSum = 0;
                mbrw.railwayWeight = 0;
                foreach (UltraGridRow ugr in ultraGridRecive.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE")
                    {
                        mbrw.railwayWeight += Convert.ToDecimal(ugr.Cells["meterWeight"].Text.Trim() == "" ? "0" : ugr.Cells["meterWeight"].Text.Trim());
                        i++;
                    }
                }


                if (i > 0)
                {
                    dSum = mbrw.railwayWeight.Value;
                    mbrw.railwayWeight = Math.Round(mbrw.railwayWeight.Value / i, 2);

                    frmMotoriaTareSave fc = new frmMotoriaTareSave();
                    mbrw.createManNo = appUser.userid;
                    mbrw.createManName = appUser.username;
                    mbrw.railwayTypeNo = "001019002";
                    mbrw.railwayTypeName = "动态轨道衡";
                    mbrw.valueFlag = "0";
                    mbrw.railwayType = "0";
                    mbrw.tareType = strBaseSpotNo;


                    fc.iCnt = i;
                    fc.dWgt = dSum;
                    fc.getDt = mbrw;
                    if (fc.ShowDialog() == DialogResult.OK)
                    {
                        QueryFirstDb();
                        MessageBox.Show("期限皮重保存成功");
                    }
                }
                else
                {
                    MessageBox.Show("请勾选需求平均期限皮的数据");
                }

            }
            else
            {
                MessageBox.Show("请先勾选需求平均的皮重数据");
            }
        }


        string strBaseSpotNo = "";

        private void ultraGridVoice_Click(object sender, EventArgs e)
        {
            UltraGridRow ugr = ultraGridVoice.ActiveRow;
            if (ugr != null)
            {
                QueryReceived(ugr.Cells["actualNo"].Text.Trim());
                cbCheckAll.Checked = false;

                foreach (UltraGridRow ur in ultraGridVoice.Rows) 
                {
                    ur.Appearance.BackColor = Color.White;
                }
                ugr.Appearance.BackColor = Color.Red;
            }
            
        }

        private void ultraGridPre_Click(object sender, EventArgs e)
        {
            UltraGridRow ugr = ultraGridPre.ActiveRow;
            if (ugr != null)
            {
                foreach (UltraGridRow ugrc in ultraGridPre.Rows)
                {
                    ugrc.Appearance.BackColor = Color.White;
                }
                ugr.Appearance.BackColor = Color.Red;

                //
                if (ultraGridPW.ActiveRow != null && ultraGridPW.ActiveRow.Cells["baseSpotNo"].Text.Trim() == "00025") 
                {
                    foreach (UltraGridRow ugrc in ultraGridFirst.Rows)
                    {
                        if (ugr.Cells["matterName"].Text.Trim().CompareTo("石英石") < 0)
                        {
                            if (ugrc.Cells["tareTypeNo"].Text.Trim() == "001032003")
                            {
                                ultraGridFirst.ActiveRow = ugrc;
                                break;
                            }
                        }
                        else
                        {
                            if (ugrc.Cells["tareTypeNo"].Text.Trim() == "001032002")
                            {
                                ultraGridFirst.ActiveRow = ugrc;
                                break;
                            }
                        }
                    }
                }

            }
        }
        #endregion

        #region 数据查询
        /// <summary>
        /// 视频查询
        /// </summary>
        private void QueryVoice() 
        {
            string sql = string.Format(@"select t.actual_no actualNo,
                               to_char(t.create_time, 'yyyy-MM-dd HH24:mi:ss') createTime,
                               t.carriage_num carriageNum,
                               t.base_spot_no baseSpotNo,
                               t.base_spot_name baseSpotName,
                               t.video_name videoName,
                               t.sound_name soundName,
                               t.track_way trackWay
                          from METER_WORK_RAILWAY_REC_MAIN t
                          where t.create_time between to_date('{0}','yyyy-MM-dd HH24:mi:ss') and to_date('{1}','yyyy-MM-dd HH24:mi:ss')",
                          dtStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), dtEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));

            if (!string.IsNullOrEmpty(strBaseSpotNo))
            {
                sql += " and t.base_spot_no='" + strBaseSpotNo + "'";
            }

            sql += " order by t.actual_no";

            DataTable dtV = dtVioce.Clone();

            PbModelDbService<List<MeterWorkRailwayMotorialRecMain>> pb = new PbModelDbService<List<MeterWorkRailwayMotorialRecMain>>();
            RESTfulResult<List<MeterWorkRailwayMotorialRecMain>> rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                dtV = rmType.Data.ListToDataTable<MeterWorkRailwayMotorialRecMain>();
            }

            ClsControlPack.CopyDataToDatatable(ref dtV, ref this.dtVioce, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridVoice);
        }

        /// <summary>
        /// 采集数据查询
        /// </summary>
        private void QueryReceived(string actualNo)
        {
            string sql = string.Format(@"select t.actual_first_no actualFirstNo,
                               t.railway_no railwayNo,
                               t.railway_carriage_no railwayCarriageNo,
                               t.railway_speed railwaySpeed,
                               nvl(t.meter_weight, 0)/1000 meterWeight,
                               to_char(t.create_time,'yyyy-mm-dd hh24:mi:ss') createTime,
                               t.base_spot_no baseSpotNo,
                               t.base_spot_name baseSpotName,
                               value_flag valueFlag
                          from METER_WORK_RAILWAY_RECEIVED t
                          where value_flag !='0' and actual_first_no like '{0}%' order by t.actual_first_no", actualNo);

            DataTable dtV = dtRecevice.Clone();

            PbModelDbService<List<MeterWorkRailwayMotorialReceived>> pb = new PbModelDbService<List<MeterWorkRailwayMotorialReceived>>();
            RESTfulResult<List<MeterWorkRailwayMotorialReceived>> rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                dtV = rmType.Data.ListToDataTable<MeterWorkRailwayMotorialReceived>();
            }

            ClsControlPack.CopyDataToDatatable(ref dtV, ref this.dtRecevice, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridRecive);

            foreach (UltraGridRow ugrc in ultraGridRecive.Rows)
            {
                if (ugrc.Cells["valueFlag"].Value.ToString() != "1") 
                {
                    ugrc.Appearance.BackColor = Color.Yellow;
                }
            }
        }

        /// <summary>
        /// 预报数据查询
        /// </summary>
        private void QueryPre()
        {
            PreRailwayScale prs = new PreRailwayScale();
            prs.railwayTypeNo = "001019002";
            if (strBaseSpotNo != "") 
            {
                switch (strBaseSpotNo) 
                {
                    case "00025":
                        { 
                            prs.memo = "1"; //选矿计检站动态衡
                            prs.startTime = dtStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                            prs.endTime = dtEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        }; break;
                    case "00026":
                        { 
                            prs.memo = "0"; //砂石计检站动态衡
                        }; break;
                    default:break;
                }
            }

            


            //通过车号查询计量预报
            RESTfulResult<List<PreRailwayScale>> rmx = PreService.doQueryTenWf(prs);
            dtRailwayScale.Clear();
            DataTable dt = dtRailwayScale.Clone();
            if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
            {
                dt = rmx.Data.ListToDataTable<PreRailwayScale>();
            }
            ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtRailwayScale, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridPre);
        }

        /// <summary>
        /// 期限皮重查询
        /// </summary>
        private void QueryFirstDb()
        {
            string sql = @"select railway_pk railwayPk, 
                               railway_no railwayNo, 
                               railway_weight/1000 railwayWeight, 
                               railway_type railwayType, 
                               railway_type_no railwayTypeNo,
                               railway_type_name railwayTypeName, 
                               value_flag valueFlag, 
                               create_man_no createManNo, 
                               create_man_name createManName, 
                               update_man_no updateManNo, 
                               update_man_name updateManName,
                               to_char(update_time, 'yyyy-mm-dd hh24:mi:ss') updateTime,
                               to_char(start_time, 'yyyy-mm-dd') startTime, 
                               term_validity termValidity, 
                               tare_type_no tareTypeNo, 
                               tare_type_name tareTypeName,
                               to_char(create_time, 'yyyy-MM-dd HH24:mi:ss') createTime, 
                               to_char(end_time, 'yyyy-MM-dd') endTime
                          from Meter_Base_Railway_Weight
                          where value_flag = '0' and tare_type='" + strBaseSpotNo + "' order by tare_type_no"; //end_time >= to_date(to_char(sysdate, 'yyyy-MM-dd'), 'yyyy-MM-dd') and

            dtRailwayActFirst.Clear();
            DataTable dtV = dtRailwayActFirst.Clone();

            PbModelDbService<List<MeterBaseRailwayWeight>> pb = new PbModelDbService<List<MeterBaseRailwayWeight>>();
            RESTfulResult<List<MeterBaseRailwayWeight>> rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                dtV = rmType.Data.ListToDataTable<MeterBaseRailwayWeight>();
            }

            ClsControlPack.CopyDataToDatatable(ref dtV, ref this.dtRailwayActFirst, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridFirst);
        }

        /// <summary>
        /// 结净数据查询
        /// </summary>
        private void QueryNetDb()
        {
            string sql = $@"select actual_no actualNo，
                                prediction_no predictionNo，
                                notice_no noticeNo，
                                railway_no railwayNo，
                                railway_carriage_no railwayCarriageNo，
                                matter_no matterNo，
                                matter_name matterName，
                                contract_no contractNo，
                                batch_no batchNo，
                                customer_supplier_no customerSupplierNo，
                                customer_supplier_name customerSupplierName，
                                forwarding_unit_no forwardingUnitNo，
                                forwarding_unit_name forwardingUnitName，
                                receiving_uint_no receivingUintNo，
                                receiving_uint_name receivingUintName，
                                material_no materialNo，
                                material_name materialName，
                                spec_no specNo，
                                spec_name specName，
                                load_point_no loadPointNo，
                                load_point_name loadPointName，
                                sample_voucher sampleVoucher，
                                carrier_unit_no carrierUnitNo，
                                carrier_unit_name carrierUnitName，
                                meter_type_no meterTypeNo，
                                meter_type_name meterTypeName，
                                meter_process_no meterProcessNo，
                                meter_process_edition_no meterProcessEditionNo，
                                actual_first1_no actualFirst1No，
                                nvl(gross_weight,0)/1000 grossWeight，
                                gross_man_no grossManNo，
                                gross_man_name grossManName，
                                to_char(gross_time, 'yyyy-mm-dd hh24:mi:ss') grossTime  ，
                                base_spot1_no baseSpot1No，
                                base_spot1_name baseSpot1Name，
                                gross_class grossClass，
                                gross_group grossGroup，
                                gross_mode grossMode，
                                actual_first2_no actualFirst2No，
                                nvl(tare_weight,0)/1000 tareWeight，
                                tare_man_no tareManNo，
                                tare_man_name tareManName，
                                to_char(tare_time, 'yyyy-mm-dd hh24:mi:ss') tareTime    ，
                                base_spot2_no baseSpot2No，
                                base_spot2_name baseSpot2Name，
                                tare_class tareClass，
                                tare_group tareGroup，
                                tare_mode tareMode，
                                nvl(net_weight,0)/1000 netWeight，
                                net_man_no netManNo，
                                net_man_name netManName，
                                to_char(net_time, 'yyyy-mm-dd hh24:mi:ss') netTime      ，
                                net_spot3_no netSpot3No，
                                net_spot3_name netSpot3Name，
                                net_class netClass，
                                net_group netGroup，
                                net_mode netMode，
                                value_flag valueFlag，
                                upload_flag uploadFlag，
                                check_man_no checkManNo，
                                check_man_name checkManName，
                                to_char(check_time, 'yyyy-mm-dd hh24:mi:ss') checkTime  ，
                                upload_man_no uploadManNo，
                                upload_man_name uploadManName，
                                to_char(upload_time, 'yyyy-mm-dd hh24:mi:ss') uploadTime，
                                sample_no sampleNo，
                                railway_type_no railwayTypeNo，
                                railway_type_name railwayTypeName,
                                water_num waterNum,
                                round((nvl(net_weight,0)- nvl(net_weight,0) * nvl(water_num,0)/100)/1000,2) dryWgt
                          from meter_work_railway_actual
                          where value_flag = '0' and railway_type_no='001019002'  and {(cbTimeType.Text == "毛重时间" ? "gross_time" : "net_time")}  between to_date('{dtStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss")}','yyyy-MM-dd HH24:mi:ss') and  to_date('{dtEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss")}','yyyy-MM-dd HH24:mi:ss')";


            if (!string.IsNullOrEmpty(strBaseSpotNo))
            {
                sql += string.Format(" and NET_SPOT3_NO ='{0}'", strBaseSpotNo);
            }
            sql += " order by net_time";

            dtRailwayActual.Clear();
            DataTable dt = dtRailwayActual.Clone();

            PbModelDbService<List<MeterWorkRailwayActual>> pb = new PbModelDbService<List<MeterWorkRailwayActual>>();
            RESTfulResult<List<MeterWorkRailwayActual>> rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                dt = rmType.Data.ListToDataTable<MeterWorkRailwayActual>();
            }
            ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtRailwayActual, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridNet);
        }


        #endregion



        #region 对讲代码
        int iPic = 0;
        /// <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;
            }
            setPicBoxSet();
            return true;
        }

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

        }

        private void setPicBoxSet()
        {
            pic1.Name = "pb2";
            pic1.DoubleClick += new EventHandler(PictureBoxDoubleClick);
            cameraShotMain.RealPlay(pic1, 2);
        }

        /// <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);
        }

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

        private void frmMotoriaMaincs_FormClosing(object sender, FormClosingEventArgs e)
        {
            IPVideoClose();
        }

        private void cbCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            if (ultraGridRecive.Rows.Count > 0)
            {
                foreach (UltraGridRow ugr in ultraGridRecive.Rows)
                {
                    if (ugr.Cells["valueFlag"].Value.ToString() == "1" && cbCheckAll.Checked)
                    {
                        ugr.Cells["UNCK"].Value = cbCheckAll.Checked;
                    }
                    else
                    {
                        ugr.Cells["UNCK"].Value = false;
                    }
                }
            }
            ultraGridRecive.UpdateData();
        }

        private void ultraGridFirst_Click(object sender, EventArgs e)
        {
            UltraGridRow ugr = ultraGridFirst.ActiveRow;
            if (ugr != null)
            {
                foreach (UltraGridRow ugrc in ultraGridFirst.Rows)
                {
                    ugrc.Appearance.BackColor = Color.White;
                    ugrc.Cells["UNCK"].Value = false;
                }
                ugr.Appearance.BackColor = Color.Red;
                ugr.Cells["UNCK"].Value = true;
            }
        }

        private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            ultraGridNet.UpdateData();
            ultraGridRecive.UpdateData();
            switch (e.Tool.Key)
            {
                case "btnQuery":
                    {
                        cbCheckAll.Checked = false;
                        cbNetAll.Checked = false;
                        btnQuery();
                        break;
                    }
                case "btnSubmit":
                    {
                        btnSubmit();
                        break;
                    }
                case "btnTare":
                    {
                        btnTare();
                        break;
                    }
                case "btnPlay":
                    {
                        btnPlay();
                        break;
                    }
                case "btnWaterSave": 
                    {
                        btnWaterSave();
                        break;
                    } 
                default: break;
            }
        }

        private void btnWaterSave()
        {
            List<MeterWorkRailwayActual> lmwrf = new List<MeterWorkRailwayActual>();
           
            if(ultraGridNet.Rows!=null && ultraGridNet.Rows.Count > 0) 
            {
                foreach (UltraGridRow ugr in ultraGridNet.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE"&& !ugr.HiddenResolved)
                    {
                        MeterWorkRailwayActual act = new MeterWorkRailwayActual();
                        act.actualNo = ugr.Cells["actualNo"].Text.Trim();
                        act.actualFirst1No = ugr.Cells["actualFirst1No"].Text.Trim();
                        act.waterNum = (double)txtWaterNum.Value;
                        act.uploadManName = appUser.username;
                        act.uploadManNo = appUser.userid;

                        lmwrf.Add(act);

                        if (ugr.Cells["uploadFlag"].Value.ToString() != "0")
                        {
                            MessageBox.Show("已审核过的数据不允许进行水份匹配操作！");
                            break;
                        }
                    }
                }
            }
            if (lmwrf.Count > 0)
            {
                FrmMessage frmMessage = FrmMess($"当前选中了【{lmwrf.Count}】条过磅数据\n\r水分为【{lmwrf[0].waterNum.Value}】\n\r是否进行匹配！", "匹配");
                if (frmMessage.ShowDialog(this) != DialogResult.OK)
                {
                    return;
                }

                //下面先保存，保存成功则使用下面的清理predictionNo的代码
                RESTfulResult<string> rES = actFirstService.doEditMotoriaWf(lmwrf);
                if (rES.Succeed)
                {
                    QueryNetDb();
                    MessageBox.Show("匹配成功");
                }
                else
                {
                    MessageBox.Show("匹配失败：" + rES.Message);
                }
            }
            else
            {
                MessageBox.Show("请勾选需增加水分的结净数据");
            }
        }

        private void cbNetAll_CheckedChanged(object sender, EventArgs e)
        {
            if (ultraGridNet.Rows.Count > 0)
            {
                foreach (UltraGridRow ugr in ultraGridNet.Rows)
                {
                    ugr.Cells["UNCK"].Value = cbNetAll.Checked;
                }
            }
            ultraGridNet.UpdateData();
        }
    }
}
