using CarMeterSystem.OptionCls;
using com.hnshituo.core.webapp.vo;
using Common;
using Infragistics.Win.UltraWinGrid;
using MeterConditionLibrary;
using MeterModuleLibrary;
using MeterPlugInLibrary;
using MeterSceneLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace CarMeterSystem
{
    public partial class frmInternalTransport : Form
    {
        private validTermTareCar termTareCar = new validTermTareCar();//验证是否可留期限皮
        private MeterBaseTermTareDataService termTareDate = new MeterBaseTermTareDataService();//留期限皮操作
        private MeterWorkMonitorService monitor = new MeterWorkMonitorService(); //设备及远程呼叫监控表
        private MeterBaseHisTareDataService histTare = new MeterBaseHisTareDataService();//历史皮重
        private MeterWorkCarActualFirstService workCarActualFirstService = new MeterWorkCarActualFirstService();//一次计量数据
        private MeterWorkCarRecoverService carRecoverService = new MeterWorkCarRecoverService(); //复磅操作

        private validRecoverInfo recoverInfo = new validRecoverInfo();//验证是否需要复磅以及是否满足复磅条件

        private MeterWorkCarActualFirst firstDb = null;//一次计量数据
        private InnerMeter inner = new InnerMeter(); //内倒业务处理
        private Print printClass = new Print();//打印

        //验证校秤数据
        private validCalibration vCalib = new validCalibration();

        private VoicePlay vicPlayClass = new VoicePlay();//语音播放
        private Log lg = Log.GetInstance(); //写日志

        public bool isTest = false;

        public frmInternalTransport()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                PbCache.isLockFrm = true;

                PbCache.lockCarNo = PbCache.collect.carno;
                PbCache.lockWgt = PbCache.collect.weight;

                btnSubmit.Enabled = false;
                btnTare.Enabled = false;

                //2021年6月22日 存在需要复磅的数据，不允许进行保存操作
                recoverInfo.ValidAllowSave(PbCache.lockCarNo);
                if (PbCache.isAllowRecover)
                {
                    PbCache.isLockFrm = false;
                    btnSubmit.Enabled = true;
                    btnTare.Enabled = true;
                    setMsg(PbCache.ResultMessage);
                    return;
                }

                txtMsgInfo.Text = "称重保存中......";
                FrmMessage frmMessage = FrmMess("是否确认保存当前计量数据！", "继续保存");
                lg.WriteLog(15, PbCache.lockCarNo + "点击了保存按钮【内倒界面】");
                if (frmMessage.ShowDialog(this) == DialogResult.Cancel)
                {
                    PbCache.isLockFrm = false;
                    btnSubmit.Enabled = true;
                    btnTare.Enabled = true;
                    txtMsgInfo.Text = "";
                    lg.WriteLog(15, PbCache.lockCarNo + "保存按钮选择了【否】【内倒界面】");
                    return;
                }

                try
                {
                    //是否在黑名单内
                    MeterBaseCarBlacelistService bService = new MeterBaseCarBlacelistService();
                    RESTfulResult<List<MeterBaseCarBlacelist>> rmB = bService.doQueryWf(new MeterBaseCarBlacelist { carNo = PbCache.lockCarNo, valueFlag = "0" });
                    if (rmB.Succeed)
                    {
                        if (rmB.Data != null && rmB.Data.Count > 0)
                        {
                            PbCache.ResultMessage = string.Format("车辆[{0}在黑名单内，不能计量", PbCache.lockCarNo);
                            lg.WriteLog(3, string.Format("车辆[{0}在黑名单内，不能计量", PbCache.lockCarNo));

                            PbCache.isLockFrm = false;
                            btnSubmit.Enabled = true;
                            btnTare.Enabled = true;

                            vicPlayClass.GetVoicePlay("车辆在黑名单内", PbCache.lockCarNo);
                            //提示信息，
                            setMsg(PbCache.ResultMessage);
                            return;
                        }
                    }
                    else
                    {
                        PbCache.ResultMessage = "保存失败，获取黑名单数据异常，请稍后再试";
                        lg.WriteLog(3, "获取黑名单数据异常，请稍后再试");

                        PbCache.isLockFrm = false;
                        btnSubmit.Enabled = true;
                        btnTare.Enabled = true;

                        vicPlayClass.GetVoicePlay("车辆在黑名单内", PbCache.lockCarNo);
                        //提示信息，
                        setMsg(PbCache.ResultMessage);
                        return;
                    }

                    List<PbModelDb> lp = ucCarMeterInfo1.lp;
                    rtInfo ri = null;
                    //ucCarMeterInfo1
                    //获取稳定的重量，车号，计量信息等，然后进行计量业务操作
                    if (lp != null)
                    {
                        ri = inner.MeterMethod(new InnerMeterInfo
                        {
                            carNo = PbCache.lockCarNo,
                            batchNo = ucCarMeterInfo1.batchNo(),
                            forwardingUnitNo = lp.Where(s => s.id == "forwardingUnitNo").FirstOrDefault() != null ? lp.Where(s => s.id == "forwardingUnitNo").FirstOrDefault().text : "",
                            forwardingUnitName = lp.Where(s => s.id == "forwardingUnitName").FirstOrDefault() != null ? lp.Where(s => s.id == "forwardingUnitName").FirstOrDefault().text : "",
                            matterNo = lp.Where(s => s.id == "matterNo").FirstOrDefault() != null ? lp.Where(s => s.id == "matterNo").FirstOrDefault().text : "",
                            matterName = lp.Where(s => s.id == "matterName").FirstOrDefault() != null ? lp.Where(s => s.id == "matterName").FirstOrDefault().text : "",
                            receivingUintName = lp.Where(s => s.id == "receivingUintName").FirstOrDefault() != null ? lp.Where(s => s.id == "receivingUintName").FirstOrDefault().text : "",
                            receivingUintNo = lp.Where(s => s.id == "receivingUintNo").FirstOrDefault() != null ? lp.Where(s => s.id == "receivingUintNo").FirstOrDefault().text : "",
                            meterTypeNo = "001006003",
                            meterTypeName = ucCarMeterInfo1.meterTypeName == null ? "" : ucCarMeterInfo1.meterTypeName,
                            //predictionNo = "",
                            predictionNo = ucCarMeterInfo1.predictionNo(), //2021年4月27日将predictionNo业务号存在预报编号字段中
                            addWgtNo = ucCarMeterInfo1.getJz(),
                            addWgtPk = string.IsNullOrEmpty(ucCarMeterInfo1.getAddWgtPk) ? "" : ucCarMeterInfo1.getAddWgtPk.Substring(0, ucCarMeterInfo1.getAddWgtPk.Length - 1)
                        });
                    }
                    else
                    {
                        ri = inner.MeterMethod(new InnerMeterInfo
                        {
                            carNo = PbCache.lockCarNo,
                            batchNo = "",
                            forwardingUnitNo = "",
                            forwardingUnitName = "",
                            matterNo = "",
                            matterName = "",
                            receivingUintName = "",
                            receivingUintNo = "",
                            meterTypeNo = "001006003",
                            meterTypeName = ucCarMeterInfo1.meterTypeName == null ? "" : ucCarMeterInfo1.meterTypeName,
                            predictionNo = ""
                        });
                    }
                    if (ri.result == true)
                    {
                        try
                        {
                            #region 截取图片信息

                            //*
                            //截取屏幕信息

                            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\\formalImg\\{1}_{2}_{3}.jpg",
                                AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                                PbCache.sportInfo.baseSpotNo, "C" + PbCache.actualFirstNo, 7), System.Drawing.Imaging.ImageFormat.Jpeg);
                            //(PbCache.videoChild.Count + 1)), System.Drawing.Imaging.ImageFormat.Jpeg);

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

                            #endregion 截取图片信息
                        }
                        catch (Exception ex)
                        {
                            lg.WriteLog(3, "计量完成，但图片截取失败，编号：" + PbCache.actualFirstNo);
                        }

                        //若不是测试，保存完成后则不能返回，若是测试界面进入的则可点击返回按钮
                        if (!isTest)
                        {
                            btnFH.Enabled = false;
                        }
                        btnTare.Enabled = true;
                    }
                    else
                    {
                        PbCache.isLockFrm = false;
                        btnSubmit.Enabled = true;
                        btnTare.Enabled = true;
                    }

                    //提示信息，
                    //setMsg(PbCache.ResultMessage);

                    #region LED写入

                    PbCache.ledInfo = string.Format("计量完成，车号：{0}，车重：{1}，物资：{2}", PbCache.lockCarNo, PbCache.lockWgt, lp != null ? lp.Where(s => s.id == "matterName").FirstOrDefault().text : "");

                    #endregion LED写入

                    #region 计量完成后，查一次是否在期限皮提醒时间范围内，若在则提醒留期限皮

                    //*
                    if (ri.result == true) //&& termTareCar.ValidMethod(PbCache.collect.carno))
                    {
                        int iSound = 0;
                        string sql = @"select base_spot_no   baseSpotNo,
                                       base_spot_name baseSpotName,
                                       warn_time      warnTime,
                                       end_time    endTime,
                                       car_no         carNo
                                  from Meter_Base_Term_Tare_Data
                                  where car_no='" + PbCache.lockCarNo + "' and value_flag='0'";
                        PbModelDbService<List<MeterBaseTermTareData>> pbModelDbService = new PbModelDbService<List<MeterBaseTermTareData>>();
                        RESTfulResult<List<MeterBaseTermTareData>> rES = pbModelDbService.executeSqlDataWf(sql);

                        if (rES.Succeed)
                        {
                            if (rES.Data != null && rES.Data.Count > 0)
                            {
                                if (DateTime.Now.CompareTo(rES.Data[0].endTime) >= 0)
                                {
                                    PbCache.ResultMessage += "\n\r提醒：期限皮重已过期，请及时留期限皮";
                                    iSound = 1;
                                }
                                else if (DateTime.Now.CompareTo(rES.Data[0].warnTime) >= 0)
                                {
                                    PbCache.ResultMessage += "\n\r提醒：期限皮重将要过期，请及时留期限皮";
                                    //setMsg(PbCache.ResultMessage + "\n\r提醒：上次留的期限皮重将要过期，请及时留期限皮");
                                    iSound = 1;
                                }
                            }
                        }

                        sql = @"select t.matter_no id, t.matter_name text
                              from meter_base_matter_info t,meter_work_car_actual_first c
                             where c.matter_no=t.matter_no
                                   and c.WEIGHT_TYPE='0'
                                   and c.value_flag = '1'
                                   and c.actual_first_no='" + PbCache.actualFirstNo + "'";

                        PbModelDbService<List<PbModelDb>> pb = new PbModelDbService<List<PbModelDb>>();
                        RESTfulResult<List<PbModelDb>> rm = pb.executeSqlDataWf(sql);
                        if (rm.Succeed)
                        {
                            if (rm.Data != null && rm.Data.Count > 0)
                            {
                                PbCache.ResultMessage += "\n\r提醒：当前物料未结净，请于下次进行空车称重保存";
                                iSound = iSound == 1 ? 3 : 2;
                            }
                        }

                        switch (iSound)
                        {
                            case 0:
                                vicPlayClass.GetVoicePlay(ri.resultInfo, PbCache.lockCarNo);
                                break;
                            case 1:
                                vicPlayClass.GetVoicePlay("称重完成空车留期限皮", PbCache.lockCarNo);
                                break;
                            case 2:
                                vicPlayClass.GetVoicePlay("称重完成空车回皮", PbCache.lockCarNo);
                                break;
                            case 3:
                                vicPlayClass.GetVoicePlay("称重完成空车回皮留期限皮", PbCache.lockCarNo);
                                break;
                        }
                    }
                    else
                    {
                        vicPlayClass.GetVoicePlay(ri.resultInfo, PbCache.lockCarNo);
                    }

                    setMsg(PbCache.ResultMessage);
                    //*
                    if (ri.result == true)
                    {
                        //票据打印
                        Print1(PbCache.actualFirstNo);
                    }
                    //*/

                    #endregion 计量完成后，查一次是否在期限皮提醒时间范围内，若在则提醒留期限皮
                }
                catch (Exception ex)
                {
                    btnSubmit.Enabled = true;
                    btnTare.Enabled = true;
                    //语音播报
                    vicPlayClass.GetVoicePlay("称重数据保存失败", PbCache.lockCarNo);
                    //提示信息，
                    setMsg("称重数据保存失败");
                    lg.WriteLog(3, PbCache.lockCarNo + "称重保存失败：" + ex.Message);
                }
            }
            catch (Exception ex)
            {
                lg.WriteLog(13, PbCache.lockCarNo + "保存事件异常【内倒计量】：" + ex.Message);
            }
        }

        /// <summary>
        /// 复磅保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRecover_Click(object sender, EventArgs e)
        {
            try
            {
                if (PbCache.collect == null) return;
                PbCache.isLockFrm = true;
                PbCache.lockCarNo = PbCache.collect.carno;
                PbCache.lockWgt = PbCache.collect.weight;
                btnRecover.Enabled = false;
                lg.WriteLog(15, PbCache.lockCarNo + "点击【复磅】按钮");

                //验证是否满足复磅的条件
                recoverInfo.ValidMethod(PbCache.lockCarNo);
                if (!PbCache.isAllowRecover)
                {
                    PbCache.isLockFrm = false;
                    btnRecover.Enabled = true;
                    setMsg(PbCache.ResultMessage);
                    lg.WriteLog(15, PbCache.lockCarNo + "不满足复磅条件！");
                    return;
                }

                txtMsgInfo.Text = "复磅保存中......";
                FrmMessage frmMessage = FrmMess("是否确认保存当前复磅重量数据！", "继续保存");
                if (frmMessage.ShowDialog(this) == DialogResult.Cancel)
                {
                    PbCache.isLockFrm = false;
                    btnRecover.Enabled = true;
                    txtMsgInfo.Text = "";
                    lg.WriteLog(15, PbCache.lockCarNo + "【复磅】按钮选择否");
                    return;
                }

                //复磅数据保存
                RESTfulResult<string> RESTfulResult = carRecoverService.doRecover(new MeterWorkCarRecover { carNo = PbCache.lockCarNo, recMeterWeight = PbCache.lockWgt });
                if (RESTfulResult.Succeed)
                {
                    //保存成功，语音提示保存成功
                    vicPlayClass.GetVoicePlay("称重完成", PbCache.lockCarNo);//播放语音
                    btnTare.Visible = false;
                    lg.WriteLog(3, string.Format("车号[{0}]复磅保存成功", PbCache.lockCarNo));
                    setMsg("复磅保存成功，请离开秤台！");
                }
                else
                {
                    PbCache.isLockFrm = false;
                    btnRecover.Enabled = true;
                    setMsg(RESTfulResult.ResultMessage);
                    vicPlayClass.GetVoicePlay("称重数据保存失败", PbCache.lockCarNo);//播放语音
                    lg.WriteLog(3, string.Format("车号[{0}]复磅保存失败" + RESTfulResult.Message, PbCache.lockCarNo));
                }
            }
            catch (Exception ex)
            {
                lg.WriteLog(13, PbCache.lockCarNo + "复磅保存事件异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 车号改变事件；用于触发修正车号后的复磅操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCarNo_TextChanged(object sender, EventArgs e)
        {
            //第一次判断由timerk控件执行
            if (!string.IsNullOrEmpty(txtCarNo.Text) && !isShowRecover)
            {
                recoverInfo.ValidMethod(txtCarNo.Text);
                if (PbCache.isAllowRecover)
                {
                    btnRecover.Visible = true;
                }
                else
                {
                    btnRecover.Visible = false;
                }
                isShowRecover = false;
            }
        }

        private void frmInternalTransport_Load(object sender, EventArgs e)
        {
            try
            {
                timer1.Start();
                lbPointName.Text = PbCache.sportInfo.baseSpotName;
                ucCarMeterInfo1.setMeterType(PbCache.bussinessTypeName);
                ucCarMeterInfo1.openWgt += new EventOpenWgt(EventWgt);
                ucCarMeterInfo1.openTareWgt += new EventOpenWgt(EventTareWgt);
            }
            catch (Exception ex)
            {
                lg.WriteLog(13, PbCache.lockCarNo + "frmInternalTransport_Load事件异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 委托事件；从用户组件中调用
        /// </summary>
        /// <param name="wgt"></param>
        private void EventWgt(string wgt)
        {
            if (!string.IsNullOrEmpty(wgt))
            {
                if (!string.IsNullOrEmpty(txtNet.Text.Trim()))
                {
                    try
                    {
                        //2021年5月10日界面显示单位，调整为T
                        txtNet.Text = Math.Round((Convert.ToInt32(txtGroess.Text.Trim()) - Convert.ToInt32(txtTare.Text.Trim()) - (double)Convert.ToInt32(wgt) / 1000), 2) + "";
                    }
                    catch (Exception ex)
                    {
                        lg.WriteLog(13, PbCache.lockCarNo + "EventWgt重量计算事件异常：" + ex.Message);
                    }
                }
                PbCache.addWgt = Convert.ToInt32(wgt);
            }
            else
            {
                PbCache.addWgt = 0;
            }
        }

        /// <summary>
        /// 委托事件，设置皮重
        /// </summary>
        /// <param name="wgt"></param>
        private void EventTareWgt(string wgt)
        {
            firstWgt = string.IsNullOrEmpty(wgt) ? 0 : Convert.ToInt32(wgt);
        }

        private double firstWgt = 0, fWg = 0;
        private bool bRailwayActual = true;//
        private bool isVoiceDownCar = false;//车上人员请下车播放一次

        private bool isOverSound = false;
        private string sCode = "";

        private bool isCalibration = true;
        private bool bRelation = true;
        private string strMatNo = "", strRecNo = "", strSndNo = ""; //物料的编号,收货单位编号，发货单位编号
        private bool bXCStart = false;

        private string sPreCarNo = "";//上一次PbCache.collect.carno中的车号
        private bool isShowRecover = true; //是否需要判断显示复磅按钮

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!PbCache.isLockFrm)
                {
                    //ucWeightT1.setWgt(PbCache.collect.weight);
                    double a = Math.Round((double)PbCache.collect.weight / 1000, 2);
                    ucWeightT1.setWgt(a); //2021年5月10日界面显示单位，调整为T
                    ucWeightT1.setStable(PbCache.collect.weightStatus != 1 ? true : false);
                    //ucWeightT1.setExceed(PbCache.collect.weight > PbCache.range.upperRange * 1000 ? false : true);
                    ucWeightT1.setExceed(PbCache.collect.weight > PbCache.range.upperRange ? false : true);
                    txtCarNo.Text = PbCache.collect.carno;
                }

                #region 求助按钮控制

                if (PbCache.monitor != null && !string.IsNullOrEmpty(PbCache.monitor.isHelp))
                {
                    switch (PbCache.monitor.isHelp)
                    {
                        case "0": //未呼叫
                            {
                                if (btnHelp.Text != "语音求助")
                                {
                                    btnHelp.BackColor = Color.DodgerBlue;
                                    btnHelp.Text = "语音求助";
                                }
                            }; break;
                        case "1": //呼叫待接听
                            {
                                if (btnHelp.Text != "呼叫中")
                                {
                                    btnHelp.BackColor = Color.Red;
                                    btnHelp.Text = "呼叫中";
                                }
                            }; break;
                        case "2": //呼叫已接听
                            {
                                if (btnHelp.Text != "已接听")
                                {
                                    btnHelp.BackColor = Color.Green;
                                    btnHelp.Text = "已接听";
                                }
                            }; break;
                    }
                }

                #endregion 求助按钮控制

                #region 重量小于500自动关闭界面

                if (PbCache.collect.weight < 500)
                {
                    isCalibration = true;
                    this.Close();
                }
                else
                {
                    //如果处于远程计量状态，且远程保存完成了，则提示保存完成，让司机知道
                    if (PbCache.monitor != null)
                    {
                        if (!string.IsNullOrEmpty(PbCache.monitor.isOverWgt) && !isOverSound && !PbCache.isLockFrm)
                        {
                            txtMsgInfo.Text = "称重完成";
                            vicPlayClass.GetVoicePlay("称重完成", PbCache.lockCarNo);
                            isOverSound = true;
                            Print1(PbCache.monitor.isOverWgt);
                            return;
                        }

                        if (PbCache.monitor.isTakeOver == "2" || !string.IsNullOrEmpty(PbCache.monitor.isOverWgt))
                        {
                            if (PbCache.monitorResult != null && PbCache.monitorResult.valid_wgt && !PbCache.isShowTare)
                            {
                                PbCache.isShowTare = true;
                                RESTfulResult<List<MeterWorkCarActualFirst>> RESTfulResult = workCarActualFirstService.doQueryWf(new MeterWorkCarActualFirst { carNo = PbCache.lockCarNo, valueFlag = "1" });
                                if (RESTfulResult.Succeed && RESTfulResult.Data != null && RESTfulResult.Data.Count > 0)
                                {
                                    txtTare.Text = Math.Round(PbCache.lockWgt / 1000, 2) + "";
                                    txtGroess.Text = "";
                                    txtNet.Text = "";
                                }
                            }
                            btnSubmit.Visible = false;
                            //btnTare.Visible = false;
                            bRelation = true;
                            if (PbCache.monitor.isTakeOver == "2" && !txtMsgInfo.Text.Contains("称重完成"))
                            {
                                txtMsgInfo.Text = "司秤工正在远程计量，请等待处理！！";
                            }
                            return;
                        }
                    }

                    #region 查一次是否校秤，若未校秤则不能计量

                    //*
                    if (bRelation)
                    {
                        string msgInfo = "";
                        isCalibration = vCalib.ValidMethod(new MeterWorkCalibrationMain { baseSpotNo = PbCache.sportInfo.baseSpotNo, valueFlag = "2" }, out msgInfo);
                        bRelation = false;
                    }

                    if (!isCalibration)
                    {
                        MeterBaseCalibraNumRel calibraNumRel = PbCache.ltBaseCalibraNumRel.Where(s => s.baseSpotNo == PbCache.sportInfo.baseSpotNo).FirstOrDefault();
                        if (calibraNumRel == null || calibraNumRel.isMeter == "否" || PbCache.collect.weight > (calibraNumRel.upWeight == null ? 0 : calibraNumRel.upWeight.Value))
                        {
                            if (!bXCStart)
                            {
                                vicPlayClass.GetVoicePlay("未校秤", "");
                                bXCStart = true;
                            }
                            txtMsgInfo.Text = "未校秤无法计量";
                            return;
                        }
                    }
                    //*/

                    #endregion 查一次是否校秤，若未校秤则不能计量

                    #region 扫码获取物料信息并写入到界面

                    if (sCode != PbCache.strCode && !string.IsNullOrEmpty(PbCache.strCode) && PbCache.strCode.Length == 9)
                    {
                        if (!PbCache.strCode.StartsWith("000"))
                        {
                            //以下为普通内倒计量；000开头为临时委托计量
                            lg.WriteLog(5, "进入扫码区域");

                            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 = '" + PbCache.strCode.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 = '" + PbCache.strCode.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 = '" + PbCache.strCode.Substring(0, 3) + @"'
                                   and t2.valid_Flag = '1'";

                            PbModelDbService<List<PbModelDb>> pb = new PbModelDbService<List<PbModelDb>>();
                            RESTfulResult<List<PbModelDb>> rm = pb.executeSqlDataWf(sql);

                            lg.WriteLog(5, "扫码sql：" + sql);
                            if (rm.Succeed && rm.Data.Count == 3)
                            {
                                lg.WriteLog(5, "【中控倒运】查到了扫码数据" + PbCache.strCode);
                                MeterWorkCarActualFirst firstData = new MeterWorkCarActualFirst();
                                firstData.matterNo = rm.Data[2].id;
                                firstData.matterName = rm.Data[2].text;
                                firstData.forwardingUnitNo = rm.Data[0].id;
                                firstData.forwardingUnitName = rm.Data[0].text;
                                firstData.receivingUintNo = rm.Data[1].id;
                                firstData.receivingUintName = rm.Data[1].text;
                                firstData.meterTypeNo = "001006003";
                                firstData.meterTypeName = PbCache.bussinessTypeName;
                                firstData.predictionNo = firstData.matterNo + firstData.forwardingUnitNo + firstData.receivingUintNo;
                                ucCarMeterInfo1.setFormControlValue(firstData);

                                txtMsgInfo.Text = "请仔细核对扫码信息，无误且重量稳定后请点击保存";
                            }
                            else
                            {
                                lg.WriteLog(5, "【中控倒运】扫码信息错误，找不到业务号对应的数据" + PbCache.strCode);
                                txtMsgInfo.Text = "当前扫码信息【" + PbCache.strCode + "】找不到对应的业务编码!";
                            }
                        }
                        else
                        {
                            //临时委托计量
                            PreTrackTemEntrustService temService = new PreTrackTemEntrustService();
                            RESTfulResult<List<PreTrackTemEntrust>> rmTem = temService.doQueryWf(new PreTrackTemEntrust { entrustNo = PbCache.strCode, valueFlag = "0" });
                            if (rmTem.Succeed && rmTem.Data != null && rmTem.Data.Count > 0)
                            {
                                lg.WriteLog(5, "【临时委托】查到了扫码数据" + PbCache.strCode);
                                MeterWorkCarActualFirst firstData = new MeterWorkCarActualFirst();
                                firstData.matterNo = rmTem.Data[0].matterNo;
                                firstData.matterName = rmTem.Data[0].matterName;
                                firstData.forwardingUnitNo = rmTem.Data[0].forwardingUnitNo;
                                firstData.forwardingUnitName = rmTem.Data[0].forwardingUnitName;
                                firstData.receivingUintNo = rmTem.Data[0].receivingUintNo;
                                firstData.receivingUintName = rmTem.Data[0].receivingUintName;
                                firstData.meterTypeNo = "001006003";
                                firstData.meterTypeName = PbCache.bussinessTypeName;
                                firstData.predictionNo = rmTem.Data[0].entrustNo;
                                ucCarMeterInfo1.setFormControlValue(firstData);

                                txtMsgInfo.Text = "请仔细核对扫码信息，无误且重量稳定后请点击保存";
                            }
                            else
                            {
                                lg.WriteLog(5, "【临时委托】扫码信息错误，找不到对应的编码信息" + PbCache.strCode);
                                txtMsgInfo.Text = "当前扫码信息【" + PbCache.strCode + "】找不到对应的临时委托,请点【语音求助】!";
                            }
                        }

                        sCode = PbCache.strCode;
                    }

                    #endregion 扫码获取物料信息并写入到界面
                }

                #endregion 重量小于500自动关闭界面

                #region 第一次查询，有车号，重量稳定，红外验证通过的情况只查一次

                //如果没有查过一次，且扫描到车号信息，且重量稳定
                if ((bRailwayActual || sPreCarNo != PbCache.collect.carno) && PbCache.collect.weightStatus == 0 && !string.IsNullOrEmpty(PbCache.collect.carno) && PbCache.monitorResult.valid_park_status)
                {
                    //这个玩意，一个在过毛的时候显示，这里没取做当前车是否是毛还是皮的验证，所以默认还是放开按钮
                    //ucCarMeterInfo1.BtnCheckVisible = true;
                    //ucCarMeterInfo1.BtnNoVisible = true;
                    firstWgt = 0;
                    fWg = 0;
                    firstDb = null;
                    #region 查询一次该车最近的3条计量历史数据;此处添加trycatch看看还会不会有红叉

                    try
                    {
                        MeterWorkCarActualService mwas = new MeterWorkCarActualService();
                        CommonPage<MeterWorkCarActual> cpc = new CommonPage<MeterWorkCarActual>();
                        MeterWorkCarActual mwca = new MeterWorkCarActual();
                        mwca.carNo = PbCache.collect.carno;
                        mwca.meterTypeName = "中控倒运";
                        cpc.param = mwca;
                        cpc.pageSize = 7;

                        RESTfulResult<DataTable> rm = mwas.doQueryWf(cpc);
                        if (rm.Succeed)
                        {
                            //WriteLog("二次计量数据查询失败！" + rm.ResultMessage);
                            dataTable1.Clear();
                            DataTable dt = dataTable1.Clone();
                            if (rm.Data != null && rm.Data.Rows.Count > 0)
                            {
                                dt = rm.Data;
                                //foreach (DataRow dr in dt.Rows)
                                //{
                                //    dr["grossWeight"] = double.Parse(string.IsNullOrEmpty(dr["grossWeight"].ToString()) ? "0" : dr["grossWeight"].ToString()) / 1000; //tareWeight；netWeight
                                //    dr["tareWeight"] = double.Parse(string.IsNullOrEmpty(dr["tareWeight"].ToString()) ? "0" : dr["tareWeight"].ToString()) / 1000;
                                //    dr["netWeight"] = double.Parse(string.IsNullOrEmpty(dr["netWeight"].ToString()) ? "0" : dr["netWeight"].ToString()) / 1000;
                                //}
                            }
                            ClsControlPack.CopyDataToDatatable(ref dt, ref this.dataTable1, true);
                            foreach (var item in this.maintableult.Rows)
                            {
                                item.Cells["grossWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["grossWeight"].Value.ToString()) ? "0" : item.Cells["grossWeight"].Value.ToString()) / 1000;
                                item.Cells["tareWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["tareWeight"].Value.ToString()) ? "0" : item.Cells["tareWeight"].Value.ToString()) / 1000;
                                item.Cells["netWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["netWeight"].Value.ToString()) ? "0" : item.Cells["netWeight"].Value.ToString()) / 1000;
                            }
                            ClsControlPack.RefreshAndAutoSize(maintableult);
                        }
                    }
                    catch (Exception ex)
                    {
                        lg.WriteLog(13, "内倒二次计量数据查询异常，车号【" + PbCache.collect.carno + "】！异常信息：" + ex);
                    }

                    #endregion 查询一次该车最近的3条计量历史数据;此处添加trycatch看看还会不会有红叉

                    #region 查询一次计量表中是否存在一条未结净的数据

                    double iAddWgt = 0;
                    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)
                        {
                            firstWgt = RESTfulResult.Data[0].meterWeight.Value;
                            iAddWgt = RESTfulResult.Data[0].addWeight == null ? 0 : RESTfulResult.Data[0].addWeight.Value;
                            fWg = firstWgt;
                            firstDb = RESTfulResult.Data[0];
                            //给用户控件设置值
                            ucCarMeterInfo1.setFormControlValue(firstDb);
                        }

                        //*/
                        bRailwayActual = false;
                    }
                    if (iAddWgt > 0 && PbCache.addWgt == 0)
                    {
                        PbCache.addWgt = iAddWgt;
                    }

                    #endregion 查询一次计量表中是否存在一条未结净的数据

                    //bRailwayActual = false;
                }

                #endregion 第一次查询，有车号，重量稳定，红外验证通过的情况只查一次

                #region 界面未锁定情况下，保存按钮的控制

                //界面未锁定的情况下
                if (!PbCache.isLockFrm)
                {
                    //界面未锁定的情况下，有车号，如果重量稳定了,停车线验证通过，未超量程的情况下，则按钮可用
                    if (!string.IsNullOrEmpty(PbCache.collect.carno) && PbCache.collect.weightStatus == 0 && PbCache.monitorResult.valid_park_status && ucWeightT1.isGrennExceed)
                    {
                        if (!btnSubmit.Visible)
                        {
                            btnSubmit.Visible = true;
                            btnTare.Visible = true;
                        }
                        if (!ucCarMeterInfo1.BtnNoVisible)
                        {
                            ucCarMeterInfo1.BtnNoVisible = true;
                        }

                        if (!isVoiceDownCar)
                        {
                            isVoiceDownCar = true;
                            vicPlayClass.GetVoicePlay("车上人员请下车", PbCache.collect.carno);
                        }
                    }
                    else
                    {
                        if (btnSubmit.Visible)
                        {
                            btnSubmit.Visible = false;
                            btnTare.Visible = false;
                            ucCarMeterInfo1.BtnCheckVisible = false;
                            ucCarMeterInfo1.BtnNoVisible = false;
                        }
                    }
                }

                #region 判断是否需要复磅

                if (isShowRecover && !string.IsNullOrEmpty(txtCarNo.Text))
                {
                    recoverInfo.ValidMethod(txtCarNo.Text);
                    if (PbCache.isAllowRecover)
                    {
                        btnRecover.Visible = true;
                    }
                    else
                    {
                        btnRecover.Visible = false;
                    }
                    isShowRecover = false;
                }

                #endregion 判断是否需要复磅

                #endregion 界面未锁定情况下，保存按钮的控制

                #region

                //(firstWgt < 500 || sPreCarNo != PbCache.collect.carno) //没有一次计量数据的情况下
                if (fWg < 500 && !string.IsNullOrEmpty(PbCache.collect.carno) && ucCarMeterInfo1.lp != null && ucCarMeterInfo1.lp.Count > 0)
                {
                    //如果车号，物料编号，收发货单位编号有任意一个发生变化，则带出来的期限皮重将变化
                    if ((strMatNo != ucCarMeterInfo1.lp[0].text || strSndNo != ucCarMeterInfo1.lp[2].text || strRecNo != ucCarMeterInfo1.lp[4].text)
                         || sPreCarNo != PbCache.collect.carno)
                    {
                        firstWgt = 0;
                        strMatNo = ucCarMeterInfo1.lp[0].text;
                        strSndNo = ucCarMeterInfo1.lp[2].text;
                        strRecNo = ucCarMeterInfo1.lp[4].text;

                        string sql = @"select matter_no id, matter_name text
                              from meter_base_matter_info where matter_no='" + ucCarMeterInfo1.lp[0].text + "' and allowed_tare_weight='1'";

                        PbModelDbService<List<PbModelDb>> pbModelDbService = new PbModelDbService<List<PbModelDb>>();
                        RESTfulResult<List<PbModelDb>> rm = pbModelDbService.executeSqlDataWf(sql);
                        if (rm.Succeed)
                        {
                            txtTare.Text = "0";
                            if (rm.Data != null && rm.Data.Count > 0)
                            {
                                RESTfulResult<List<MeterBaseTermTareData>> rmD = termTareDate.doQueryWf(new MeterBaseTermTareData { carNo = PbCache.collect.carno });
                                if (rmD.Succeed)
                                {
                                    if (rmD.Data != null && rmD.Data.Count > 0)
                                    {
                                        firstWgt = rmD.Data[0].meterWeight.Value;
                                    }
                                }
                            }
                        }
                    }
                }

                sPreCarNo = PbCache.collect.carno;

                #endregion

                #region 这里设置下毛/皮/净

                if (firstWgt > 0)
                {
                    if (PbCache.lockWgt > 0)
                    {
                        if (Math.Abs(firstWgt - PbCache.lockWgt) > AppConfigCache.differenceWgt)
                        {
                            if (firstWgt > PbCache.lockWgt)
                            {
                                txtGroess.Text = Math.Round(firstWgt / 1000, 2) + ""; //2021年5月10日界面显示单位，调整为T
                                txtTare.Text = Math.Round(PbCache.lockWgt / 1000, 2) + "";
                            }
                            else
                            {
                                txtTare.Text = Math.Round(firstWgt / 1000, 2) + "";
                                txtGroess.Text = Math.Round(PbCache.lockWgt / 1000, 2) + "";
                            }
                        }
                        else
                        {
                            txtTare.Text = "";
                            txtGroess.Text = "";
                            txtNet.Text = "";
                        }
                    }
                    else
                    {
                        if (Math.Abs(firstWgt - PbCache.collect.weight) > AppConfigCache.differenceWgt)
                        {
                            if (firstWgt > PbCache.collect.weight)
                            {
                                txtGroess.Text = Math.Round(firstWgt / 1000, 2) + "";
                                txtTare.Text = Math.Round((double)PbCache.collect.weight / 1000, 2) + "";
                            }
                            else
                            {
                                txtTare.Text = Math.Round(firstWgt / 1000, 2) + "";
                                txtGroess.Text = Math.Round((double)PbCache.collect.weight / 1000, 2) + "";
                            }
                        }
                        else
                        {
                            txtTare.Text = "";
                            txtGroess.Text = "";
                            txtNet.Text = "";
                        }
                    }
                    if (txtGroess.Text.Trim() != "" && txtTare.Text.Trim() != "")
                    {
                        try
                        {
                            //txtNet.Text = (Convert.ToInt32(txtGroess.Text.Trim()) - Convert.ToInt32(txtTare.Text.Trim()) - Convert.ToInt32((double)PbCache.addWgt / 1000)) + "";
                            txtNet.Text = Math.Round(Convert.ToDouble(txtGroess.Text.Trim()) - Convert.ToDouble(txtTare.Text.Trim()) - Convert.ToDouble((double)PbCache.addWgt / 1000), 2) + "";
                        }
                        catch (Exception ex)
                        {
                            lg.WriteLog(13, PbCache.lockCarNo + "重量计算事件异常：" + ex.Message);
                        }
                    }
                }
                else
                {
                    txtGroess.Text = "";
                    txtTare.Text = "";
                    txtNet.Text = "";
                }
            }
            catch (Exception ex)
            {
                lg.WriteLog(13, PbCache.lockCarNo + "内倒timer1事件异常：" + ex.Message);
            }
            #endregion
        }

        /// <summary>
        /// 界面关闭时，需将一些线程以及一些参数进行关闭或初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmInternalTransport_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                //初始化一些线程及数据，并关闭该界面
                if (PbCache.collect != null && !string.IsNullOrEmpty(PbCache.collect.carno))
                {
                    PbCache.collect.carno = "";
                }
                isShowRecover = true;//是否去查询“复磅”按钮的显示与否
                PbCache.strCode = "";
                PbCache.Load();
                //关闭一些线程及定时任务
                timer1.Stop();
                timer1.Dispose();

                #region 清理一次监控表的几个数值，防止上车速度过快导致提示称重完成

                //RESTfulResult<string> rms = monitor.doUpdateWf(new MeterWorkMonitor { pointNo = PbCache.sportInfo.baseSpotNo, isOverWgt = "", editCar = "" });
                RESTfulResult<string> rms = monitor.doUpdateWf(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 = "",
                    isOverWgt = "",
                    isHelp = "0",
                    wgt = 0
                });

                #endregion

                ucCarMeterInfo1.ClosingFrm();
            }
            catch (Exception ex)
            {
                lg.WriteLog(0, "frmInternalTransport_FormClosing异常：下秤关闭界面异常！异常信息：" + ex);
            }
        }

        /// <summary>
        /// 实绩数据列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void maintableult_Click(object sender, EventArgs e)
        {
            if (PbCache.isLockFrm) return; //2021年6月16日 称重完成后，不让点下面的数据项
            UltraGridRow ugr = maintableult.ActiveRow;
            if (ugr != null)
            {
                if (firstDb == null || firstDb.weightType != "0")
                {
                    ucCarMeterInfo1.setFormControlValue(ugr);
                }
            }
        }

        private void btnTare_Click(object sender, EventArgs e)
        {
            try
            {
                //界面锁定
                PbCache.lockWgt = PbCache.collect.weight;
                PbCache.lockCarNo = PbCache.collect.carno;
                btnTare.Enabled = false;
                lg.WriteLog(15, PbCache.lockCarNo + "点击了期限皮重保存按钮【内倒界面】");

                //2021年3月13日 杨秀东新增逻辑，车号为空则不允许进行期限皮重保存操作
                if (string.IsNullOrEmpty(PbCache.collect.carno))
                {
                    vicPlayClass.GetVoicePlay("不允许进行期限皮重保存", PbCache.collect.carno);
                    PbCache.ResultMessage = "未抓拍到车牌号，进行期限皮重保存，请点[语音求助]！";
                    setMsg(PbCache.ResultMessage);
                    btnTare.Enabled = true;
                    return;
                }

                //*
                //查一次是否可留期限皮
                if (!termTareCar.ValidMethod(PbCache.collect.carno))
                {
                    vicPlayClass.GetVoicePlay("不允许进行期限皮重保存", PbCache.collect.carno);
                    setMsg(PbCache.ResultMessage);
                    btnTare.Enabled = true;
                    return;
                }
                //*/

                //暂停取实时数据
                setMsg("称重保存中......");
                FrmMessage frmMessage = FrmMess("是否确认保存期限皮重！", "继续保存");
                if (frmMessage.ShowDialog(this) == DialogResult.Cancel)
                {
                    setMsg("");
                    btnTare.Enabled = true;
                    lg.WriteLog(15, PbCache.lockCarNo + "期限皮重保存按钮选择了【否】【内倒界面】");
                    return;
                }

                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 = "0";

                //期限皮重数据保存
                RESTfulResult<string> RESTfulResult = termTareDate.doSaveWf(mbttd, monitorNote);
                if (RESTfulResult.Succeed)
                {
                    //保存成功，语音提示保存成功
                    vicPlayClass.GetVoicePlay("期限皮重保存成功", PbCache.lockCarNo);//播放语音
                    btnTare.Visible = false;
                    lg.WriteLog(3, string.Format("车号[{0}]期限皮重保存成功", PbCache.lockCarNo));
                    setMsg("称重保存成功，请离开秤台！");
                }
                else
                {
                    btnTare.Enabled = true;
                    setMsg(RESTfulResult.ResultMessage);
                    vicPlayClass.GetVoicePlay("期限皮重保存失败", PbCache.lockCarNo);//播放语音
                    lg.WriteLog(3, string.Format("车号[{0}]期限皮重保存失败", PbCache.lockCarNo));
                }
            }
            catch (Exception ex)
            {
                lg.WriteLog(13, PbCache.lockCarNo + "期限皮重事件异常【内倒业务】：" + ex.Message);
            }
        }

        #region 信息提示框

        public void setMsgInfo(string ResultMessage)
        {
            setMsg(ResultMessage);
        }

        private void setMsg(string ResultMessage)
        {
            if (txtMsgInfo.InvokeRequired)
            {
                Action<string> action = new Action<string>(setMsgInfo);
                Invoke(action, new object[] { ResultMessage });
            }
            else
            {
                txtMsgInfo.Text = ResultMessage;
            }
            //2021年3月13日新增提示信息日志记录
            if (!string.IsNullOrEmpty(ResultMessage) && PbCache.collect != null)
            {
                lg.WriteLog(9, "[" + PbCache.collect.carno + "]" + ResultMessage);
            }
        }

        #endregion

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

        /// <summary>
        /// 语音求助
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHelp_Click(object sender, EventArgs e)
        {
            if (PbCache.monitor.isHelp == "0")
            {
                RESTfulResult<string> rms = monitor.doUpdateWf(new MeterWorkMonitor { pointNo = PbCache.sportInfo.baseSpotNo, isHelp = "1" }); //, isTakeOver = "1"
                if (!rms.Succeed)
                {
                    lg.WriteLog(3, "求助写入失败");
                }
                lg.WriteLog(15, PbCache.lockCarNo + "点击了语音求助按钮【内倒界面】");
            }
        }

        #region 打印

        private string strFirstNo = "";

        private class PrintCls
        {
            public int printNum { get; set; }
            public MeterWorkCarActual printDb { get; set; }
            public int iType { get; set; } //0毛 1 皮 2净
            public string qrCode { get; set; }
        }

        private PrintCls printData = new PrintCls();

        private void ucCarMeterInfo1_Load(object sender, EventArgs e)
        {
        }

        private void Print1(string firstNo)
        {
            try
            {
                //lg.WriteLog(10, "打印开始");

                #region 获取打印信息，若需要打印则调用打印操作

                List<PrintCls> prrintC = new List<PrintCls>();

                string sql = @"select actual_no actualNo,
                                   prediction_no predictionNo,
                                   car_no carNo,
                                   matter_no matterNo,
                                   matter_name matterName,
                                   gross_weight grossWeight,
                                   gross_time grossTime,
                                   tare_weight tareWeight,
                                   tare_time tareTime,
                                   net_weight netWeight,
                                   net_time netTime,
                                   'x' meterTypeNo,
                                   meter_type_name meterTypeName,
                                   spec_name specName,
                                   forwarding_unit_name forwardingUnitName,
                                   receiving_uint_name receivingUintName,
                                   load_point_name loadPointName,
                                   add_weight addWeight,
                                   '1' uploadFlag --1结净数据 0一次表数据
                              from meter_work_car_actual where actual_first1_no = '" + firstNo + @"' or actual_first2_no='" + firstNo + @"'
                            union all
                            select t.actual_first_no      actualNo,
                                   t.prediction_no        predictionNo,
                                   t.car_no               carNo,
                                   t.matter_no            matterNo,
                                   t.matter_name          matterName,
                                   t.meter_weight         grossWeight,
                                   t.create_time          grossTime,
                                   0                      tareWeight,
                                   t.create_time          tareTime,
                                   0                      netWeight,
                                   null                   netTime,
                                   t.weight_type          meterTypeNo, --0毛重 否则皮重
                                   t.meter_type_name      meterTypeName,
                                   t.spec_name            specName,
                                   t.forwarding_unit_name forwardingUnitName,
                                   t.receiving_uint_name  receivingUintName,
                                   t.load_point_name      loadPointName,
                                   t.add_weight addWeight,
                                   '0' uploadFlag
                              from METER_WORK_CAR_ACTUAL_FIRST t
                             where t.actual_first_no = '" + firstNo + "' or  t.actual_first_no = (select max(actual_first2_no) from meter_work_car_actual where actual_first1_no='" + firstNo + "')";
                //查下如果有毛重或者结净数据，则可进入打印判断
                PbModelDbService<List<MeterWorkCarActual>> pbModelDbService = new PbModelDbService<List<MeterWorkCarActual>>();
                RESTfulResult<List<MeterWorkCarActual>> rm = pbModelDbService.executeSqlDataWf(sql);
                if (rm.Succeed)
                {
                    if (rm.Data != null && rm.Data.Count > 0)
                    {
                        lg.WriteLog(10, "车号【" + PbCache.lockCarNo + "】打印开始第一个SQL");
                        //若有毛重或者净重，找到对应数据的物料信息，若有，那么去找打印配置信息数据
                        List<MeterWorkCarActual> mwa = rm.Data.Where(s => !string.IsNullOrEmpty(s.matterNo) && (s.meterTypeNo == "x" || s.meterTypeNo == "0")).ToList();
                        if (mwa != null && mwa.Count > 0 && !string.IsNullOrEmpty(mwa[0].matterNo))
                        {
                            sql = @"select BASE_SPOT_NO    baseSpotNo,
                                           load_point_no   loadPointNo,
                                           matter_no       matterNo,
                                           METER_TYPE_NO   meterTypeNo,
                                           weight_type_name weightTypeName,
                                           PRINT_NUM       printNum
                                      from METER_BASE_BILL_PRINT
                                     where matter_no = '" + mwa[0].matterNo + @"'
                                       and nvl(METER_TYPE_NO, '001006003') = '001006003'
                                       and nvl(BASE_SPOT_NO, '" + PbCache.sportInfo.baseSpotNo + @"') = '" + PbCache.sportInfo.baseSpotNo + @"'
                                       and nvl(load_point_no, '" + (mwa[0].loadPointNo == null ? "1" : mwa[0].loadPointNo) + @"') = '" + (mwa[0].loadPointNo == null ? "1" : mwa[0].loadPointNo) + @"'";
                            //and nvl(METER_TYPE_NO, '') = ''
                            PbModelDbService<List<MeterBaseBillPrint>> pbPrintService = new PbModelDbService<List<MeterBaseBillPrint>>();
                            RESTfulResult<List<MeterBaseBillPrint>> rmPint = pbPrintService.executeSqlDataWf(sql);
                            if (rmPint.Succeed)
                            {
                                if (rmPint.Data != null && rmPint.Data.Count > 0)
                                {
                                    lg.WriteLog(1, "车号【" + PbCache.lockCarNo + "】打印开始2");
                                    //若有净重信息：1毛重时间晚于皮重时间，则打印毛、皮、净重，2毛重早于皮重，打印皮、净
                                    //若只有毛重信息则打印毛重
                                    List<MeterBaseBillPrint> lGrossprint = rmPint.Data.Where(s => s.weightTypeName.Contains("毛")).ToList();
                                    List<MeterBaseBillPrint> lTarePrint = rmPint.Data.Where(s => s.weightTypeName.Contains("皮")).ToList();
                                    List<MeterBaseBillPrint> lNetprint = rmPint.Data.Where(s => s.weightTypeName.Contains("净")).ToList();

                                    List<MeterWorkCarActual> mwaChild = mwa.Where(s => s.meterTypeNo == "x").ToList();
                                    if (mwaChild != null && mwaChild.Count > 0) //若有净重信息
                                    {
                                        if (lTarePrint != null && lTarePrint.Count > 0)
                                        {
                                            //获取非毛，非净重信息如果没有则用的期限皮，此时不打，否则则打印
                                            MeterWorkCarActual mwca = rm.Data.Where(s => s.meterTypeNo != "x" && s.meterTypeNo != "0").FirstOrDefault();
                                            if (mwca != null)
                                            {
                                                PrintCls cls = new PrintCls();
                                                cls.printNum = (int)(lTarePrint[0].printNum == null ? 0 : lTarePrint[0].printNum.Value);
                                                cls.iType = 1;//皮重
                                                cls.printDb = mwca;
                                                prrintC.Add(cls);
                                            }
                                        }
                                        if (lGrossprint != null && lGrossprint.Count > 0)
                                        {
                                            //获取毛重信息
                                            MeterWorkCarActual mwca = rm.Data.Where(s => s.meterTypeNo == "0").FirstOrDefault();
                                            if (mwca != null)
                                            {
                                                PrintCls cls = new PrintCls();
                                                cls.printNum = (int)(lGrossprint[0].printNum == null ? 0 : lGrossprint[0].printNum.Value);
                                                cls.iType = 0;//毛重
                                                cls.printDb = mwca;
                                                prrintC.Add(cls);
                                            }
                                        }
                                        if (lNetprint != null && lNetprint.Count > 0)
                                        {
                                            //获取净重信息
                                            MeterWorkCarActual mwca = rm.Data.Where(s => s.meterTypeNo == "x").FirstOrDefault();
                                            if (mwca != null)
                                            {
                                                PrintCls cls = new PrintCls();
                                                cls.printNum = (int)(lNetprint[0].printNum == null ? 0 : lNetprint[0].printNum.Value);
                                                cls.iType = 2;//净重
                                                cls.printDb = mwca;
                                                prrintC.Add(cls);
                                            }
                                        }
                                    }
                                    else //只有毛重信息则打印毛重
                                    {
                                        if (lGrossprint != null && lGrossprint.Count > 0)
                                        {
                                            //获取毛重信息
                                            MeterWorkCarActual mwca = rm.Data.Where(s => s.meterTypeNo == "0").FirstOrDefault();
                                            if (mwca != null)
                                            {
                                                PrintCls cls = new PrintCls();
                                                cls.printNum = (int)(lGrossprint[0].printNum == null ? 0 : lGrossprint[0].printNum.Value);
                                                cls.iType = 0;//毛重
                                                cls.printDb = mwca;
                                                prrintC.Add(cls);
                                            }
                                        }
                                    }
                                    if (prrintC != null && prrintC.Count > 0)
                                    {
                                        FrmMessage frmMessage = FrmMess("是否打印第【1】张票据！", "打印");
                                        if (frmMessage.ShowDialog(this) == DialogResult.OK)
                                        {
                                            lg.WriteLog(10, "车号【" + PbCache.lockCarNo + "】是否打印选择了【是】");

                                            strFirstNo = firstNo;
                                            //printDocument1.PrinterSettings.PrinterName = PbCache.sportInfo.printerName;//strPntSvrName;
                                            System.Drawing.Printing.PaperSize customSize1 = new System.Drawing.Printing.PaperSize("TestPaper", 398, 433); //101mm*110mm,换算成英寸
                                            printDocument1.DefaultPageSettings.PaperSize = customSize1;//将自定义的Papersize赋给PrintDocument
                                            System.Drawing.Printing.Margins marginss = new System.Drawing.Printing.Margins(0, 0, 0, 0);
                                            printDocument1.DefaultPageSettings.Margins = marginss;
                                            printDocument1.PrintController = new System.Drawing.Printing.StandardPrintController();

                                            foreach (PrintCls db in prrintC)
                                            {
                                                switch (db.printDb.meterTypeNo)
                                                {
                                                    case "0": //毛
                                                        db.qrCode = db.printDb.actualNo + "," + db.printDb.grossWeight + "," + "1";
                                                        break;

                                                    case "x": //净
                                                        db.qrCode = db.printDb.actualNo + "," + db.printDb.netWeight + "," + "2";
                                                        break;

                                                    default: //皮
                                                        db.qrCode = db.printDb.actualNo + "," + db.printDb.grossWeight + "," + "1";
                                                        break;
                                                }
                                                RESTfulResult<string> rQRCode = workCarActualFirstService.doQRCodeWf(db.qrCode);
                                                db.qrCode = rQRCode.Data;

                                                for (int i = 0; i < db.printNum; i++)
                                                {
                                                    if (i == 0)
                                                    {
                                                        printData = db;
                                                        printDocument1.Print();
                                                        lg.WriteLog(10, "当前第" + (i + 1) + "次打印：" + printData.iType + "  车号：" + db.printDb.carNo + ",二维码:" + db.qrCode);
                                                    }
                                                    else
                                                    {
                                                        FrmMessage frmMessageContinue = FrmMess("是否继续打印第【" + (i + 1) + "】张票据！", "打印");
                                                        if (frmMessageContinue.ShowDialog(this) == DialogResult.OK)
                                                        {
                                                            printData = db;
                                                            printDocument1.Print();
                                                            lg.WriteLog(10, "当前第" + (i + 1) + "次打印：" + printData.iType + "  车号：" + db.printDb.carNo + ",二维码:" + db.qrCode);
                                                        }
                                                        else
                                                        {
                                                            lg.WriteLog(10, "车号【" + PbCache.lockCarNo + "】第" + i + "次是否打印，选择了【否】");
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            lg.WriteLog(10, "车号【" + PbCache.lockCarNo + "】是否打印，选择了【否】");
                                        }
                                    }
                                }
                            }
                            else
                            {
                                lg.WriteLog(10, "车号【" + PbCache.lockCarNo + "】获取打印配置数据信息异常sql:【" + sql + "】");
                            }
                        }
                    }
                }
                else
                {
                    lg.WriteLog(10, "车号【" + PbCache.lockCarNo + "】获取计量数据信息异常sql:【" + sql + "】");
                }

                #endregion
            }
            catch (Exception ex)
            {
                lg.WriteLog(10, "车号【" + PbCache.lockCarNo + "】打印异常" + ex);
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                if (printData != null && printData.printDb != null)
                {
                    printClass.PrintAllPage(e, printData.printDb, printData.qrCode);
                }
            }
            catch (Exception ex)
            {
                lg.WriteLog(3, "打印异常");
            }
        }

        #endregion

        private void btnFH_Click(object sender, EventArgs e)
        {
            lg.WriteLog(15, PbCache.lockCarNo + "点击返回主界面【内倒界面】");
            this.Close();
        }
    }
}