using com.hnshituo.core.webapp.vo;
using Common;
using Common.vo.pb;
using Infragistics.Win;
using Infragistics.Win.UltraWinEditors;
using Infragistics.Win.UltraWinGrid;
using JC_MeasuringSystem;
using MeterModuleLibrary;
using MeterPlugInLibrary;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace BeltScaleSystem

{
    public partial class frmScalePredictionManage : Form
    {
        public frmScalePredictionManage()
        {
            InitializeComponent();
        }

        //菜单栏事件
        private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                case "查询":
                    QueryScalePrediction();
                    break;
                case "新增":
                    AddScalePrediction();
                    break;
                case "修改":
                    UpdateScalePrediction();
                    break;
                case "导出":
                    ExporterScalePrediction();
                    break;
                case "删除":
                    DeleteScalePrediction();
                    break;
                case "还原":
                    RecoverScalePrediction();
                    break;
                case "退出":
                    this.Close();
                    break;
            }
        }


        #region 自定义变量
        // private ComBaseInfoService comBaseInfoService = new ComBaseInfoService(); //基础数服务
        PreBeltScalePreService PreBeltScalePreService = new PreBeltScalePreService();//预报服务
        private CoreAppUser appUser = null;//登陆信息
        private string userId = "", userName = ""; //用户ID用户名
        private DataTable dtMaterial;//物料数据源
        private DataTable dtMaterial2;//物料数据源
        private DataTable dtcustomerSupplier;//发货单位数据源
        private DataTable dtPoint;//计量点数据源
        MeterBaseMatterInfoService matterInfoService = new MeterBaseMatterInfoService();//物料服务
        MeterBaseCustomerSupplierService customerSupplierService = new MeterBaseCustomerSupplierService();
        #endregion


        #region 菜单栏方法
        //预报查询
        private void  QueryScalePrediction() {
            try
            {
                if (DateTime.Compare(dtStartTime.Value, dtEndTime.Value) > 0)
                {
                    MessageBox.Show("开始时间不能大于结束时间");
                    return;
                }
                PreBeltScaleForecast forecast = new PreBeltScaleForecast();
                DataTable dtScaleTable = dataTable1.Clone();
                CommonPage<PreBeltScaleForecast> cp = new CommonPage<PreBeltScaleForecast>();
                if (checkDate.Checked)
                {
                    cp.startTime = dtStartTime.Text.ToString();
                    cp.endTime = dtEndTime.Text.ToString();
                }
                if (cmMatName.Text.ToString() != "全部") {
                    forecast.newMatName = cmMatName.Text.ToString();
                }
                if (cbfahuo.Text.ToString() != "全部" )
                {
                    forecast.newSupplier = cbfahuo.Text.ToString();
                }
                if (cbshouh.Text.ToString() != "全部" )
                {
                    forecast.receivingUintName = cbshouh.Text.ToString();
                }
                if (ShipnoTxt_1.Text.ToString() != null && ShipnoTxt_1.Text.ToString().Trim() != "")//船号
                {
                    forecast.shipNo = ShipnoTxt_1.Text.ToString();
                }
                if (cmbState.Text.ToString() != "全部" && cmbState.SelectedIndex != -1)
                {
                    forecast.valueFlag = cmbState.Value.ToString();
                }
                cp.param = forecast; // new PreBeltScaleForecast { }; // ！=0
                RESTfulResult<List<PreBeltScaleForecast>> rms = PreBeltScalePreService.doQueryWflike(cp);
                if (rms.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        dtScaleTable = rms.Data.ListToDataTable<PreBeltScaleForecast>();

                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridBeltPre);

                        foreach (UltraGridRow ugr in ultraGridBeltPre.Rows)
                        {
                            if (ugr.Cells["valueFlag"].Value.ToString() == "0")
                            {
                                ugr.Appearance.BackColor = Color.Red;
                            }
                            else if (ugr.Cells["valueFlag"].Value.ToString() == "3")
                            {
                                ugr.Appearance.BackColor = Color.YellowGreen;
                            }
                            else
                            {
                                ugr.Appearance.BackColor = Color.White;
                            }
                        }

                    }
                    else
                    {
                        dtScaleTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridBeltPre);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("预报查询失败，请联系技术中心！" + ex.Message);
                return;
            }
        }
        //预报新增
        private void AddScalePrediction() {
            RESTfulResult<string> rm = PreBeltScalePreService.doAddBeltScalePrediction(findFromInfo(1));
            if (rm.Succeed)
            {
                MessageBox.Show("新增预报成功");
                QueryScalePrediction();
                return;
            }
            else {
                MessageBox.Show("新增预报失败，请联系技术中心！"+rm.Message);
                return;
            }
        }
        //预报修改
        private void UpdateScalePrediction()
        {
            try
            {
                RESTfulResult<string> rm = PreBeltScalePreService.doUpdateWf(findFromInfo(2));
                if (rm.Succeed)
                {
                    MessageBox.Show("预报修改成功");
                    QueryScalePrediction();
                    return;
                }
                else
                {
                    MessageBox.Show("预报修改失败，请联系技术中心！" + rm.Message);
                    return;
                }
            }
            catch (Exception ex) {
                MessageBox.Show("预报修改异常！" + ex.Message);
                return;
            }
        }
        //导出预报数据
        private void ExporterScalePrediction() {
            string str = Interaction.InputBox("请输入要导出的文件名", "提示", "", 100, 100);
            string pqath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            this.ultraGridExcelExporter1.Export(this.ultraGridBeltPre, pqath + "\\" + str + ".xls");
            MessageBox.Show("导出成功，请查看桌面！是否有[" + str + ".xls]表格");
        }
        //删除预报
        private void DeleteScalePrediction() {
            try
            {
                List<PreBeltScaleForecast> list = new List<PreBeltScaleForecast>();//预报实体
                string flag = "";
                //获取已选择的列
                List<UltraGridRow> uGrid = GridHelper.UltraGridGetChooseRows(ultraGridBeltPre, "UNCK");
                if (uGrid.Count <= 0) {
                    MessageBox.Show("请选择需要删除的预报！");
                    return;
                }
                foreach (UltraGridRow ugr in uGrid) {
                    flag = ugr.Cells["valueFlag"].Value.ToString();
                    if (flag == "0")
                    {
                        MessageBox.Show("该预报已是无效，不允许删除！");
                        return;
                    }
                    list.Add(new PreBeltScaleForecast { valueFlag = "0", predictionNo= ugr.Cells["predictionNo"].Value.ToString() });
                }
                RESTfulResult<int> rm = PreBeltScalePreService.doUpdateFlags(list);
                if (rm.Succeed)
                {
                    MessageBox.Show("预报删除成功");
                    QueryScalePrediction();
                    return;
                }
                else
                {
                    MessageBox.Show("预报删除失败，请联系技术中心！" + rm.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("预报删除异常！" + ex.Message);
                return;
            }

        }
        //预报还原
        private void RecoverScalePrediction()
        {
            try
            {
                List<PreBeltScaleForecast> list = new List<PreBeltScaleForecast>();//预报实体
                string flag = "";
                //获取已选择的列
                List<UltraGridRow> uGrid = GridHelper.UltraGridGetChooseRows(ultraGridBeltPre, "UNCK");
                if (uGrid.Count <= 0)
                {
                    MessageBox.Show("请选择需要还原的预报！");
                    return;
                }
                foreach (UltraGridRow ugr in uGrid)
                {
                    flag = ugr.Cells["valueFlag"].Value.ToString();
                    if (flag !="0") { 
                        MessageBox.Show("不是无效的预报不允许恢复！");
                        return;
                    }
                    list.Add(new PreBeltScaleForecast { valueFlag = "1", predictionNo = ugr.Cells["predictionNo"].Value.ToString() });
                }
                RESTfulResult<int> rm = PreBeltScalePreService.doUpdateFlags(list);
                if (rm.Succeed)
                {
                    MessageBox.Show("预报还原成功");
                    QueryScalePrediction();
                    return;
                }
                else
                {
                    MessageBox.Show("预报还原失败，请联系技术中心！" + rm.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("预报还原异常！" + ex.Message);
                return;
            }

        }
        #endregion


        #region 公共方法区
        private void frmScalePredictionManage_Load(object sender, EventArgs e)
        {
            //设置grid除了选择列 其余不可编辑
            GridHelper.SetExcludeColumnsActive(ultraGridBeltPre.DisplayLayout.Bands[0], "UNCK");

           // GridHelper.SetNoEnable(ultraGridBeltPre);
            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"));
            
            DataTable dt = new DataTable();
            dt.Columns.Add("TEXT");
            dt.Columns.Add("VALUE");
            dt.Rows.Add("-1", "全部");
            dt.Rows.Add("0", "无效");
            dt.Rows.Add("1", "未使用");
            dt.Rows.Add("2", "使用中");
            dt.Rows.Add("3", "已完成");
            valueToCombo(dt, cmbState);
            this.cmbState.SelectedIndex = 0;


            //预报表转换
            ValueList vlistFlag1 = new ValueList();
            vlistFlag1.ValueListItems.Add("0", "无效");
            vlistFlag1.ValueListItems.Add("1", "未使用");
            vlistFlag1.ValueListItems.Add("2", "使用中");
            vlistFlag1.ValueListItems.Add("3", "已完成");
            this.ultraGridBeltPre.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vlistFlag1;

            InitFromLoad();//加载
            QueryScalePrediction();
        }
        //控件初始化加载
        private void InitFromLoad() {
            try
            {
                RESTfulResult<List<MeterBaseMatterInfo>> rmx = matterInfoService.doQueryListLike(new MeterBaseMatterInfo { validFlag = "1", pageNum = 1, pageSize = 9999 });
                RESTfulResult<List<MeterBaseCustomerSupplier>>  rmx2 = customerSupplierService.doQuery(new MeterBaseCustomerSupplier { validFlag = "1"});
                MeterBaseSpotInfoService meterBaseSpotInfoService = new MeterBaseSpotInfoService();//计量点信息
                RESTfulResult<List<MeterBaseSpotInfo>> spo = meterBaseSpotInfoService.doQueryWf(new MeterBaseSpotInfo { validFlag = "1", spotTypeNo = "001002005" });
                if (spo.Succeed && spo.Data != null && spo.Data.Count > 0)
                {
                    dtPoint = spo.Data.ListToDataTable<MeterBaseSpotInfo>();
                }
                if (dtPoint != null)
                {
                    cbPntName_1.DataSource = dtPoint;
                    cbPntName_1.DisplayMember = "baseSpotName";
                    cbPntName_1.ValueMember = "baseSpotNo";
                }
                cbPntName_1.SelectedIndex = -1;

                if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                {
                    dtMaterial = rmx.Data.ListToDataTable<MeterBaseMatterInfo>();
                    dtMaterial2 = dtMaterial.Copy();
                }
                if (dtMaterial != null)
                {
                    DataRow d1 = dtMaterial.NewRow();
                    d1["matterName"] = "全部";
                    d1["matterNo"] = "0";
                    dtMaterial.Rows.InsertAt(d1, 0);

                    cmMatName.DataSource = dtMaterial;
                    cmMatName.DisplayMember = "matterName";
                    cmMatName.ValueMember = "matterNo";

                    cmMatName_1.DataSource = dtMaterial2;
                    cmMatName_1.DisplayMember = "matterName";
                    cmMatName_1.ValueMember = "matterNo";
                    cmMatName_1.SelectedIndex = -1;
                }
                if (rmx2.Succeed && rmx2.Data != null && rmx2.Data.Count > 0)
                {
                    dtcustomerSupplier = rmx2.Data.ListToDataTable<MeterBaseCustomerSupplier>();
                }
                if (dtcustomerSupplier != null)
                {
                    DataRow d1 = dtcustomerSupplier.NewRow();
                    d1["customerSupplierName"] = "全部";
                    d1["customerSupplierNo"] = "0";
                    dtcustomerSupplier.Rows.InsertAt(d1, 0);
                    cbfahuo.DataSource = dtcustomerSupplier;
                    cbfahuo.DisplayMember = "customerSupplierName";
                    cbfahuo.ValueMember = "customerSupplierNo";

                    cbfahuo_1.DataSource = dtcustomerSupplier.Copy();
                    cbfahuo_1.DisplayMember = "customerSupplierName";
                    cbfahuo_1.ValueMember = "customerSupplierNo";
                    cbfahuo_1.SelectedIndex = -1;

                    DataTable dt2 = new DataTable();
                    dt2.Columns.Add("TEXT");
                    dt2.Columns.Add("VALUE");
                    dt2.Rows.Add("0", "西区炼铁");
                    dt2.Rows.Add("1", "东区炼铁");
                    valueToCombo1(dt2, cbshouh);
                    valueToCombo1(dt2.Copy(), cbshouh_1);
                    this.cbshouh.SelectedIndex = -1;
                    this.cbshouh_1.SelectedIndex = -1;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化失败  " + ex.ToString());
            }
        }
        //获取表单数据
        private PreBeltScaleForecast findFromInfo(int no) {
            PreBeltScaleForecast beltinfo = new PreBeltScaleForecast();
            beltinfo.predictionNo = newGg_text.Text.ToString();
            beltinfo.baseSpotNo = cbPntName_1.SelectedValue.ToString();//计量点编码
            beltinfo.baseSpotName = cbPntName_1.Text.ToString();//计量点
            beltinfo.forwardingUnitNo = cbfahuo_1.SelectedValue.ToString();//发货单位编码
            beltinfo.newSupplier = cbfahuo_1.Text.ToString();//发货单位
            beltinfo.receivingUintNo = cbshouh_1.SelectedValue.ToString();//收货单位编码
            beltinfo.receivingUintName = cbshouh_1.Text.ToString();
            beltinfo.productNo = cmMatName_1.SelectedValue.ToString();//物料编码
            beltinfo.newMatName = cmMatName_1.Text;//物料名称
            beltinfo.overstock = dateTimePicker1.Value;//压港时间
            beltinfo.forwardingWeight = Convert.ToDouble(textBox1.Text);//发运重量
            beltinfo.orderNo = textOrderno.Text.ToString().Trim();//合同号
            beltinfo.newGg = newGg_text.Text.ToString().Trim();//规格
            beltinfo.newMatClass = newMatName_text.Text.ToString().Trim();//物料类别
            beltinfo.newHlh = newHlh_text.Text.ToString().Trim();//海轮号
        //  beltinfo.unloadSite = comboBox5.Text.ToString();//卸货地点
        //  beltinfo.unloadWharf = comboBox5.Text.ToString();//卸货码头
            beltinfo.shipNo = shipnoTxt.Text.ToString();//船号
            if (no == 1)
            {
                beltinfo.createManNo = userId;
                beltinfo.createManName = userName;
            }
            else
            {
                beltinfo.updateManNo = userId;
                beltinfo.updateManName = userName;
            }
            
            return beltinfo;
        }
        // 填充窗口表单
        private void autoAutoFill(PreBeltScaleForecast beltinfo)
        {
            if (beltinfo == null || string.IsNullOrEmpty(beltinfo.predictionNo))
            {
                return;
            }
            cbPntName_1.Text= beltinfo.baseSpotName;//计量点
            cbfahuo_1.Text= beltinfo.newSupplier;//发货单位
            cbshouh_1.Text= beltinfo.receivingUintName;//收货单位
            cmMatName_1.Text= beltinfo.newMatName;//物料名称
            dateTimePicker1.Value= (DateTime)beltinfo.overstock;//压港时间
            textBox1.Text= beltinfo.forwardingWeight.ToString();//发运重量
          //  comboBox1.Text= beltinfo.unloadSite;//卸货地点
          //  comboBox5.Text= beltinfo.unloadSite;//卸货地点
            shipnoTxt.Text= beltinfo.shipNo;//船号
            //textPrediction.Text = beltinfo.predictionNo;
            textOrderno.Text = beltinfo.orderNo;
            newMatName_text.Text = beltinfo.newMatClass;//物料类别
            newHlh_text.Text = beltinfo.newHlh;//海轮号
            newGg_text.Text = beltinfo.newGg;//规格
        }
        //下拉框控件自定义option
        public static void valueToCombo(DataTable source, UltraComboEditor cbb)
        {
            cbb.DataSource = source;
            cbb.DisplayMember = "VALUE";
            cbb.ValueMember = "TEXT";
        }
        //下拉框控件自定义option
        public static void valueToCombo1(DataTable source, ComboBox cbb)
        {
            cbb.DataSource = source;
            cbb.DisplayMember = "VALUE";
            cbb.ValueMember = "TEXT";
        }
        //时间控件开关
        private void checkDate_CheckedChanged(object sender, EventArgs e)
        {
            if (checkDate.Checked)
            {
                dtStartTime.Enabled = true;
                dtEndTime.Enabled = true;
            }
            else
            {
                dtStartTime.Enabled = false;
                dtEndTime.Enabled = false;
            }
        }
        //控制文本框格式
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            int keyValue = (int)e.KeyChar;
            if ((keyValue >= 48 && keyValue <= 57) || keyValue == 8 || keyValue == 46)
            {
                if (sender != null && sender is TextBox && keyValue == 46)
                {
                    if (((TextBox)sender).Text.IndexOf(".") >= 0)
                        e.Handled = true;
                    else
                        e.Handled = false;
                }
                else
                    e.Handled = false;
            }
            else
                e.Handled = true;
        }

        private void ultraGridBeltPre_CellChange(object sender, CellEventArgs e)
        {
            if (e.Cell.Column.Key == "UNCK")
            {
                checkGridCell(ultraGridBeltPre);
            }

        }
        private void checkGridCell(UltraGrid grid)
        {
            try
            {
                grid.UpdateData();
                List<UltraGridRow> row = GridHelper.SetAllColumnsCheckByCode(grid, "predictionNo", "UNCK", IsBatch);
                if (row.Count == 0)
                {
                    clearGridInfo();
                    return;
                }
                PreBeltScaleForecast beltinfo = new PreBeltScaleForecast();//预报实体
                //界面赋值
                UltraGridRow ugr = row[0];
                if (ugr != null)
                {
                    beltinfo.predictionNo = ugr.Cells["predictionNo"].Text.Trim(); //预报编号
                    beltinfo.baseSpotNo = ugr.Cells["baseSpotNo"].Text.ToString();//计量点编码
                    beltinfo.baseSpotName = ugr.Cells["baseSpotName"].Text.ToString();//计量点
                    beltinfo.overstock = ugr.Cells["overstock"].Text.ToString() == "" ? DateTime.Now : Convert.ToDateTime(ugr.Cells["overstock"].Text.ToString());//压港时间
                    beltinfo.forwardingWeight = ugr.Cells["forwardingWeight"].Text.Trim() == "" ? 0 : Convert.ToDouble(ugr.Cells["forwardingWeight"].Text.Trim());//发运重量
                    beltinfo.unloadSite = ugr.Cells["unloadSite"].Text.Trim();//卸货地点
                    beltinfo.unloadWharf = ugr.Cells["unloadWharf"].Text.Trim();//卸货码头
                    beltinfo.shipNo = ugr.Cells["shipNo"].Text.Trim();//船号
                    beltinfo.newSupplier = ugr.Cells["newSupplier"].Text.Trim();//发货单位
                    beltinfo.receivingUintName = ugr.Cells["receivingUintName"].Text.Trim(); //收货单位
                    beltinfo.forwardingUnitNo = ugr.Cells["forwardingUnitNo"].Text.Trim();//发货单位编号
                    beltinfo.receivingUintNo = ugr.Cells["receivingUintNo"].Text.Trim();//收货单位编号
                    beltinfo.newMatName = ugr.Cells["newMatName"].Text.Trim();   //物料名称
                    beltinfo.productNo = ugr.Cells["productNo"].Text.Trim();//物料编号
                    beltinfo.orderNo = ugr.Cells["orderNo"].Text.Trim();//合同号
                    beltinfo.newMatClass = ugr.Cells["newMatClass"].Text.Trim();//物料类别
                    beltinfo.newHlh = ugr.Cells["newHlh"].Text.Trim();//海轮号
                    beltinfo.newGg = ugr.Cells["newGg"].Text.Trim();//规格
                    autoAutoFill(beltinfo);

                }
            }catch (Exception ex)
            {
                MessageBox.Show("处理异常：" + ex);
            }
        }
        private Boolean IsBatch = false;
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                IsBatch = true;
            }
            else
            {
                IsBatch = false;
            }

        }

        private void clearGridInfo() {
            cbPntName_1.Text = "";//计量点
            cbfahuo_1.Text = "";//发货单位
            cbshouh_1.Text = "";//收货单位
            cmMatName_1.Text = "";//物料名称
            textBox1.Text = "";//发运重量                        
            shipnoTxt.Text = "";//船号
            newGg_text.Text = "";
        }


        #endregion
    }
}