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 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 frmBeltMatPmInfo : Form
    {
        public frmBeltMatPmInfo()
        {
            InitializeComponent();
        }

        //菜单栏事件
        private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                case "查询":
                    Query();
                    break;
                case "新增":
                    Add();
                    break;
                case "修改":
                    Update();
                    break;
                case "导出":
                    Exporter();
                    break;
                case "删除":
                    Delete();
                    break;
                case "还原":
                    Recover();
                    break;
                case "物料分配":
                    UpdateMatType();
                    break;
            }
        }


        #region 自定义变量
        private ComBaseInfoService comBaseInfoService = new ComBaseInfoService(); //基础数服务
        private MeterBaseBeltMaterialpmService materialpmService = new MeterBaseBeltMaterialpmService();//物料系数服务
        MeterBaseMatterInfoService matterInfoService = new MeterBaseMatterInfoService();//物料服务
        private string userId = "", userName = ""; //用户ID用户名
        private DataTable dtPoint;//计量点数据源
        MeterBaseOperationLogService LogService = new MeterBaseOperationLogService();//日志服务
        MeterBasemeterMaterialpm nowPm = new MeterBasemeterMaterialpm();
        #endregion


        #region 菜单栏方法
        //物料系数查询
        private void Query() {
            try
            {
                MeterBasemeterMaterialpm materialpm = new MeterBasemeterMaterialpm();
                if (ultraCombo1.Text!="") {
                    materialpm.materialType = ultraCombo1.Text.ToString();
                }
                if (cbSpotName.Text != "")
                {
                    materialpm.baseSpotName = cbSpotName.Text.ToString();
                }
                DataTable dtScaleTable = dataTable1.Clone();
                RESTfulResult<List<MeterBasemeterMaterialpm>> rms = materialpmService.doQueryWf(materialpm);
                if (rms.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        dtScaleTable = rms.Data.ListToDataTable<MeterBasemeterMaterialpm>();

                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridBeltMat);
                        foreach (UltraGridRow ugr in ultraGridBeltMat.Rows)
                        {
                            if (ugr.Cells["validFlag"].Value.ToString() == "0")
                            {
                                ugr.Appearance.BackColor = Color.Red;
                            }
                            else
                            {
                                ugr.Appearance.BackColor = Color.White;
                            }
                        }
                    }
                    else
                    {
                        dtScaleTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridBeltMat);
                    }
                }
                MeterBaseMatterInfoService meterBaseMatterInfo = new MeterBaseMatterInfoService();//物料服务
                MeterBaseMatterInfo MatterInfo1 = new MeterBaseMatterInfo();
                if (textWgtName.Text.ToString().Trim()!="") {
                    MatterInfo1.matterName = textWgtName.Text.ToString().Trim();
                }
                MatterInfo1.validFlag = "1";
                MatterInfo1.pageNum = 1;
                MatterInfo1.pageSize = 9999;
                if (!checkBox1.Checked) {
                    MatterInfo1.beltTypeName = "1";
                }
                DataTable dtMatTable = dataTable2.Clone();
                RESTfulResult<List<MeterBaseMatterInfo>> rmx = meterBaseMatterInfo.doQueryListLike(MatterInfo1);
                if (rmx.Succeed)
                {
                    if (rmx.Data != null && rmx.Data.Count > 0)
                    {
                        dtMatTable = rmx.Data.ListToDataTable<MeterBaseMatterInfo>();

                        ClsControlPack.CopyDataToDatatable(ref dtMatTable, ref dataTable2, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                        foreach (UltraGridRow ugr in ultraGrid1.Rows)
                        {
                            if (ugr.Cells["beltTypeName"].Value.ToString() == "")
                            {
                                ugr.Appearance.BackColor = Color.Red;
                            }
                            else
                            {
                                ugr.Appearance.BackColor = Color.White;
                            }
                        }
                    }
                    else
                    {
                        dtMatTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtMatTable, ref dataTable2, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                    }
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show("物料系数查询失败，请联系技术中心！" + ex.Message);
                return;
            }
        }
        //物料系数新增
        private void Add() {
            MeterBasemeterMaterialpm pm = findFromInfo(1);
            if (pm==null) {
                return;
            }
            RESTfulResult<string> rm = materialpmService.doAddBeltScalePrediction(pm);
            if (rm.Succeed)
            {
                Addlog(pm, nowPm, "修改");
                MessageBox.Show("新增物料系数成功");
                Query();
                return;
            }
            else
            {
                MessageBox.Show("新增物料系数失败，请联系技术中心！" + rm.Message);
                return;
            }
        }
        //物料系数修改
        private void Update()
        {
            try
            {
                MeterBasemeterMaterialpm pm = findFromInfo(2);
                if (pm == null)
                {
                    return;
                }
                RESTfulResult<string> rm = materialpmService.doUpdateWf(pm);
                if (rm.Succeed)
                {
                    Addlog(pm, nowPm,"新增");
                    MessageBox.Show("物料系数修改成功");
                    Query();
                    return;
                }
                else
                {
                    MessageBox.Show("物料系数修改失败，请联系技术中心！" + rm.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("物料系数修改异常！" + ex.Message);
                return;
            }
        }
        private void Addlog(MeterBasemeterMaterialpm newPm, MeterBasemeterMaterialpm oldPm,string Function) {
            MeterBaseOperationLog log = new MeterBaseOperationLog();
            log.operationId = newPm.materialPmCode;
            log.operationPage = "物料系数维护";
            log.operationFunction = Function;
            log.operationBeforeFix = "-卸货码头:"+oldPm.baseSpotName+"-秤台:"+oldPm.scaleName+"-物料类型:"+oldPm.materialType + "-国内：" + oldPm.materialParameter + "-进口：" + oldPm.materialParameterImport+"";
            log.operationAfterFix = "-卸货码头:"+ newPm.baseSpotName+"-秤台："+ newPm.scaleName+"-物料类型;"+ newPm.materialType + "-国内：" + newPm.materialParameter + "-进口：" + newPm.materialParameterImport+"";
            log.logType = "皮带秤";
            log.logTypeCode = "001002005";
            log.createManNo = userId;
            log.createManName = userName;
            RESTfulResult<string> rESTfulResult = LogService.AddLog(log);
            if (!rESTfulResult.Succeed) {
                MessageBox.Show("新增日志错误" + rESTfulResult.Message);
                return;
            }
        }
        //修改物料分类
        private void UpdateMatType() {
            try
            {
                List<MeterBaseMatterInfo> list = new List<MeterBaseMatterInfo>();//物料系数实体
                string flag = "";
                //获取已选择的列
                List<UltraGridRow> uGrid = GridHelper.UltraGridGetChooseRows(ultraGrid1, "UNCK");
                if (uGrid.Count <= 0)
                {
                    MessageBox.Show("请选择需要分配的物料系数！");
                    return;
                }
                foreach (UltraGridRow ugr in uGrid)
                {
                    flag = ugr.Cells["beltTypeName"].Value.ToString();
                    //if (flag != "")
                    //{
                    //    MessageBox.Show("存在物料已分配系数类型，不允许批量操作!");
                    //    return;
                    //}
                    list.Add(new MeterBaseMatterInfo { validFlag = "1", 
                        matterNo = ugr.Cells["matterNo"].Value.ToString(),
                        beltTypeCode=cbMatType2.Value.ToString(),
                        beltTypeName=cbMatType2.Text.ToString() });
                }
                RESTfulResult<int> rm = matterInfoService.doUpdateType(list);
                if (rm.Succeed)
                {
                    MessageBox.Show("物料分类成功！");
                    Query();
                    return;
                }
                else
                {
                    MessageBox.Show("物料分类失败，请联系技术中心！" + rm.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("物料分类异常！" + ex.Message);
                return;
            }
        }
        //导出物料系数数据
        private void Exporter() {
            string str = Interaction.InputBox("请输入要导出的文件名", "提示", "", 100, 100);
            string pqath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

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

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

        }

        private void frmBeltMatPmInfo_Load(object sender, EventArgs e)
        {

            cb2.SelectedIndex = -1;
            RESTfulResult<List<ComBaseInfo>> rrComGradeName = comBaseInfoService.doQueryBaseList(new ComBaseInfo { validFlag = "1", pBaseCode = "001046" });
            if (rrComGradeName.Succeed && rrComGradeName.Data != null && rrComGradeName.Data.Count > 0)
            {
                rrComGradeName.Data.Sort((a, b) => a.baseName.CompareTo(b.baseName));
                ClsControlPack.SetUltraComboDataSource(cbMatType, rrComGradeName.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
                ClsControlPack.SetUltraComboDataSource(ultraCombo1, rrComGradeName.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
                ClsControlPack.SetUltraComboDataSource(cbMatType2, rrComGradeName.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("物料系数信息载入失败!");
                return;
            }
            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)
            {
                cb1.DataSource = dtPoint;
                cb1.DisplayMember = "baseSpotName";
                cb1.ValueMember = "baseSpotNo";
                DataTable data1 = new DataTable();
                data1 = dtPoint.Copy();
                cbSpotName.DataSource = data1;
                cbSpotName.DisplayMember = "baseSpotName";
                cbSpotName.ValueMember = "baseSpotNo";
                
            }
            cbSpotName.SelectedIndex = -1;
            cb1.SelectedIndex = -1;


            //RESTfulResult<List<MeterBaseScalePoint>> rmx3 = monitorService.doQueryWf(new MeterBaseScalePoint { spotTypeNo = "001002005", validFlag = "1" });

            //if (rmx3.Succeed && rmx3.Data != null && rmx3.Data.Count > 0)
            //{
            //    dtPoint = rmx3.Data.ListToDataTable<MeterBaseScalePoint>();
            //}
            //if (dtPoint != null)
            //{
            //    cb1.DataSource = dtPoint;
            //    cb1.DisplayMember = "baseSpotName";
            //    cb1.ValueMember = "baseSpotNo";
            //}

            ValueList vlistFlag4 = new ValueList();
            vlistFlag4.ValueListItems.Add("0", "无效");
            vlistFlag4.ValueListItems.Add("1", "有效");
            this.ultraGridBeltMat.DisplayLayout.Bands[0].Columns["validFlag"].ValueList = vlistFlag4;

            //设置grid除了选择列 其余不可编辑
            GridHelper.SetExcludeColumnsActive(ultraGridBeltMat.DisplayLayout.Bands[0], "UNCK");

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

        private void ultraGridBeltMat_CellChange(object sender, CellEventArgs e)
        {
            if (e.Cell.Column.Key == "UNCK")
            {
                checkGridCell(ultraGridBeltMat);
            }
        }
        #endregion
        private void cleanFromInfo(){
            text1.Text = "";
            cb1.Text = "";
            cb2.Text = "";
            text2.Text = "";
            cbMatType.Text = "";
        }
        private void checkGridCell(UltraGrid grid) {
            try
            {
                grid.UpdateData();
                List<UltraGridRow> row =  GridHelper.SetAllColumnsCheckByCode(grid, "materialPmCode", "UNCK");
                if (row.Count == 0) {
                    cleanFromInfo();
                    return;
                }
                MeterBasemeterMaterialpm model = new MeterBasemeterMaterialpm();//实绩实体
                //界面赋值
                UltraGridRow ugr = row[0];
                if (ugr != null)
                {
                    model.materialPmCode = ugr.Cells["materialPmCode"].Text.Trim();//系数编号
                    model.materialTypeCode = ugr.Cells["materialTypeCode"].Text.Trim();//系数类型编号
                    model.materialType = ugr.Cells["materialType"].Text.Trim();//系数类型名称
                    model.scaleName = ugr.Cells["scaleName"].Text.Trim();//ab秤
                    model.baseSpotNo = ugr.Cells["baseSpotNo"].Text.Trim();//计量点编号
                    model.baseSpotName = ugr.Cells["baseSpotName"].Text.Trim();//计量点名称
                    model.materialParameter = ugr.Cells["materialParameter"].Text.ToString() == "" ? 0:Convert.ToDouble(ugr.Cells["materialParameter"].Text.ToString()) ;//国内系数
                    model.materialParameterImport = ugr.Cells["materialParameterImport"].Text.ToString() == "" ? 0 : Convert.ToDouble(ugr.Cells["materialParameterImport"].Text.ToString()); //进口系数
                    model.materialPmCode = ugr.Cells["materialPmCode"].Text.Trim();;//该条数据编码
                    nowPm = model;
                    autoAutoFill(model);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("处理异常：" + ex);
            }
        }
        //填充窗口表单
        private void autoAutoFill(MeterBasemeterMaterialpm model)
        {
            if (model == null || string.IsNullOrEmpty(model.materialPmCode))
            {
                return;
            }
            text1.Text = model.materialParameter.ToString();
            text2.Text = model.materialParameterImport.ToString();
            cb1.Text = model.baseSpotName.ToString();
            cb2.Text = model.scaleName.ToString();
            cbMatType.Text = model.materialType.ToString();
            test.Text = model.materialPmCode.ToString();
        }

        #region 公共方法区
        //获取表单数据
        private MeterBasemeterMaterialpm findFromInfo(int no)
        {
            MeterBasemeterMaterialpm materialpm = new MeterBasemeterMaterialpm();
            materialpm.baseSpotNo = cb1.SelectedValue.ToString();//计量点编码
            materialpm.materialTypeCode = cbMatType.Value.ToString();//物料类型编码
            materialpm.scaleName = cb2.Text.ToString();//AB
            RESTfulResult<List<MeterBasemeterMaterialpm>> Result = materialpmService.doQueryWf(materialpm);
            if (Result.Succeed) {
                materialpm.baseSpotName = cb1.Text.ToString();//计量点
                materialpm.materialType = cbMatType.Text.ToString();//物料类型
                materialpm.materialParameter = text1.Text.ToString().Trim() == "" ? 0 : Convert.ToDouble(text1.Text.ToString().Trim());
                materialpm.materialParameterImport = text2.Text.ToString().Trim() == "" ? 0 : Convert.ToDouble(text2.Text.ToString().Trim());
                if (no == 1)
                {
                    materialpm.createManNo = userId;
                    materialpm.createManName = userName;
                }
                else
                {
                    materialpm.updateManNo = userId;
                    materialpm.updateManName = userName;
                    materialpm.materialPmCode = this.test.Text.ToString();
                }
                if (Result.Data.Count == 1)
                {
                    if (no == 1)
                    {
                        MessageBox.Show("该计量点-物料类型-秤台已存在！,不能新增");
                        return null;
                    }
                    else if (no == 2)
                    {
                        if (Result.Data[0].materialPmCode != test.Text.ToString())
                        {
                            MessageBox.Show("该计量点-物料类型-秤台已存在！,不能修改");
                            return null;
                        }
                        else {
                            return materialpm;
                        }

                    }
                }
                else if (Result.Data.Count == 0)
                {
                    return materialpm;
                }
                else {
                    MessageBox.Show("该计量点-物料类型-秤台存在的数量大于1条，请管理员检查！");
                    return null;
                }
                  
            }
            return null;
           
        }
        #endregion
    }
}