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 frmHotDeliveryTheoryWgt : 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 frmHotDeliveryTheoryWgt()
        {
            InitializeComponent();
        }

        private void frmHotDeliveryTheoryWgt_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.ToString("yyyy-MM-dd") + " 00:00:00"));
            dtEndTime.Value = Convert.ToDateTime((DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59"));

            #region 载入基础信息

            /*
            string sql = @"SELECT base_code baseCode,base_name baseName,memo FROM Com_Base_Info where p_base_code='001025' and valid_Flag='1'";
            PbModelDbService<List<ComBaseInfo>> pb = new PbModelDbService<List<ComBaseInfo>>();
            RESTfulResult<List<ComBaseInfo>> rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbScaleState, rmType.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("产品信息载入失败");
                return;
            }

            */

            //热送磅规格信息载入cmbSpcNameUp
            RESTfulResult<List<ComBaseInfo>> rrComSpcName = comBaseInfoService.doQueryBaseList(new ComBaseInfo { validFlag = "1", pBaseCode = "001018" });
            if (rrComSpcName.Succeed && rrComSpcName.Data != null && rrComSpcName.Data.Count > 0)
            {
                rrComSpcName.Data.Sort((a, b) => a.baseName.CompareTo(b.baseName));
                ClsControlPack.SetUltraComboDataSource(cmbSpcNameUp, rrComSpcName.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
                ClsControlPack.SetUltraComboDataSource(cmbSpcName, rrComSpcName.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("热送磅规格信息载入失败!");
                return;
            }

            //热送磅钢种信息载入cmbGradeNameUp
            RESTfulResult<List<ComBaseInfo>> rrComGradeName = comBaseInfoService.doQueryBaseList(new ComBaseInfo { validFlag = "1", pBaseCode = "001017" });
            if (rrComGradeName.Succeed && rrComGradeName.Data != null && rrComGradeName.Data.Count > 0)
            {
                rrComGradeName.Data.Sort((a, b) => a.baseName.CompareTo(b.baseName));
                ClsControlPack.SetUltraComboDataSource(cmbGradeNameUp, rrComGradeName.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
                ClsControlPack.SetUltraComboDataSource(cmbGradeName, rrComGradeName.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            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 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.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>
        private void updateBoxUnEnable()
        {
            cmbSpcNameUp.Enabled = false;
            cmbGradeNameUp.Enabled = false;
            numSingleWeightUp.Enabled = false;
        }

        /// <summary>
        /// 界面可编辑
        /// </summary>
        private void updateBoxEnable()
        {
            cmbSpcNameUp.Enabled = true;
            cmbGradeNameUp.Enabled = true;
            numSingleWeightUp.Enabled = true;
        }

        /// <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;
            }
            cmbSpcNameUp.Text = singleWgt.specName; //规格名称3
            cmbGradeNameUp.Text = singleWgt.gradeName; //钢号名称4
            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.specName = cmbSpcNameUp.Text;
            preStorageScale.specNo = cmbSpcNameUp.Value + "";
            preStorageScale.gradeName = cmbGradeNameUp.Text;
            preStorageScale.gradeNo = cmbGradeNameUp.Value + "";
            preStorageScale.singleWeight = Convert.ToDouble(numSingleWeightUp.Value);
            preStorageScale.weightDiff = Convert.ToDouble(numWeightDiff.Value);
            preStorageScale.weightType = "1";//重量类型（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.specName = cmbSpcNameUp.Text;
                            preStorageUpdate.specNo = cmbSpcNameUp.Value + "";
                            preStorageUpdate.gradeName = cmbGradeNameUp.Text;
                            preStorageUpdate.gradeNo = cmbGradeNameUp.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 = cmbPoint.Value?.ToString() };
            cp.param.valueFlag = cmbValueFlag.Value + "";
            cp.param.specNo = cmbSpcName.Value + "";//规格名称
            cp.param.gradeNo = cmbGradeName.Value + ""; //牌号名称（钢号名称）
            cp.param.weightType = "1";//重量类型（0=单只实际重量，1=理论重量）
            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;
                        }
                    }
                }
                else
                {
                    dtScale.Clear();
                    ClsControlPack.CopyDataToDatatable(ref dtScale, ref dataTable1, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridSingleWgt);
                }
            }
        }
    }
}