using Common;
using MeterConditionLibrary;
using MeterPlugInLibrary;
using MeterSceneLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using com.hnshituo.core.webapp.vo;
using CarMeterSystem.OptionCls;

namespace CarMeterSystem
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        Print printClass = new Print();//打印
        validTermTareCar termTareCar = new validTermTareCar();//验证是否可留期限皮
        MeterBaseTermTareDataService termTareDate = new MeterBaseTermTareDataService();//留期限皮操作
        MeterWorkMonitorService monitor = new MeterWorkMonitorService(); //设备及远程呼叫监控表
        MeterWorkCarActualFirst firstDb = null;//一次计量数据
        SceneControl inner = new SceneControl(); //内倒业务处理
        PreTrackScaleService trackService = new PreTrackScaleService();//查询预报信息
        validPrediction validPred = new validPrediction(); //验证预报信息
        VoicePlay vicPlayClass = new VoicePlay();//语音播放
        Log lg = Log.GetInstance(); //写日志

        double firstWgt = 0;
        bool bRailwayActual = true;
        bool isVoiceDownCar = false;//车上人员请下车播放一次
        int iCollection = 0, licType = 0;
        string firstCode = "";//上次扫码编号
        string TrackCarNo = "";//预报车号

        private void frmCarSalePurchase_Load(object sender, EventArgs e)
        {
            lbPointName.Text = PbCache.sportInfo.baseSpotName;
            ucCarMeterInfo21.setMeterType(PbCache.bussinessTypeName);
        }

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

            PbCache.lockCarNo = PbCache.collect.carno;
            btnSave.Enabled = false;
            FrmMessage frmMessage = FrmMess("是否确认保存当前计量数据！");
            if (frmMessage.ShowDialog(this) == DialogResult.Cancel)
            {
                PbCache.isLockFrm = false;
                btnSave.Enabled = true;
                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;
                        btnSave.Enabled = true;
                        return;
                    }
                }
                else
                {
                    PbCache.ResultMessage = "保存失败，获取黑名单数据异常，请稍后再试";
                    lg.WriteLog(3, "获取黑名单数据异常，请稍后再试");

                    PbCache.isLockFrm = false;
                    btnSave.Enabled = true;
                    return;
                }

                PreTrackScale preTrack = ucCarMeterInfo21._preTrack;
                string strMsg = "";
                if (inner.WeightMeter(preTrack, out strMsg))  //meterTypeNo  "001006001","001006002"
                {
                    //票据打印
                    Print1(PbCache.actualFirstNo);
                    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\\tempImg\\{1}_{2}_{3}",
                            AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                            PbCache.sportInfo.baseSpotNo,
                            PbCache.actualFirstNo,
                            (PbCache.videoChild.Count + 1)), System.Drawing.Imaging.ImageFormat.Jpeg);

                        //*
                        //最后进行截图操作
                        CameraShotCls cameraShot = new CameraShotCls();
                        cameraShot.CapMethod(PbCache.actualFirstNo);
                        //*/
                        #endregion
                    }
                    catch (Exception ex)
                    {

                    }
                    btnFH.Enabled = false;
                }
                else
                {
                    btnSave.Enabled = true;
                }


                vicPlayClass.GetVoicePlay(strMsg, PbCache.lockCarNo);
                //提示信息，
                //txtMsgInfo.Text = PbCache.ResultMessage;
                lblog = PbCache.ResultMessage;

                #region LED写入
                PbCache.ledInfo = string.Format("计量完成，车号：{0}，车重：{1}，物资：{2}", PbCache.lockCarNo, PbCache.lockWgt, preTrack != null ? preTrack.matterName : "");
                #endregion
            }
            catch (Exception ex)
            {
                //语音播报
                vicPlayClass.GetVoicePlay("称重数据保存失败", PbCache.lockCarNo);
                //提示信息，
                //txtMsgInfo.Text = "称重数据保存失败";
                lblog = "称重数据保存失败";
                lg.WriteLog(3, PbCache.lockCarNo + "称重保存失败：" + ex.Message);
            }
        }

        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" });
                if (!rms.Succeed)
                {
                    lg.WriteLog(3, PbCache.lockCarNo + "求助写入失败");
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            #region 采集线程中断超过30秒则自动关闭界面
            /*
            if (licType == PbCache.collect.licType)
            {
                iCollection++;
                if (iCollection > 30) //若连续30秒采集不到数据则关闭界面
                {
                    this.Close();
                }
            }
            else
            {
                iCollection = 0;
            }
            licType = PbCache.collect.licType;
            //*/
            #endregion


            #region 查询扫码信息
            if (string.IsNullOrEmpty(PbCache.strCode))
            {
                firstCode = "";
            }
            else
            {
                if (firstCode != PbCache.strCode)
                {
                    firstCode = "";
                    //将预报信息查出来，然后写入到界面
                    RESTfulResult<List<PreTrackScale>> rm = trackService.doQueryWf(new PreTrackScale { predictionNo = PbCache.strCode });
                    if (rm.Succeed)
                    {
                        if (rm.Data == null || rm.Data.Count == 0)
                        {
                            //未找到预报信息，预报已删除
                            vicPlayClass.GetVoicePlay("未找到有效预报", PbCache.collect.carno);
                        }
                        else
                        {
                            string ResultMessage = "";
                            //验证预报信息
                            if (validPred.ValidMethod(rm.Data[0], out ResultMessage))
                            {
                                //预报验证无误，则将预报信息写入到用户控件
                                TrackCarNo = rm.Data[0].carNo;
                                ucCarMeterInfo21.setFormControlValue(rm.Data[0]);//预报信息写入界面
                                firstCode = PbCache.strCode;
                            }
                            else
                            {
                                //播报语音，提示预报异常
                                vicPlayClass.GetVoicePlay(ResultMessage, PbCache.collect.carno);
                                lblog = PbCache.ResultMessage;
                            }
                        }
                    }
                    else
                    {
                        lg.WriteLog(1, "查询预报编号异常");
                        vicPlayClass.GetVoicePlay("未找到有效预报", PbCache.collect.carno);
                        lblog = "获取预报失败!";

                    }
                }
            }
            #endregion

            #region 第一次查询，有车号，重量稳定，红外验证通过的情况只查一次
            //如果没有查过一次，且扫描到车号信息，且重量稳定
            if (bRailwayActual && PbCache.collect.weightStatus == 0 && !string.IsNullOrEmpty(PbCache.collect.carno) && PbCache.monitorResult.valid_park_status)
            {
                #region 查询一次计量表中是否存在一条未洁净的数据，非一车联运情况扫码两次，一车联运的话
                MeterWorkCarActualFirstService workCarActualFirstService = new MeterWorkCarActualFirstService();
                RESTfulResult<List<MeterWorkCarActualFirst>> RESTfulResult = workCarActualFirstService.doQueryWf(new MeterWorkCarActualFirst { carNo = PbCache.collect.carno, valueFlag = "1" });
                if (RESTfulResult.Succeed)
                {
                    if (RESTfulResult.Data != null && RESTfulResult.Data.Count > 0)
                    {
                        firstWgt = RESTfulResult.Data[0].meterWeight.Value;

                        if (RESTfulResult.Data[0].weightType == "0")
                        {
                            txtGroess.Text = RESTfulResult.Data[0].meterWeight.Value + "";
                        }
                        else
                        {
                            txtTare.Text = RESTfulResult.Data[0].meterWeight.Value + "";
                        }
                        firstDb = RESTfulResult.Data[0];
                        //给用户控件设置值
                        ucCarMeterInfo21.setFormControlValue(firstDb);
                    }

                    bRailwayActual = false;
                }

                #endregion

                #region 查一次是否可留期限皮，可以则显示按钮
                /*
                if (termTareCar.ValidMethod(PbCache.collect.carno))
                {
                    btnTare.Visible = true;
                }
                //*/
                #endregion
            }
            #endregion

            #region 毛皮净赋值
            if (PbCache.collect.weightStatus == 0 && PbCache.collect.carno != null && PbCache.collect.carno != "")
            {
                if (Math.Abs(PbCache.collect.weight - firstWgt) >= AppConfigCache.differenceWgt)
                {
                    if (PbCache.collect.weight > firstWgt)
                    {
                        txtGroess.Text = PbCache.collect.weight + "";
                        txtTare.Text = firstWgt + "";
                    }
                    else
                    {
                        txtTare.Text = PbCache.collect.weight + "";
                        txtGroess.Text = firstWgt + "";
                    }

                    txtNet.Text = Math.Abs(PbCache.collect.weight - firstWgt) + "";
                }
            }
            #endregion

            #region 界面未锁定情况下，保存按钮的控制
            //界面未锁定的情况下
            if (!PbCache.isLockFrm)
            {
                ucWeightT1.setWgt(PbCache.collect.weight);
                ucWeightT1.setStable(PbCache.collect.weightStatus != 1 ? true : false);
                ucWeightT1.setExceed(PbCache.collect.weight > PbCache.range.upperRange ? false : true);
                txtCarNo.Text = PbCache.collect.carno;

                //界面未锁定的情况下，如果，有车号，重量稳定了,停车线验证通过，完成了扫码验证的情况下，则按钮可用
                if (!string.IsNullOrEmpty(PbCache.collect.carno) && PbCache.collect.weightStatus == 0 && !string.IsNullOrEmpty(firstCode) && PbCache.monitorResult.valid_park_status && ucWeightT1.isGreenWgt)
                {
                    if (!btnSave.Visible)
                    {
                        btnSave.Visible = true;
                    }
                    if (!isVoiceDownCar)
                    {
                        isVoiceDownCar = true;
                        vicPlayClass.GetVoicePlay("车上人员请下车", PbCache.collect.carno);
                    }

                }
                else
                {
                    if (btnSave.Visible)
                    {
                        btnSave.Visible = false;
                    }
                }
            }
            #endregion

            #region 求助按钮控制
            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 信息提示框
        private string lblog;//信息显示
        public string Lblog//信息显示
        {
            get { return lblog; }
            set
            {
                lblog = value;
                DoShowlbLog(value);
            }
        }
        private delegate void ShowlbLog(string lblog);
        private void DoShowlbLog(string _lbLog)
        {
            if (this.txtMsgInfo.InvokeRequired)
            {//在线程里以安全方式调用控件
                ShowlbLog _MyInvokeOne = new ShowlbLog(DoShowlbLog);
                txtMsgInfo.Invoke(_MyInvokeOne, new object[] { _lbLog });
            }
            else
            {
                txtMsgInfo.Text = _lbLog;
            }
        }
        #endregion

        private void frmCarSalePurchase_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭一些线程及定时任务
            timer1.Enabled = false;
            //初始化一些线程及数据，并关闭该界面
            PbCache.Load();
        }

        #region 打印
        string strFirstNo = "";
        private void Print1(string firstNo)
        {
            try
            {
                strFirstNo = firstNo;
                System.Drawing.Printing.PaperSize customSize1 = new System.Drawing.Printing.PaperSize("TestPaper", 300, 480); //101mm*110mm,换算成英寸
                printDocument1.DefaultPageSettings.PaperSize = customSize1;//将自定义的Papersize赋给PrintDocument
                printDocument1.DefaultPageSettings.PrinterSettings.PrinterName = PbCache.sportInfo.printerName;//strPntSvrName;
                System.Drawing.Printing.Margins marginss = new System.Drawing.Printing.Margins(0, 0, 0, 0);
                printDocument1.DefaultPageSettings.Margins = marginss;
                printDocument1.Print();
            }
            catch (Exception ex)
            {
                lg.WriteLog(3, "打印异常");
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(strFirstNo))
                {
                    string sql = @"select actual_no actualNo, 
                                   prediction_no predictionNo,
                                   car_no carNo,
                                   matter_name matterName,
                                   gross_weight grossWeight,
                                   gross_time grossTime,
                                   tare_weight tareWeight,
                                   tare_time tareTime,
                                   net_weight netWeight,
                                   meter_type_name meterTypeName,
                                   spec_name specName,
                                   forwarding_unit_name forwardingUnitName,
                                   receiving_uint_name receivingUintName,
                                   load_point_name loadPointName
                              from meter_work_car_actual where actual_first1_no='" + strFirstNo + "' or actual_first2_no='" + strFirstNo + "'";
                    //查下如果有洁净数据，表示这个数据是洁净，那么进行打印
                    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)
                        {
                            printClass.PrintPage(e, rm.Data[0]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lg.WriteLog(3, "打印异常");
            }
        }
        #endregion

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

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