using com.hnshituo.core.webapp.vo;
using Common;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using JC_MeasuringSystem;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace StorageMeterSystem
{
    public partial class frmHotDeliveryCalibration : Form
    {
        private MeterWorkStorageCalibrationService calibrationService = new MeterWorkStorageCalibrationService(); //校秤服务
        private ComBaseInfoService comBaseInfoService = new ComBaseInfoService(); //基础数服务
        private MeterBaseScalePointService scalePointService = new MeterBaseScalePointService(); //计量点信息服务
        private MeterWorkStorageCalibration calibration = new MeterWorkStorageCalibration();

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

        public frmHotDeliveryCalibration()
        {
            InitializeComponent();
        }

        private void frmHotDeliveryCalibration_Load(object sender, EventArgs e)
        {
            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"));

            userId = ((ST_MainForm)(this.MdiParent)).UserID;
            userName = ((ST_MainForm)(this.MdiParent)).UserName;
            appUser = ((ST_MainForm)(this.MdiParent)).AppUser;

            //界面显示班次班组
            lbUserName.Text = "登陆用户: " + userName;
            lbGroupClass.Text = "班次班组: " + appUser.userClass + " " + appUser.userGroup;

            this.ultraGridSingleWgt.DisplayLayout.ViewStyleBand = ViewStyleBand.OutlookGroupBy;
            this.ultraGridSingleWgt.DisplayLayout.GroupByBox.Hidden = true;

            #region 载入基础信息

            //计量点信息载入cmbPoint;cmbPointUp
            RESTfulResult<List<MeterBaseScalePoint>> rr = scalePointService.doQueryWf(new MeterBaseScalePoint { validFlag = "1", spotTypeNo = "001002004" });
            if (rr.Succeed && rr.Data != null && rr.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbPoint, 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", "通过");
            cmbQualifiedFlag.ValueList = vlistFlag2;
            cmbQualifiedFlag.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;

            ValueList vlistFlag4 = new ValueList();
            vlistFlag4.ValueListItems.Add("", "全部");
            vlistFlag4.ValueListItems.Add("0", "未通过");
            vlistFlag4.ValueListItems.Add("1", "通过");
            this.ultraGridSingleWgt.DisplayLayout.Bands[0].Columns["qualifiedFlag"].ValueList = vlistFlag4;
            //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 "btnExcelOut": //导出
                    {
                        string str = Interaction.InputBox("请输入要导出的文件名", "提示", "", 100, 100);
                        string pqath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                        this.ultraGridExcelExporter1.Export(this.ultraGridSingleWgt, pqath + "\\" + str + ".xls");
                        //MessageUtil.ShowTips("导出成功，请查看桌面！是否有[" + str + ".xls]表格");
                        MessageBox.Show("导出成功，请查看桌面！是否有[" + str + ".xls]表格");
                    }
                    break;

                case "btnNotProd": //未生产
                    {
                        btnNotProd();
                        break;
                    }
                case "btnUpdate": //修改备注
                    {
                        btnUpdate();
                        break;
                    }
                default: break;
            }
        }

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

        /// <summary>
        /// 是否开启过滤
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckFilter_CheckedChanged(object sender, EventArgs e)
        {
            if (ckFilter.Checked)
            {
                this.ultraGridSingleWgt.DisplayLayout.Override.AllowRowFiltering = DefaultableBoolean.True;
            }
            else
            {
                this.ultraGridSingleWgt.DisplayLayout.Override.AllowRowFiltering = DefaultableBoolean.False;
            }
        }

        /// <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)
                {
                    calibration.wgtNo = ugr.Cells["wgtNo"].Text.Trim(); //实绩编号
                    calibration.memo = ugr.Cells["memo"].Text.Trim(); //备注
                    calibration.baseSpotName= ugr.Cells["baseSpotName"].Text.Trim();//计量点名称

                    tbMemo.Text = calibration.memo;
                    tbBasePoint.Text = calibration.baseSpotName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ultraGridSingleWgt_ClickCell方法处理异常：" + ex);
            }
        }
        #endregion 点击事件

        /// <summary>
        /// 更新数据
        /// </summary>
        private void btnUpdate()
        {
            try
            {
                int iCount = 0;
                List<MeterWorkStorageCalibration> lt = new List<MeterWorkStorageCalibration>();
                ultraGridSingleWgt.UpdateData();
                foreach (UltraGridRow ugr in ultraGridSingleWgt.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().Trim().ToUpper() == "TRUE")
                    {
                       
                        MeterWorkStorageCalibration calibrationUpdate = new MeterWorkStorageCalibration();

                        calibrationUpdate.wgtNo = ugr.Cells["wgtNo"].Text.Trim(); //实绩编号
                        calibrationUpdate.memo = tbMemo.Text; //备注
                        calibrationUpdate.updateManNo = userId;
                        calibrationUpdate.updateManName = userName;
                        lt.Add(calibrationUpdate);
                        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 = calibrationService.doUpdateWf(lt);
                if (rms.Succeed)
                {
                    MessageBox.Show( "修改成功！");
                    btnQuery();
                }
                else
                {
                    MessageBox.Show("操作失败：" + rms.Data);
                    l.WriteLog(19, "操作失败：" + rms.Data + rms.Message);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void btnQuery()
        {
            DataTable dtCalibration = dataTable1.Clone();
            CommonPage<MeterWorkStorageCalibration> cp = new CommonPage<MeterWorkStorageCalibration>();
            cp.param = new MeterWorkStorageCalibration(); //{ valueFlag = "1", baseSpotNo = cmbPoint.Value?.ToString() };
            cp.param.baseSpotNo = cmbPoint.Value + ""; //计量点
            cp.param.valueFlag = "1";// cmbValueFlag.Value+"";//状态(1=有效，0=无效)
            cp.param.qualifiedFlag = cmbQualifiedFlag.Value + "";//校秤状态(1=通过，0=未通过)
            cp.param.startTime = dtStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
            cp.param.endTime = dtEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss");

            RESTfulResult<List<MeterWorkStorageCalibration>> rms = calibrationService.doQueryWf(cp.param);
            if (rms.Succeed)
            {
                if (rms.Data != null && rms.Data.Count > 0)
                {
                    dtCalibration = rms.Data.ListToDataTable<MeterWorkStorageCalibration>();

                    ClsControlPack.CopyDataToDatatable(ref dtCalibration, 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
                {
                    dtCalibration.Clear();
                    ClsControlPack.CopyDataToDatatable(ref dtCalibration, ref dataTable1, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridSingleWgt);
                }
            }
        }


        /// <summary>
        /// 未生产
        /// </summary>
        private void btnNotProd()
        {
            if (string.IsNullOrEmpty(cmbPoint.Text) || string.IsNullOrEmpty(cmbPoint.Value.ToString()))
            {
                MessageBox.Show("请先选择计量点！");
                return;
            }
            DialogResult dr = MessageBox.Show("当前计量点为【" + cmbPoint.Text + "】，是否继续添加【未生产】的较秤数据！", "提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.Cancel)
            {
                return;
            }
            MeterWorkStorageCalibration calibration = new MeterWorkStorageCalibration();
            calibration.qualifiedFlag = "1";//校秤状态(1=通过，0=未通过)
            calibration.valueFlag = "1"; //状态(1 = 有效，0 = 无效)
            calibration.createManNo = userId;
            calibration.createManName = userName;
            calibration.baseSpotNo = cmbPoint.Value + ""; //校秤计量点的编号
            calibration.baseSpotName = cmbPoint.Text;//校秤计量点的名称
            calibration.meterClass = appUser.userGroup;
            calibration.meterGroup = appUser.userClass;
            calibration.actualWeight = 888;//较秤重量
            calibration.theoryWeight = 888; //理论重量

            calibration.theoryWeightDiff = 0; //理论重量差值
            calibration.actualWeightDiff = 0; //校秤重量差值
            calibration.memo = "未生产";

            RESTfulResult<string> rm = calibrationService.doAddNotProd(calibration);
            if (rm.Succeed)
            {
                MessageBox.Show("校秤数据保存成功！");
            }
            else
            {
                MessageBox.Show("保存失败：" + rm.Data);
                l.WriteLog(19, "保存失败：" + rm.Data + rm.Message);
            }
            btnQuery();
        }
    }
}