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

        //菜单栏事件
        private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                case "查询":
                    QueryScaleActualinfo();
                    break;
                case "导出":
                    ExporterScaleActual();
                    break;
                case "打印":
                    Print();
                    break;
                
            }
        }

        #region 自定义变量
        private MeterWorkBeltActualService BeltActualService = new MeterWorkBeltActualService();
        private DataTable dtMaterial;//物料数据源
        private DataTable dtcustomerSupplier;//发货单位数据源
        MeterBaseMatterInfoService meterBaseMatterInfo = new MeterBaseMatterInfoService();//物料服务
        MeterBaseCustomerSupplierService customerSupplierService = new MeterBaseCustomerSupplierService();
        private  string userName="",userId;
        MeterBaseOperationLogService LogService = new MeterBaseOperationLogService();//日志服务
        private Log l = Log.GetInstance(); //日志
        #endregion

        #region 菜单栏方法
        //实绩查询
        private void QueryScaleActualinfo() {
            try
            {
                CommonPage<MeterWorkBeltActual> cp = new CommonPage<MeterWorkBeltActual>();
                MeterWorkBeltActual actual = new MeterWorkBeltActual();
                DataTable dtScaleTable = dataTable1.Clone();
                if (checkDate.Checked)
                {
                    if (DateTime.Compare(dtStartTime.Value, dtEndTime.Value) > 0)
                    {
                        MessageBox.Show("开始时间不能大于结束时间");
                        return;
                    }
                    cp.startTime = dtStartTime.Value.ToString();
                    cp.endTime = dtEndTime.Value.ToString();
                }
                else {
                    MessageBox.Show("请勾选查询时间");
                    return;
                }
                if (cmMatName.Text.ToString() != "全部" && cmMatName.Text.ToString() != "")
                {
                    actual.newMatName = cmMatName.Text.ToString();
                }
                else {
                    actual.newMatName = "1";
                }
                if (cbfahuo.Text.ToString() != "全部"&&cbfahuo.Text.ToString()!="")
                {
                    actual.newSupplier = cbfahuo.Text.ToString().Trim();
                }
                else
                {
                    actual.newSupplier = "1";
                }
                if (cbshouh.Text.ToString() != "全部" && cbshouh.Text.ToString() != "")
                {
                    actual.receivingUintName = cbshouh.Text.ToString().Trim();
                }
                else
                {
                    actual.receivingUintName = "1";
                }
                if (ShipnoTxt_1.Text.ToString().Trim() != "")
                {
                    actual.shipNo = ShipnoTxt_1.Text.ToString().Trim();
                }
                else
                {
                    actual.shipNo = "1";
                }
                if (moteTxt_1.Text.ToString().Trim()!="")
                {
                    actual.unloadSite = moteTxt_1.Text.ToString().Trim();
                }
                else
                {
                    actual.unloadSite = "1";
                }
                actual.valueFlag = "1";//查询有效
                actual.checkFlag = "1";//已审核的数据
                actual.orderNo = "1";//不为空则分组
                cp.param = actual;
                RESTfulResult<List<MeterWorkBeltActual>> rms = BeltActualService.doQueryActualInfoAndGroup(cp);
                if (rms.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        dtScaleTable = rms.Data.ListToDataTable<MeterWorkBeltActual>();

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

                    }
                    else
                    {
                        dtScaleTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(beltActualGrid);
                    }
                }
                else
                {
                    MessageBox.Show("查询失败，请联系技术中心！" + rms.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("预报查询异常，请联系技术中心！" + ex.Message);
                return;
            }
        }

        //票据打印
        private void Print() {
            if (ultraGrid1.Rows.Count == 0)
            {
                return;
            }
            ArrayList arry = new ArrayList();
            string _BILLNO = "";
            MeterWorkBeltActual meterWorkBeltActual = new MeterWorkBeltActual();
            meterWorkBeltActual.printNo = "JGPD-R" + DateTime.Now.ToString("yyyyMMdd");
            meterWorkBeltActual.checkFlag = "1";
            meterWorkBeltActual.valueFlag = "1";
            RESTfulResult<List<MeterWorkBeltActual>> Result = BeltActualService.doQueryMaxPno(meterWorkBeltActual);

            if (ultraGrid1.ActiveRow.Cells["printNo"].Text.ToString().Trim() != "")
            {//使用已有编号
                _BILLNO = ultraGrid1.ActiveRow.Cells["printNo"].Text.ToString().Trim();
            }
            else {
                
                    if (ultraGrid1.Rows.Count >= 0 )
                    {//使用第一个编号
                        if (Result.Data[0] == null)
                        {
                            _BILLNO = "JGPD-R" + DateTime.Now.ToString("yyyyMMdd") + "-" + "0001";
                        }else {
                        //根据已有编号 自增
                        _BILLNO = Convert.ToString(Convert.ToInt32(Result.Data[0].printNo.ToString().Split('-')[2].ToString()) + 1);
                            if (_BILLNO.Length < 4)
                            {
                                string ss = "";
                                for (int i = 1; i <= 4 - _BILLNO.Length; i++)
                                {
                                    ss += "0";
                                }
                                _BILLNO = ss + _BILLNO;
                            }

                            _BILLNO = Result.Data[0].printNo.ToString().Remove(Result.Data[0].printNo.ToString().Length - 4, 4) + _BILLNO;

                        }
                }
                else
                {
                    MessageBox.Show("下方表格暂无数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }


            }
            arry.Add(_BILLNO);
            string titledate = "日期:";
            if (ultraGrid1.Rows.Count == 1)
            {
                titledate += ultraGrid1.ActiveRow.Cells["endTime"].Text.Substring(0, 10);
            }
            else 
            {
                int a = ultraGrid1.ActiveRow.Cells["endTime"].Text.Length;
                string[] str = ultraGrid1.Rows[0].Cells["endTime"].Text.Split(' ');
                string[] end = ultraGrid1.Rows[ultraGrid1.Rows.Count - 1].Cells["endTime"].Text.Split(' ');

                string dayall = str[0].ToString() + "-" + end[0].ToString();
                titledate += dayall;
            }
            arry.Add(titledate);
            arry.Add(ultraGrid1.ActiveRow.Cells["newSupplier"].Text);
            arry.Add(ultraGrid1.ActiveRow.Cells["receivingUintName"].Text);
            arry.Add(ultraGrid1.ActiveRow.Cells["newMatName"].Text);
            arry.Add(ultraGrid1.ActiveRow.Cells["shipNo"].Text);//船号
            arry.Add(ultraGrid1.ActiveRow.Cells["orderNo"].Text);//合同号
            arry.Add(ultraGrid1.ActiveRow.Cells["newMatClass"].Text);//物料类别
            arry.Add(ultraGrid1.ActiveRow.Cells["newGg"].Text);//规格
            arry.Add(ultraGrid1.ActiveRow.Cells["endTime"].Text.Substring(0, 10));
            arry.Add(ultraGrid1.ActiveRow.Cells["baseSpotName"].Text);
            arry.Add(ultraGrid1.ActiveRow.Cells["netWeight"].Text);
            arry.Add(ultraGrid1.ActiveRow.Cells["newHlh"].Text);//海轮号

            string preNo = ultraGrid1.ActiveRow.Cells["predictionNo"].Text;
            string actualNo = ultraGrid1.ActiveRow.Cells["actualNo"].Text;

            MeterWorkBeltActual Actualprint = new MeterWorkBeltActual();
            Actualprint.orderNo = ultraGrid1.ActiveRow.Cells["orderNo"].Text;
            if (ultraGrid1.ActiveRow.Cells["printNum"].Text == "0")
            {
                Actualprint.firstPrint = userName;
            }
            else {
                Actualprint.secondPrint = userName;
            }
            Actualprint.printNo = _BILLNO;
            Actualprint.printNum = Convert.ToInt16(ultraGrid1.ActiveRow.Cells["printNum"].Text)+1;
            RESTfulResult<string> Results = BeltActualService.doUpdateWf(Actualprint);
            if (!Results.Succeed) {
                MessageBox.Show("修改打印人错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            Boolean IsHaveMemo = false;
            for (int i = 1; i < ultraGrid1.Rows.Count; i++)
            {
                arry.Add(ultraGrid1.Rows[i].Cells["endTime"].Text.Substring(0, 10));
                arry.Add(ultraGrid1.Rows[i].Cells["baseSpotName"].Text);
                arry.Add(ultraGrid1.Rows[i].Cells["netWeight"].Text);
                if (i==2&&!IsHaveMemo) {
                    arry.Add(ultraGrid1.ActiveRow.Cells["unloadSite"].Text);//备注
                    IsHaveMemo = true;
                }
            }
            for (int j = ultraGrid1.Rows.Count; j < 6; j++)
            {
                arry.Add("");
                arry.Add("");
                arry.Add("");
                if (j == 2 && !IsHaveMemo)
                {
                    arry.Add(ultraGrid1.ActiveRow.Cells["unloadSite"].Text);//备注
                    IsHaveMemo = true;
                }
            }
            if (ultraGrid1.Rows.Count == 1)
            {
                arry.Add(ultraGrid1.Rows[0].Cells["netWeight"].Text);
            }
            if (ultraGrid1.Rows.Count > 1)
            {
                decimal sum_net_wgt = 0;
                for (int a = 0; a < ultraGrid1.Rows.Count; a++)
                {
                    sum_net_wgt += Convert.ToDecimal(ultraGrid1.Rows[a].Cells["netWeight"].Text.ToString());
                }
                arry.Add(sum_net_wgt);
            }
            if (ultraGrid1.ActiveRow.Cells["newMatName"].Text == "焦粉" && ultraGrid1.ActiveRow.Cells["printNum"].Text == "1")
            {
                MessageBox.Show("焦粉物料，当前打印第"+(Convert.ToInt16(ultraGrid1.ActiveRow.Cells["printNum"].Text)+1).ToString() +"次！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else if(ultraGrid1.ActiveRow.Cells["newMatName"].Text != "焦粉" && Convert.ToInt16(ultraGrid1.ActiveRow.Cells["printNum"].Text) >= 2)
            {
                MessageBox.Show("焦粉物料，当前打印第" + (Convert.ToInt16(ultraGrid1.ActiveRow.Cells["printNum"].Text) + 1).ToString() + "次！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            PrintSolution.ExcelPrinter ePrinter = new PrintSolution.ExcelPrinter("weight2.xml", arry);
            ePrinter.PageSetup.IsCustom = true;
            ePrinter.PageSetup.TopMargin = 0.5;
            ePrinter.PageSetup.BottomMargin = 1;
            ePrinter.PageSetup.LeftMargin = 1;
            ePrinter.PageSetup.RightMargin = 1;
            ePrinter.printExcel();
            Addlog(actualNo, preNo,arry);
        }
        //日志
        public void Addlog(string actualNo,string preNo, ArrayList list)
        {
            try
            {

                MeterBaseOperationLog log = new MeterBaseOperationLog();
                log.operationId = preNo;
                log.operationPage = "票据打印";
                log.operationFunction = "修改";
                string content = "";
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].ToString() != "")
                    {
                        content += "-" + list[i].ToString();
                    }
                }
                log.operationBeforeFix = "打印数据" + content;
                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;
                }
            }
            catch (Exception ex) {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }

        //导出
        private void ExporterScaleActual()
        {
            string str = Interaction.InputBox("请输入要导出的文件名", "提示", "", 100, 100);
            string pqath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

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

        #region 公共方法区
        //初始化加载
        private void frmBeltScaleActualinfo_Load(object sender, EventArgs e)
        {
            userName = ((ST_MainForm)(this.MdiParent)).UserName;
            userId = ((ST_MainForm)(this.MdiParent)).UserID;
            //设置grid除了选择列 其余不可编辑
            GridHelper.SetExcludeColumnsActive(beltActualGrid.DisplayLayout.Bands[0], "UNCK");
            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")); 


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

            ValueList vlistFlag4 = new ValueList();
            vlistFlag4.ValueListItems.Add("0", "未审核");
            vlistFlag4.ValueListItems.Add("1", "已审核");
            this.beltActualGrid.DisplayLayout.Bands[0].Columns["checkFlag"].ValueList = vlistFlag4;

            InitFromLoad();//加载物料
            QueryScaleActualinfo();
        }
        //下拉框控件自定义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 InitFromLoad()
        {
            try
            {
                RESTfulResult<List<MeterBaseMatterInfo>> rmx = meterBaseMatterInfo.doQueryListLike(new MeterBaseMatterInfo { validFlag = "1", pageNum = 1, pageSize = 9999 });
                RESTfulResult<List<MeterBaseCustomerSupplier>> rmx2 = customerSupplierService.doQuery(new MeterBaseCustomerSupplier { validFlag = "1"});
               

                if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                {
                    dtMaterial = rmx.Data.ListToDataTable<MeterBaseMatterInfo>();
                }
                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";
                }
                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";

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

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化失败  " + ex.ToString());
            }
        }
   
        //日期选择框
        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 ckShipNo_CheckedChanged(object sender, EventArgs e)
        {
            if (ckShipNo.Checked)
            {
                ShipnoTxt_1.Enabled = true;
            }
            else
            {
                ShipnoTxt_1.Enabled = false;
            }
        }


        #endregion

        private void beltActualGrid_CellChange(object sender, CellEventArgs e)
        {
            if (e.Cell.Column.Key == "UNCK")
            {
                checkGridCell(beltActualGrid);
            }
        }
        private void checkGridCell(UltraGrid grid)
        {
            try
            {
                grid.UpdateData();
                List<UltraGridRow> row = GridHelper.SetAllColumnsCheckByCode(beltActualGrid, "orderNo", "UNCK");
                if (row.Count == 0)
                {
                    clearGridTable();
                    return;
                }
                //界面赋值
                UltraGridRow ugr = row[0];
                if (ugr != null && ugr.Cells["orderNo"].Text.Trim() != "")
                {
                    // findActualById(ugr.Cells["orderNo"].Text.Trim());
                    CommonPage<MeterWorkBeltActual> cp2 = new CommonPage<MeterWorkBeltActual>();
                    MeterWorkBeltActual meterWorkBeltActual = new MeterWorkBeltActual();
                    meterWorkBeltActual.orderNo = ugr.Cells["orderNo"].Text.Trim();
                    if (meterWorkBeltActual.orderNo != "")
                    {
                        meterWorkBeltActual.valueFlag = "1";
                        meterWorkBeltActual.checkFlag = "1";
                        meterWorkBeltActual.newSupplier = ugr.Cells["newSupplier"].Text.Trim();
                        meterWorkBeltActual.receivingUintName = ugr.Cells["receivingUintName"].Text.Trim();
                        meterWorkBeltActual.shipNo = ugr.Cells["shipNo"].Text.Trim();
                        meterWorkBeltActual.newMatName = ugr.Cells["newMatName"].Text.Trim();
                        if (checkDate.Checked)
                        {
                            if (DateTime.Compare(dtStartTime.Value, dtEndTime.Value) > 0)
                            {
                                MessageBox.Show("开始时间不能大于结束时间");
                                return;
                            }
                            cp2.startTime = dtStartTime.Value.ToString();
                            cp2.endTime = dtEndTime.Value.ToString();
                        }
                        else
                        {
                            MessageBox.Show("请勾选查询时间");
                            return;
                        }
                        meterWorkBeltActual.checkTime = DateTime.Now;
                        cp2.param = meterWorkBeltActual;
                        DataTable dtScaleTable = dataTable2.Clone();
                        RESTfulResult<List<MeterWorkBeltActual>> rms = BeltActualService.doQueryAndMultiple(cp2);
                        if (rms.Succeed)
                        {
                            if (rms.Data != null && rms.Data.Count > 0)
                            {
                                dtScaleTable = rms.Data.ListToDataTable<MeterWorkBeltActual>();
                                ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable2, true);
                                ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                            }
                            else
                            {
                                dtScaleTable.Clear();
                                ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable2, true);
                                ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                            }
                        }
                        else
                        {
                            MessageBox.Show("查询失败，请联系技术中心！" + rms.Message);
                            return;
                        }
                    }
                }
                else {
                    clearGridTable();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("checkGridCell方法处理异常：" + ex);
            }
        }
        private void clearGridTable() {
            DataTable dtScaleTable = dataTable2.Clone();
            dtScaleTable.Clear();
            ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable2, true);
            ClsControlPack.RefreshAndAutoSize(ultraGrid1);
        }
        //根据合同号查询实绩
        private void findActualById(string orderno)
        {
            CommonPage<MeterWorkBeltActual> cp2 = new CommonPage<MeterWorkBeltActual>();
            MeterWorkBeltActual meterWorkBeltActual = new MeterWorkBeltActual();
            if (orderno != "")
            {
                meterWorkBeltActual.valueFlag = "1";
                meterWorkBeltActual.checkFlag = "1";
                meterWorkBeltActual.orderNo = orderno;
                if (checkDate.Checked)
                {
                    if (DateTime.Compare(dtStartTime.Value, dtEndTime.Value) > 0)
                    {
                        MessageBox.Show("开始时间不能大于结束时间");
                        return;
                    }
                    cp2.startTime = dtStartTime.Value.ToString();
                    cp2.endTime = dtEndTime.Value.ToString();
                }
                else
                {
                    MessageBox.Show("请勾选查询时间");
                    return;
                }
                meterWorkBeltActual.checkTime = DateTime.Now;
                cp2.param = meterWorkBeltActual;
                DataTable dtScaleTable = dataTable2.Clone();
                RESTfulResult<List<MeterWorkBeltActual>> rms = BeltActualService.doQueryAndMultiple(cp2);
                if (rms.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        dtScaleTable = rms.Data.ListToDataTable<MeterWorkBeltActual>();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable2, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                    }
                    else
                    {
                        dtScaleTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable2, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                    }
                }
                else
                {
                    MessageBox.Show("查询失败，请联系技术中心！" + rms.Message);
                    return;
                }
            }
        }
    }
}