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.Data;
using System.Drawing;
using System.Windows.Forms;

namespace StorageMeterSystem
{
    public partial class frmHotDeliveryStandardWgt : Form
    {
        private MeterWorkStorageSingleWgtService singleWgtService = new MeterWorkStorageSingleWgtService(); //预报服务
        private ComBaseInfoService comBaseInfoService = new ComBaseInfoService(); //基础数服务
        private MeterBaseScalePointService scalePointService = new MeterBaseScalePointService(); //计量点信息服务
        private MeterWorkStorageSingleWgt singleWgt = new MeterWorkStorageSingleWgt(); //预报实体类

        private Log l = Log.GetInstance(); //日志
        private string userId = "", userName = ""; //用户ID用户名
        private CoreAppUser appUser = null;//登陆信息

        public frmHotDeliveryStandardWgt()
        {
            InitializeComponent();
        }

        private void frmHotDeliveryStandardWgt_Load(object sender, EventArgs e)
        {
            userId = ((ST_MainForm)(this.MdiParent)).UserID;
            userName = ((ST_MainForm)(this.MdiParent)).UserName;
            appUser = ((ST_MainForm)(this.MdiParent)).AppUser;

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

            #region 载入基础信息

            //计量点信息载入cmbPoint1;cmbPoint1Up
            RESTfulResult<List<MeterBaseScalePoint>> rr = scalePointService.doQueryWf(new MeterBaseScalePoint { validFlag = "1", spotTypeNo = "001002004" });
            if (rr.Succeed && rr.Data != null && rr.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbPoint1, rr.Data.ListToDataTable<MeterBaseScalePoint>(), "baseSpotNo", "baseSpotName");
                ClsControlPack.SetUltraComboDataSource(cmbPoint1Up, rr.Data.ListToDataTable<MeterBaseScalePoint>(), "baseSpotNo", "baseSpotName");
            }
            else
            {
                MessageBox.Show("计量点载入失败!");
                return;
            }

            ValueList vlistFlag1 = new ValueList();
            vlistFlag1.ValueListItems.Add("", "全部");
            vlistFlag1.ValueListItems.Add("0", "无效");
            vlistFlag1.ValueListItems.Add("1", "有效");
            cmbValueFlag.ValueList = vlistFlag1;
            cmbValueFlag.SelectedIndex = 0;

            ValueList vlistFlag2 = new ValueList();
            vlistFlag2.ValueListItems.Add("", "全部");
            vlistFlag2.ValueListItems.Add("0", "实际重量");
            vlistFlag2.ValueListItems.Add("1", "理论重量");
            vlistFlag2.ValueListItems.Add("2", "标准重量");
            this.ultraGridSingleWgt.DisplayLayout.Bands[0].Columns["weightType"].ValueList = vlistFlag2;

            ValueList vlistFlag3 = new ValueList();
            vlistFlag3.ValueListItems.Add("", "全部");
            vlistFlag3.ValueListItems.Add("0", "无效");
            vlistFlag3.ValueListItems.Add("1", "有效");
            this.ultraGridSingleWgt.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vlistFlag3;

            //表格进行筛选
            //ClsControlPack.SetUltraGridRowFilter(ref ultraGridSingleWgt, true);

            #endregion 载入基础信息

            btnQuery();
        }

        #region 点击事件

        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                case "btnQuery": //btnInsert
                    {
                        btnQuery();
                        break;
                    }
                case "btnInsert": //新增
                    {
                        btnInsert();
                        break;
                    }
                case "btnCancel": //作废
                    {
                        btnUpdate("0");
                    }
                    break;

                case "btnUnCancel": //还原
                    {
                        btnUpdate("1");
                    }
                    break;

                case "btnUpdate": //还原
                    {
                        btnUpdate("");
                    }
                    break;

                default: break;
            }
        }

        /// <summary>
        /// 行点击事件，给下面的区域赋值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraGridSingleWgt_ClickCell(object sender, ClickCellEventArgs e)
        {
            try
            {
                if (ultraGridSingleWgt.ActiveRow == null)
                {
                    return;
                }

                UltraGridRow ugr = ultraGridSingleWgt.ActiveRow;
                if (ugr.Cells["UNCK"].Value.ToString().ToUpper().Equals("TRUE"))
                {
                    ugr.Cells["UNCK"].Value = false;
                }
                else
                {
                    ugr.Cells["UNCK"].Value = true;
                }

                //界面赋值
                if (ugr != null)
                {
                    singleWgt.singleWgtNo = ugr.Cells["singleWgtNo"].Text.Trim(); //重量编号
                    singleWgt.specName = ugr.Cells["specName"].Text.Trim();         //规格
                    singleWgt.specNo = ugr.Cells["specNo"].Text.Trim();         //规格编号

                    singleWgt.baseSpotName = ugr.Cells["baseSpotName"].Text.Trim();         //计量点
                    singleWgt.baseSpotNo = ugr.Cells["baseSpotNo"].Text.Trim();         //计量点编号

                    singleWgt.gradeName = ugr.Cells["gradeName"].Text.Trim();       //钢号
                    singleWgt.gradeNo = ugr.Cells["gradeNo"].Text.Trim();       //钢号编号
                    singleWgt.singleWeight = Convert.ToDouble(ugr.Cells["singleWeight"].Text.Trim());         //理论重量
                    singleWgt.weightDiff = Convert.ToDouble(ugr.Cells["weightDiff"].Text.Trim());         //重量偏差
                    autoAutoFill(singleWgt); //点击行进行自动填充界面字段
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ultraGridSingleWgt_ClickCell方法处理异常：" + ex);
            }
        }

        /// <summary>
        /// 全选点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (UltraGridRow ugr in ultraGridSingleWgt.Rows)
            {
                if (!ugr.HiddenResolved)
                {
                    ugr.Cells["UNCK"].Value = cbAll.Checked;
                }
            }
        }

        #endregion 点击事件

        /// <summary>
        /// 自动填充界面的数据
        /// </summary>
        private void autoAutoFill(MeterWorkStorageSingleWgt singleWgt)
        {
            if (singleWgt == null || string.IsNullOrEmpty(singleWgt.singleWgtNo))
            {
                return;
            }
            cmbPoint1Up.Text = singleWgt.baseSpotName;
            numSingleWeightUp.Value = (decimal)singleWgt.singleWeight;//理论重量8
            numWeightDiff.Value = (decimal)singleWgt.weightDiff;//理论重量维护
        }

        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="vFlag"></param>
        private void btnInsert()
        {
            List<MeterWorkStorageSingleWgt> scaleList = new List<MeterWorkStorageSingleWgt>();
            MeterWorkStorageSingleWgt preStorageScale = new MeterWorkStorageSingleWgt();
            if (string.IsNullOrEmpty(numSingleWeightUp.Text))
            {
                MessageBox.Show("理论重量的值不允许为空！");
                return;
            }
            preStorageScale.createManName = userName;
            preStorageScale.createManNo = userId;
            preStorageScale.baseSpotName = cmbPoint1Up.Text.Trim();         //计量点
            preStorageScale.baseSpotNo = cmbPoint1Up.Value + "";         //计量点编号
            preStorageScale.singleWeight = Convert.ToDouble(numSingleWeightUp.Value); //理论重量
            preStorageScale.weightDiff = Convert.ToDouble(numWeightDiff.Value);//重量允许偏差
            preStorageScale.weightType = "2";//重量类型（0=单只实际重量，1=预报理论重量，2=标准件重量）

            scaleList.Add(preStorageScale);
            RESTfulResult<string> rms = singleWgtService.doAddWf(scaleList);
            if (rms.Succeed)
            {
                MessageBox.Show("新增成功！");
                btnQuery();
            }
            else
            {
                MessageBox.Show("操作失败：" + rms.Data);
                l.WriteLog(19, "操作失败：" + rms.Data + rms.Message);
            }
        }

        /// <summary>
        /// 修改数据(作废还原)
        /// </summary>
        /// <param name="vFlag"></param>
        private void btnUpdate(string vFlag)
        {
            try
            {
                int iCount = 0;
                List<MeterWorkStorageSingleWgt> lt = new List<MeterWorkStorageSingleWgt>();
                ultraGridSingleWgt.UpdateData();
                foreach (UltraGridRow ugr in ultraGridSingleWgt.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().Trim().ToUpper() == "TRUE")
                    {
                        if (string.IsNullOrEmpty(vFlag) && "0".Equals(ugr.Cells["valueFlag"].Value + ""))
                        {
                            MessageBox.Show("已作废的数据，请先还原再进行修改！");
                            return;
                        }
                        if (string.IsNullOrEmpty(numSingleWeightUp.Text))
                        {
                            MessageBox.Show("理论重量的值不允许为空！");
                            return;
                        }

                        MeterWorkStorageSingleWgt preStorageUpdate = new MeterWorkStorageSingleWgt();
                        preStorageUpdate.singleWgtNo = ugr.Cells["singleWgtNo"].Text.Trim();
                        preStorageUpdate.updateManNo = userId;
                        preStorageUpdate.updateManName = userName;
                        if (!string.IsNullOrEmpty(vFlag))
                        {
                            preStorageUpdate.valueFlag = vFlag;
                        }
                        else
                        {
                            preStorageUpdate.baseSpotName = cmbPoint1Up.Text.Trim();         //计量点
                            preStorageUpdate.baseSpotNo = cmbPoint1Up.Value + "";         //计量点编号
                            preStorageUpdate.singleWeight = Convert.ToDouble(numSingleWeightUp.Value); //理论重量
                            preStorageUpdate.weightDiff = Convert.ToDouble(numWeightDiff.Value); //重量偏差
                        }

                        lt.Add(preStorageUpdate);
                        iCount++;
                    }
                }
                if (lt == null || lt.Count == 0)
                {
                    MessageBox.Show("请至少勾选一条数据后再进行更新操作！");
                    return;
                }
                DialogResult dr = MessageBox.Show("共更新[" + iCount + "]条数据，是否继续更新！", "提示", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.Cancel)
                {
                    return;
                }
                RESTfulResult<String> rms = singleWgtService.doUpdateWf(lt);
                if (rms.Succeed)
                {
                    MessageBox.Show("修改成功！");
                    btnQuery();
                }
                else
                {
                    MessageBox.Show("操作失败：" + rms.Data);
                    l.WriteLog(19, "操作失败：" + rms.Data + rms.Message);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        private void btnQuery()
        {
            DataTable dtScale = dataTable1.Clone();
            CommonPage<MeterWorkStorageSingleWgt> cp = new CommonPage<MeterWorkStorageSingleWgt>();

            cp.param = new MeterWorkStorageSingleWgt(); //{ valueFlag = "1", baseSpotNo = cmbPoint1.Value?.ToString() };
            cp.param.valueFlag = cmbValueFlag.Value + "";
            cp.param.baseSpotNo = cmbPoint1.Value + "";//计量点编号
            cp.param.weightType = "2";//重量类型（0=单只实际重量，1=预报理论重量，2=标准件重量）
            cp.param.createTime1 = dtStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
            cp.param.createTime2 = dtEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss");

            RESTfulResult<List<MeterWorkStorageSingleWgt>> rms = singleWgtService.doQuery(cp.param);
            if (rms.Succeed)
            {
                if (rms.Data != null && rms.Data.Count > 0)
                {
                    dtScale = rms.Data.ListToDataTable<MeterWorkStorageSingleWgt>();

                    ClsControlPack.CopyDataToDatatable(ref dtScale, ref dataTable1, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridSingleWgt);

                    foreach (UltraGridRow ugr in ultraGridSingleWgt.Rows)
                    {
                        if (ugr.Cells["valueFlag"].Value.ToString() == "0")
                        {
                            ugr.Appearance.BackColor = Color.Red;
                        }
                        else
                        {
                            ugr.Appearance.BackColor = Color.White;
                        }
                        //ugr.Cells["valueFlag"].Value = GetValueFlageType(ugr.Cells["valueFlag"].Value.ToString());
                        //ugr.Cells["weightType"].Value = GetWeightType(ugr.Cells["weightType"].Value.ToString());
                    }
                }
                else
                {
                    dtScale.Clear();
                    ClsControlPack.CopyDataToDatatable(ref dtScale, ref dataTable1, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridSingleWgt);
                }
            }
        }
    }
}