using com.hnshituo.core.webapp.vo;
using Common;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using JC_MeasuringSystem;
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;

namespace CraneScaleSystem
{
    public partial class frmCraneScaleDb : Form
    {
        public frmCraneScaleDb()
        {
            InitializeComponent();
            ClsControlPack.ShowGridCaption<MeterWorkCraneActual>(ultraGridYb.DisplayLayout.Bands[0]);
        }
        private CoreAppUser userinfo = null;

        MeterWorkCarActualFirstService firstService = new MeterWorkCarActualFirstService();
        MeterWorkCraneActualService craneActualService = new MeterWorkCraneActualService();

        private void frmCraneScaleDb_Load(object sender, EventArgs e)
        {
            userinfo = ((ST_MainForm)(this.MdiParent)).AppUser;
            ClsControlPack.SetUltraGridRowFilter(ref ultraGridYb, true);

            ValueList vValid = new ValueList(); //状态（0=作废，1=有效，2=结净）
            vValid.ValueListItems.Add("2", "生成");
            vValid.ValueListItems.Add("1", "有效");
            vValid.ValueListItems.Add("0", "作废");
            ultraGridYb.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vValid.Clone();


            ValueList vValidFst = new ValueList(); //状态（0=作废，1=有效，2=结净）
            vValidFst.ValueListItems.Add("2", "校磅");
            vValidFst.ValueListItems.Add("1", "皮重");
            vValidFst.ValueListItems.Add("0", "毛重");//weightType
            ultraGridYb.DisplayLayout.Bands[0].Columns["weightType"].ValueList = vValidFst.Clone();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            doQuery();
        }

        private void doQuery() 
        {
            MeterWorkCraneActual mwca = new MeterWorkCraneActual();
            mwca.startTime = Convert.ToDateTime($"{DateTime.Now.ToString("yyyy")}-01-01 00:00:00");
            mwca.endTime = DateTime.Now;
            mwca.valueFlag = "1";
            //mwca.weightType = "0"; //实际上需要生成1次数据的只有毛重数据

            RESTfulResult<List<MeterWorkCraneActual>> result = craneActualService.doQueryWf(mwca);
            if (result.Succeed)
            {
                if (result.Data == null || result.Data.Count == 0)
                {
                    meterWorkCraneActualBindingSource.DataSource = new List<MeterWorkCraneActual>();
                    CleanForm();
                }
                else
                {
                    meterWorkCraneActualBindingSource.DataSource = result.Data;//.Where(s => s.weightType != "1").ToList();
                }
                ClsControlPack.RefreshAndAutoSize(ultraGridYb, true);
            }
            else
            {
                MessageBox.Show("查询失败：" + result.ResultMessage);
            }
        }

        private void btnCreateFirstDb_Click(object sender, EventArgs e)
        {
            if (!(meterWorkCraneActualBindingSource.DataSource is List<MeterWorkCraneActual>))
                return;

            //操作日志
            MeterMonitorNote monitorNote = new MeterMonitorNote();
            monitorNote.baseSpotNo = "";
            monitorNote.baseSpotName = "贵金属吊钩秤";
            monitorNote.operationContent = "贵金属数据生成";
            monitorNote.operationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            monitorNote.meterManNo = userinfo.userid;
            monitorNote.meterManName = userinfo.username;
            monitorNote.meterNoteSource = "0";

            string msg = "";
            string sPreNo = "";
            List<MeterWorkCraneActual> lmwca = (List<MeterWorkCraneActual>)meterWorkCraneActualBindingSource.DataSource;
            foreach (MeterWorkCraneActual actual in lmwca) 
            {
                if (actual.weightType == "0") 
                {
                    if (sPreNo != actual.predictionNo) 
                    {
                        monitorNote.carNo = actual.carNo;

                        MeterWorkCarActualFirst first = new MeterWorkCarActualFirst();
                        //相同名称的均赋值一次
                        EntityBase<MeterWorkCraneActual> entityBase = new EntityBase<MeterWorkCraneActual>();
                        first = entityBase.format<MeterWorkCarActualFirst>(actual, first);
                        first.meterNum = lmwca.Where(s => s.weightType == "0" && s.predictionNo == actual.predictionNo).Count();
                        first.meterWeight = lmwca.Where(s => s.weightType == "0" && s.predictionNo == actual.predictionNo).Sum(s => s.meterWeight);
                        //执行一次生成，然后再赋值，继续下一轮
                        RESTfulResult<string> res = firstService.doCraneDbWf(first, monitorNote);
                        if (!res.Succeed) 
                        {
                            msg = "生成异常："+res.ResultMessage;
                            break;
                        }
                        sPreNo = actual.predictionNo;
                    }
                }
            }

            if (!string.IsNullOrEmpty(msg)) 
            {
                MessageBox.Show(msg);
            }
            doQuery();
        }

        

        private void ultraGridYb_AfterRowActivate(object sender, EventArgs e)
        {
            UltraGridRow ugr = ultraGridYb.ActiveRow;
            if (ugr != null) 
            {
                foreach (UltraGridCell uc in ugr.Cells) 
                {
                    foreach (Control cn in gbBottom.Controls)
                    {
                        if (cn is TextBox)
                        {
                            if (cn.Name.Substring(3).ToLower() == uc.Column.Key.ToLower()) 
                            {
                                cn.Text = uc.Text;
                                break;
                            }
                        }
                    }
                }
            }
        }

        private void CleanForm() 
        {
            foreach (Control cn in gbBottom.Controls) 
            {
                if (cn is TextBox) 
                {
                    cn.Text = "";
                }
            }
        }

        private void btnCreateNetDB_Click(object sender, EventArgs e)
        {
            if (!(meterWorkCraneActualBindingSource.DataSource is List<MeterWorkCraneActual>))
                return;

            //操作日志
            MeterMonitorNote monitorNote = new MeterMonitorNote();
            monitorNote.baseSpotNo = "";
            monitorNote.baseSpotName = "贵金属吊钩秤";
            monitorNote.operationContent = "贵金属数据二次生成";
            monitorNote.operationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            monitorNote.meterManNo = userinfo.userid;
            monitorNote.meterManName = userinfo.username;
            monitorNote.meterNoteSource = "0";

            string msg = "";
            string sPreNo = "";
            List<MeterWorkCraneActual> lmwca = (List<MeterWorkCraneActual>)meterWorkCraneActualBindingSource.DataSource;
            foreach (MeterWorkCraneActual actual in lmwca)
            {
                if (actual.weightType == "1")
                {
                    if (sPreNo != actual.predictionNo)
                    {
                        RESTfulResult<List<MeterWorkCarActualFirst>> resx = firstService.doQueryByCarNo(new MeterWorkCarActualFirst { predictionNo = actual.predictionNo, carNo = actual.carNo, baseSpotNo = "00018", valueFlag = "1" });
                        if (resx.Succeed) 
                        {
                            if (resx.Data != null && resx.Data.Count > 0) 
                            {
                                monitorNote.carNo = actual.carNo;

                                MeterWorkCarActualFirst first = new MeterWorkCarActualFirst();
                                //相同名称的均赋值一次
                                EntityBase<MeterWorkCraneActual> entityBase = new EntityBase<MeterWorkCraneActual>();
                                first = entityBase.format<MeterWorkCarActualFirst>(actual, first);

                                //这个重量应该是汽车一次表中同预报编号，未结净的车信息的meterNum值*(当前重量/件数)，然后取整
                                first.meterWeight = int.Parse(((actual.meterWeight / actual.meterNum) * first.meterNum) + "");

                                MeterWorkCarActual netDb = new MeterWorkCarActual();
                                EntityBase<MeterWorkCraneActual> entityB = new EntityBase<MeterWorkCraneActual>();
                                netDb = entityBase.format<MeterWorkCarActual>(actual, netDb);
                                netDb.netTime = DateTime.Now;
                                netDb.netManNo = userinfo.userid;
                                netDb.netManName = userinfo.username;
                                netDb.netWeight = resx.Data[0].meterWeight - first.meterWeight;
                                netDb.actualFirst1No = resx.Data[0].actualFirstNo;
                                netDb.netSpot3No = first.baseSpotNo;
                                netDb.netSpot3Name = first.baseSpotName;
                                
                                netDb.grossMode = "1";
                                netDb.tareMode = "1";

                                netDb.grossManNo = resx.Data[0].createManNo;
                                netDb.grossManName = resx.Data[0].createManName;
                                netDb.grossTime = resx.Data[0].createTime;
                                netDb.grossWeight = resx.Data[0].meterWeight;
                                netDb.baseSpot1No = resx.Data[0].baseSpotNo;
                                netDb.baseSpot1Name = resx.Data[0].baseSpotName;

                                netDb.tareManNo = first.createManNo;
                                netDb.tareManName = first.createManName;
                                netDb.tareTime = first.createTime;
                                netDb.tareWeight = first.meterWeight;
                                netDb.valueFlag = "0";
                                netDb.netMode = "1";
                                netDb.baseSpot2No = first.baseSpotNo;
                                netDb.baseSpot2Name = first.baseSpotName;
                                netDb.uploadFlag = "0";

                                netDb.netManNo = first.createManNo; //净重计量员编码 
                                netDb.netManName = first.createManName; //净重计量员名称
                                netDb.netSpot3No = PbCache.sportInfo.baseSpotNo; //净重计量点编号
                                netDb.netSpot3Name = PbCache.sportInfo.baseSpotName; //净重计量点
                                //执行一次生成，然后再赋值，继续下一轮
                                RESTfulResult<string> res = firstService.doCraneNetDbWf(first, netDb, monitorNote);
                                if (!res.Succeed)
                                {
                                    msg = "生成异常：" + res.ResultMessage;
                                    break;
                                }
                                sPreNo = actual.predictionNo;
                            }
                        }

                        
                    }
                }
            }

            if (!string.IsNullOrEmpty(msg))
            {
                MessageBox.Show(msg);
            }
            doQuery();
        }
    }
}
