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;
using Common.DbOption.work;
using System.Collections;

namespace RailMeterSystem
{
    public partial class frmTgMotoriaMain : Form
    {
        #region
        MeterWorkRailwayActFirstService actFirstService = new MeterWorkRailwayActFirstService(); //
        MeterBaseRailwayWeightService baseRailwayWgt = new MeterBaseRailwayWeightService(); 
        MeterWorkRailwayActualService actualService = new MeterWorkRailwayActualService();
        MeterWorkRailwayRecMainService meterWorkRailwayRecMainService = new MeterWorkRailwayRecMainService();
        MeterWorkRailwayReceivedService meterWorkRailwayReceivedService = new MeterWorkRailwayReceivedService();
        #endregion


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

        CoreAppUser appUser = null;
        string strBaseSpotNo = "00013", sBaseSpotName = "动态轨道衡";

        public frmTgMotoriaMain()
        {
            InitializeComponent();
        }

        private void frmTgMotoriaMain_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");


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

        #region 按钮事件
        private void btnQuery() 
        {
            dtRecevice.Clear();
            DataTable dtV = dtRecevice.Clone();
            ClsControlPack.CopyDataToDatatable(ref dtV, ref this.dtRecevice, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridRecive);

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

        /// <summary>
        /// 结净匹配
        /// </summary>
        private void btnSubmit() 
        {
            ultraGridRecive.UpdateData();
            ultraGridFirst.UpdateData();

            List<MeterWorkRailwayMotorialReceived> lmmr = new List<MeterWorkRailwayMotorialReceived>();
            List<MeterWorkRailwayActFirst> lmrf = new List<MeterWorkRailwayActFirst>();
            int icnt = 0;
            foreach (UltraGridRow ugrR in ultraGridRecive.Rows) 
            {
                if (ugrR.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE" && !ugrR.HiddenResolved) 
                {
                    icnt++;
                    foreach (UltraGridRow ugr in ultraGridFirst.Rows)
                    {
                        if (ugrR.Cells["railwayNo"].Text.Trim() == ugr.Cells["railwayNo"].Text.Trim()) 
                        {
                            MeterWorkRailwayMotorialReceived rec = new MeterWorkRailwayMotorialReceived();
                            rec.actualFirstNo = ugrR.Cells["actualFirstNo"].Text.Trim();
                            rec.railwayNo = ugrR.Cells["railwayNo"].Text.Trim();
                            rec.railwayCarriageNo = ugrR.Cells["railwayCarriageNo"].Text.Trim();
                            rec.railwaySpeed = Convert.ToDouble(string.IsNullOrEmpty(ugrR.Cells["railwaySpeed"].Text) ? "0" : ugrR.Cells["railwaySpeed"].Text);
                            rec.railwayModel = ugrR.Cells["railwayModel"].Text.Trim();
                            rec.shipmentGrossWeight = Convert.ToDouble(string.IsNullOrEmpty(ugrR.Cells["shipmentGrossWeight"].Text) ? "0" : ugrR.Cells["shipmentGrossWeight"].Text);
                            rec.shipmentNetWeight = Convert.ToDouble(string.IsNullOrEmpty(ugrR.Cells["shipmentNetWeight"].Text) ? "0" : ugrR.Cells["shipmentNetWeight"].Text);
                            rec.meterWeight = Convert.ToDouble(string.IsNullOrEmpty(ugrR.Cells["meterWeight"].Text) ? "0" : ugrR.Cells["meterWeight"].Text);
                            rec.createTime = Convert.ToDateTime(ugrR.Cells["createTime"].Text.Trim());
                            rec.valueFlag = ugrR.Cells["valueFlag"].Text.Trim();
                            rec.baseSpotNo = "00013";
                            rec.baseSpotName = "动态轨道衡";
                            rec.railwayTypeNo = "001019002";
                            rec.railwayTypeName = "动态轨道衡";
                            rec.weightType = "0";
                            lmmr.Add(rec);

                            MeterWorkRailwayActFirst first = new MeterWorkRailwayActFirst();
                            first.actualFirstNo = ugr.Cells["actualFirstNo"].Text.Trim();
                            first.railwayNo = ugr.Cells["railwayNo"].Text.Trim();
                            first.railwayCarriageNo = ugr.Cells["railwayCarriageNo"].Text.Trim();
                            first.railwaySpeed = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["railwaySpeed"].Text) ? "0" : ugr.Cells["railwaySpeed"].Text);
                            first.meterWeight = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["meterWeight"].Text) ? "0" : ugr.Cells["meterWeight"].Text);
                            first.shipmentGrossWeight = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["shipmentGrossWeight"].Text) ? "0" : ugr.Cells["shipmentGrossWeight"].Text);
                            first.shipmentNetWeight = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["shipmentNetWeight"].Text) ? "0" : ugr.Cells["shipmentNetWeight"].Text);
                            first.createManNo = ugr.Cells["createManNo"].Text.Trim();
                            first.createManName = ugr.Cells["createManName"].Text.Trim();
                            first.createTime = Convert.ToDateTime(ugr.Cells["createTime"].Text.Trim());
                            first.valueFlag = ugr.Cells["valueFlag"].Text.Trim();
                            first.weightType = "1";
                            first.baseSpotNo = "00013";
                            first.baseSpotName = "动态轨道衡";
                            first.railwayTypeNo = "001019002";
                            first.railwayTypeName = "动态轨道衡";
                            lmrf.Add(first);

                            break;
                        }
                    }
                }
            }

            string MeterTypeNo = "", MeterTypeName = "";
            FrmMessage frmMessage = FrmMess($"当前选中【{icnt}】条毛重数据，当前选中【{lmrf.Count}】条皮重数据\n\r是否进行匹配！", "进厂保存");
            if (frmMessage.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            else 
            {
                string sType = frmMessage.setType;
                switch (sType) 
                {
                    case "0": //采购
                        MeterTypeNo = "001006001";
                        MeterTypeName = "采购进厂";
                        break;
                    case "1": //销售
                        MeterTypeNo = "001006002";
                        MeterTypeName = "销售出厂";
                        break;
                }
            }

            if (lmmr.Count == 0)
            {
                MessageBox.Show("请确保至少有一条能进行结净的毛皮数据");
            }
            else
            {
                for (int i = 0; i < lmmr.Count; i++) 
                {
                    lmmr[i].meterTypeNo = MeterTypeNo;
                    lmmr[i].meterTypeName = MeterTypeName;
                    lmrf[i].meterTypeNo = MeterTypeNo;
                    lmrf[i].meterTypeName = MeterTypeName;
                }

                //下面先保存，保存成功则使用下面的清理predictionNo的代码
                RESTfulResult<string> rES = actFirstService.doAddRailNetWf(lmmr, lmrf);
                if (rES.Succeed)
                {
                    QueryNetDb();
                    QueryFirstDb();
                    UltraGridRow ugr = ultraGridVoice.ActiveRow;
                    if (ugr != null)
                    {
                        QueryReceived(ugr.Cells["actualNo"].Text.Trim());
                    }
                    MessageBox.Show("操作成功");
                }
                else
                {
                    MessageBox.Show("操作失败：" + rES.Message);
                }
            }
        }

        /// <summary>
        /// 取消结净
        /// </summary>

        private void btnUnSubmit()
        {
            ultraGridNet.UpdateData();
            if (ultraGridNet.Rows.Count > 0) 
            {
                List<MeterWorkRailwayActual> ltFirst = new List<MeterWorkRailwayActual>();
                foreach (UltraGridRow ugr in ultraGridNet.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE" && !ugr.HiddenResolved)
                    {
                        MeterWorkRailwayActual actual = new MeterWorkRailwayActual();
                        actual.actualNo = ugr.Cells["actualNo"].Text.Trim();
                        actual.actualFirst1No = ugr.Cells["actualFirst1No"].Text.Trim();
                        actual.actualFirst2No = ugr.Cells["actualFirst2No"].Text.Trim();
                        ltFirst.Add(actual);
                    }
                }
                if (ltFirst != null && ltFirst.Count > 0)
                {
                    RESTfulResult<string> result = actFirstService.doRemoveRailNetWf(ltFirst);
                    if (result.Succeed)
                    {
                        QueryNetDb();
                        QueryFirstDb();
                        UltraGridRow ugr = ultraGridVoice.ActiveRow;
                        if (ugr != null)
                        {
                            QueryReceived(ugr.Cells["actualNo"].Text.Trim());
                        }
                    }
                    else
                    {
                        MessageBox.Show("删除失败：" + result.Message);
                    }
                }
                else 
                {
                    MessageBox.Show("请先勾选需删除且未审核的结净数据");
                }
            }
        }
        /// <summary>
        ///皮重保存
        /// </summary>

        private void btnTare()
        {
            if (ultraGridRecive.Rows.Count > 0)
            {
                List<MeterWorkRailwayActFirst> ltFirst = new List<MeterWorkRailwayActFirst>();
                foreach (UltraGridRow ugr in ultraGridRecive.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE" && !ugr.HiddenResolved)
                    {
                        MeterWorkRailwayActFirst fs = new MeterWorkRailwayActFirst();
                        fs.railwayNo = ugr.Cells["railwayNo"].Text.Trim();
                        fs.actualFirstNo = ugr.Cells["actualFirstNo"].Text.Trim();
                        fs.railwayCarriageNo = ugr.Cells["railwayCarriageNo"].Text.Trim();
                        fs.railwaySpeed = Convert.ToDouble(ugr.Cells["railwaySpeed"].Text.Trim());
                        fs.meterWeight = Convert.ToDouble(ugr.Cells["meterWeight"].Text.Trim());
                        fs.createTime = Convert.ToDateTime(ugr.Cells["createTime"].Text.Trim());
                        fs.railwayModelName = ugr.Cells["railwayModel"].Text.Trim();
                        fs.baseSpotNo = strBaseSpotNo;
                        fs.baseSpotName = sBaseSpotName;
                        fs.valueFlag = "1";
                        fs.weightType = "1";
                        fs.createManNo = appUser.userid;
                        fs.createManName = appUser.username;
                        fs.shipmentGrossWeight = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["shipmentGrossWeight"].Text) ? "0" : ugr.Cells["shipmentGrossWeight"].Text);
                        fs.shipmentNetWeight = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["shipmentNetWeight"].Text) ? "0" : ugr.Cells["shipmentNetWeight"].Text);
                        fs.railwayTypeNo = "001019002";
                        fs.railwayTypeName = "动态轨道衡";
                        ltFirst.Add(fs);
                    }
                }

                if (ltFirst != null && ltFirst.Count > 0)
                {
                    RESTfulResult<string> result = actFirstService.doAddRailWf(ltFirst);
                    if (result.Succeed)
                    {
                        UltraGridRow ugr = ultraGridVoice.ActiveRow;
                        QueryReceived(ugr.Cells["actualNo"].Text.Trim());
                        QueryFirstDb();
                    }
                    else
                    {
                        MessageBox.Show("新增失败！");
                    }

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

        /// <summary>
        /// 皮重删除
        /// </summary>

        private void btnUnTare()
        {
            if (ultraGridFirst.Rows.Count > 0)
            {
                List<MeterWorkRailwayActFirst> ltFirst = new List<MeterWorkRailwayActFirst>();
                foreach (UltraGridRow ugr in ultraGridFirst.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE" && !ugr.HiddenResolved)
                    {
                        MeterWorkRailwayActFirst fs = new MeterWorkRailwayActFirst();
                        fs.actualFirstNo = ugr.Cells["actualFirstNo"].Text.Trim();
                        ltFirst.Add(fs);
                    }
                }

                if (ltFirst != null && ltFirst.Count > 0)
                {
                    RESTfulResult<string> result = actFirstService.doDeleteWf(ltFirst);
                    if (result.Succeed)
                    {
                        QueryFirstDb();

                        UltraGridRow ugr = ultraGridVoice.ActiveRow;
                        if (ugr != null)
                        {
                            QueryReceived(ugr.Cells["actualNo"].Text.Trim());
                        }
                    }
                    else
                    {
                        MessageBox.Show("删除失败！");
                    }
                }
            }
            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 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;
            }
            
        }
        #endregion

        #region 数据查询
        /// <summary>
        /// 采集主表数据查询
        /// </summary>
        private void QueryVoice() 
        {
            DataTable dtV = dtVioce.Clone();

            Hashtable hashtable = new Hashtable();
            hashtable.Add("startTime", dtStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            hashtable.Add("endTime", dtEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!string.IsNullOrEmpty(strBaseSpotNo))
            {
                hashtable.Add("startTime", dtStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            RESTfulResult<List<MeterWorkRailwayRecMain>> rm = meterWorkRailwayRecMainService.Query(hashtable);

            dtV = ListToDatatable.ListToDataTable(rm.Data);

            //PbModelDbService<List<MeterWorkRailwayRecMain>> pb = new PbModelDbService<List<MeterWorkRailwayRecMain>>();
            //RESTfulResult<List<MeterWorkRailwayRecMain>> 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) meterWeight,
                               t.railway_model railwayModel,
                               to_char(t.create_time,'yyyy-mm-dd hh24:mi:ss') createTime,
                               t.base_spot_no baseSpotNo,
                               t.base_spot_name baseSpotName,
                               t.value_flag valueFlag,
                               t.shipment_Gross_Weight shipmentGrossWeight,
                               t.shipment_Net_Weight shipmentNetWeight
                          from METER_WORK_RAILWAY_RECEIVED t
                          where value_flag ='1' 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 QueryFirstDb()
        {
            string sql = $@"select actual_first_no actualFirstNo, 
                                railway_no railwayNo, 
                                railway_carriage_no railwayCarriageNo,
                                railway_work_no railwayWorkNo,
                                railway_speed railwaySpeed,
                                nvl(meter_weight, 0) meterWeight,
                                weight_type weightType,
                                create_man_no createManNo,
                                railway_model_name railwayModelName,
                                create_man_name createManName,
                                to_char(create_time, 'yyyy-mm-dd hh24:mi:ss') createTime,
                                base_spot_no baseSpotNo,
                                base_spot_name baseSpotName,
                                value_flag valueFlag,
                                shipment_Gross_Weight shipmentGrossWeight,
                                shipment_Net_Weight shipmentNetWeight
                          from Meter_Work_Railway_Act_First
                          where value_flag = '1' and weight_type='1' and base_spot_no='00013'  and create_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') order by CREATE_TIME,RAILWAY_CARRIAGE_NO";
                          
            dtRailwayActFirst.Clear();
            DataTable dtV = dtRailwayActFirst.Clone();

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

            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) 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) 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) 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),2) dryWgt,
                                RAILWAY_MODEL_NAME railwayModelName
                          from meter_work_railway_actual
                          where value_flag = '0'  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')";
            //and railway_type_no='001019002' 轨道衡类型

            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

        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 "btnTareSave":
                    {
                        btnTare();
                        break;
                    }
                case "btnUnSubmit":
                    {
                        btnUnSubmit();
                        break;
                    }
                case "btnUnTareSave":
                    {
                        btnUnTare();
                        break;
                    }
                default: break;
            }
        }


        private void cbCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            if (ultraGridRecive.Rows.Count > 0)
            {
                foreach (UltraGridRow ugr in ultraGridRecive.Rows)
                {
                    ugr.Cells["UNCK"].Value = cbCheckAll.Checked;
                    foreach (UltraGridRow ugrx in ultraGridFirst.Rows)
                    {
                        if (ugrx.Cells["railwayNo"].Text.Trim() == ugr.Cells["railwayNo"].Text.Trim())
                        {
                            ugrx.Cells["UNCK"].Value = cbCheckAll.Checked;
                            break;
                        }
                    }
                }
            }
            ultraGridFirst.UpdateData();
            ultraGridRecive.UpdateData();
        }

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

        private void ultraGridRecive_AfterCellUpdate(object sender, CellEventArgs e)
        {
            UltraGridRow ugr = ultraGridRecive.ActiveRow;
            if (ugr != null)
            {
                foreach (UltraGridRow ugrx in ultraGridFirst.Rows)
                {
                    if (ugrx.Cells["railwayNo"].Text.Trim() == ugr.Cells["railwayNo"].Text.Trim())
                    {
                        ugrx.Cells["UNCK"].Value = ugr.Cells["UNCK"].Value;
                        break;
                    }
                }
            }
            ugr.Appearance.BackColor = Color.Red;
        }

        private void ultraGridNet_AfterRowActivate(object sender, EventArgs e)
        {
            UltraGridRow ugr = ultraGridNet.ActiveRow;

            if (ugr != null) 
            {
                if (ultraGridNet.Rows.Count > 0)
                {
                    foreach (UltraGridRow ugrc in ultraGridNet.Rows)
                    {
                        ugrc.Appearance.BackColor = Color.White;
                    }
                }
                ugr.Appearance.BackColor = Color.Red;
            } 
            
        }

        private void ultraGridVoice_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {

        }

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

        public class ListToDatatable
        {
            public ListToDatatable() { }
            public static DataTable ListToDataTable<T>(List<T> entitys)
            {

                //检查实体集合不能为空
                if (entitys == null || entitys.Count < 1)
                {
                    return new DataTable();
                }

                //取出第一个实体的所有Propertie
                Type entityType = entitys[0].GetType();
                PropertyInfo[] entityProperties = entityType.GetProperties();

                //生成DataTable的structure
                //生产代码中，应将生成的DataTable结构Cache起来，此处略
                DataTable dt = new DataTable("dt");
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                    dt.Columns.Add(entityProperties[i].Name);
                }

                //将所有entity添加到DataTable中
                foreach (object entity in entitys)
                {
                    //检查所有的的实体都为同一类型
                    if (entity.GetType() != entityType)
                    {
                        throw new Exception("要转换的集合元素类型不一致");
                    }
                    object[] entityValues = new object[entityProperties.Length];
                    for (int i = 0; i < entityProperties.Length; i++)
                    {
                        entityValues[i] = entityProperties[i].GetValue(entity, null);

                    }
                    dt.Rows.Add(entityValues);
                }
                return dt;
            }
        }
    }
}
