using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace SSLMS.MobileUI.uc
{
    public partial class ucMANAGE_INOUT : UserControl
    {
        private PLAN_MAIN _mPLAN_MAIN;

        private PLAN_TYPE _mPLAN_TYPE;

        private bool _bZuPan
        {
            get { return !string.IsNullOrEmpty(this.txtSTOCK_BARCODE.Text) && "1".Equals(this._mPLAN_TYPE._plan_type_inout); }
        }

        private bool _bAddSTOCK
        {
            get
            {

                string AREA_ID = this.cmbAREA.SelectedValue.ToString();

                string STOCK_BARCODE = this.txtSTOCK_BARCODE.Text.Trim();

                string sResult = string.Empty; ;

                return this._bZuPan && ("1".Equals(this._mPLAN_TYPE._plan_type_inout)) && !Program._I_StorageService.STORAGE_LIST_CheckStock_1(STOCK_BARCODE, out  sResult);
            }
        }

        public ucMANAGE_INOUT()
        {
            InitializeComponent();
        }

        public ucMANAGE_INOUT(string PLAN_ID)
        {
            this.InitializeComponent();

            try
            {
                this._mPLAN_MAIN = Program._I_PlanService.PLAN_GetModel(Convert.ToInt32(PLAN_ID));

                this._mPLAN_TYPE = Program._I_PlanService.PLAN_GetModel_1(_mPLAN_MAIN._plan_type_code);

                this.cmbWAREHOUSE_Bind();

                if ("1".Equals(this._mPLAN_TYPE._plan_type_inout))
                {
                    this.cmbSTOCK_Bind();

                    cmbCELLMODEL_Bind();
                }

                //if ("2".Equals(this._mPLAN_TYPE._plan_type_inout))
                //{
                //    this.plOperation.Visible = true;
                //}

                this.PLAN_LIST_Bind();

                this.txtSTOCK_BARCODE.Focus();

                
            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }
        }

        private void cbWAREHOUSE_SelectedValueChanged(object sender, EventArgs e)
        {
            if (this.cmbWAREHOUSE.SelectedValue != null)
            {
                string WAREHOUSE_ID = Convert.ToString(this.cmbWAREHOUSE.SelectedValue);

                this.cmbAREA_Bind(WAREHOUSE_ID);
            }
        }

        private void cbAREA_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmbAREA.SelectedValue != null)
            {
                string AREA_ID = this.cmbAREA.SelectedValue.ToString();

                this.cmbCELL_Bind(AREA_ID);

                this.STORAGE_LIST_Bind();
            }
        }

     

        private void cmbWAREHOUSE_Bind()
        {
            try
            {
                cmbWAREHOUSE.ValueMember = "WAREHOUSE_ID";

                cmbWAREHOUSE.DisplayMember = "WAREHOUSE_NAME";

                cmbWAREHOUSE.DataSource = Program._I_WHService.WAREHOUSE_GetList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }

        }

        private void cmbAREA_Bind(string WAREHOUSE_ID)
        {

            try
            {
                cmbAREA.ValueMember = "AREA_ID";

                cmbAREA.DisplayMember = "AREA_NAME";

                cmbAREA.DataSource = Program._I_WHService.AREA_GetList_1(WAREHOUSE_ID, SSLMS.Model.AREA_TYPE.xuniku.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }
        }

        private void cmbCELL_Bind(string AREA_ID)
        {
            try
            {
                cbCELL.ValueMember = "CELL_ID";

                cbCELL.DisplayMember = "CELL_NAME";

                cbCELL.DataSource = Program._I_WHService.CELL_GetList(string.Empty, AREA_ID, SSLMS.Model.CELL_TYPE.station.ToString(), string.Empty);
            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }
        }

        private void cmbCELLMODEL_Bind()
        {
            this.cmbCELLMODEL.ValueMember = "value";

            cmbCELLMODEL.DisplayMember = "name";

            cmbCELLMODEL.DataSource = Program._I_SystemService.ITEM_LIST_GetList("CELL_MODEL");
        }

        private void cmbSTOCK_Bind()
        {
            try
            {
                this.cbSTOCK.ValueMember = "GOODS_ID";

                this.cbSTOCK.DisplayMember = "GOODS_NAME";

                Hashtable ht = new Hashtable();

                this.cbSTOCK.DataSource = Program._I_GoodsService.GOODS_GetList(this.cmbAREA.SelectedValue.ToString(), "0");
            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }

        }

        private void PLAN_LIST_Bind()
        {
            if ("1".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                this.uclIO_PLAN_LIST.listColumn = "<Field Column=\"MANAGE_LIST_QUANTITY\" fieldType=\"text\" bedit=\"true\" dbType=\"Decimal\" Header=\"入库数量\" index=\"31\" />";
            }

            this.uclIO_PLAN_LIST.bCheck = true;

            try
            {
                this.uclIO_PLAN_LIST.listTable = "V_PLAN_LIST";

                this.uclIO_PLAN_LIST.listXml = "PLAN_LIST";

                this.uclIO_PLAN_LIST.listWhere = string.Format("AND PLAN_ID ={0}  /*AND PLAN_LIST_QUANTITY>PLAN_LIST_FINISHED_QUANTITY */  AND GOODS_PROPERTY LIKE '%'", this._mPLAN_MAIN._plan_id);

                this.uclIO_PLAN_LIST.colGroup = "GOODS_TYPE_ID";

                this.uclIO_PLAN_LIST.colSplit = "GOODS_PROPERTY";

                this.uclIO_PLAN_LIST.Init();

                foreach (TabPage tp in this.uclIO_PLAN_LIST.tabGoodsType.TabPages)
                {
                    DataTable dt = (tp.Tag as ucGrid).dgv.DataSource as DataTable;

                    if (null != dt)
                    {
                        dt.ColumnChanged += new DataColumnChangeEventHandler(this.dtIO_PLAN_LIST_ColumnChanged);
                    }
                }

                this.uclIO_PLAN_LIST.SetEditColumns("MANAGE_LIST_QUANTITY", Color.AliceBlue);
            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }
        }

        private void STORAGE_LIST_Bind()
        {
            if ("2".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                this.uclST_STORAGE_LIST.listColumn = "<Field Column=\"MANAGE_LIST_QUANTITY\" fieldType=\"text\" bedit=\"true\" dbType=\"Decimal\" Header=\"出库数量\" index=\"14\" />";

                this.uclST_STORAGE_LIST.bCheck = true;
            }

            string AREA_ID = this.cmbAREA.SelectedValue.ToString();

            string STOCK_BARCODE = this.txtSTOCK_BARCODE.Text.Trim();

            this.uclST_STORAGE_LIST.listXml = "STORAGE_LIST";

            this.uclST_STORAGE_LIST.listTable = "V_STORAGE_LIST";

            if ("1".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                this.uclST_STORAGE_LIST.listWhere = string.Format(" AND AREA_ID = {0} AND STOCK_BARCODE LIKE '{1}' ", AREA_ID, STOCK_BARCODE);
            }

            if ("2".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                this.uclST_STORAGE_LIST.listWhere = string.Format(@" AND AREA_ID = {0} AND STOCK_BARCODE = '{1}' AND GOODS_PROPERTY  LIKE  '%' 
                                                                  AND (
                                                                       select count(0) from plan_list where V_STORAGE_LIST.Goods_Id= PLAN_LIST.Goods_Id 
                                                                  AND PLAN_LIST_QUANTITY>PLAN_LIST_FINISHED_QUANTITY 
                                                                  AND PLAN_LIST.GOODS_PROPERTY LIKE '%' 
                                                                  AND PLAN_ID = {2}
                                                                       )>0 ",
                                                                  AREA_ID,
                                                                  STOCK_BARCODE,
                                                                  this._mPLAN_MAIN._plan_id);

            }

            this.uclST_STORAGE_LIST.colGroup = "GOODS_TYPE_ID";

            this.uclST_STORAGE_LIST.colSplit = "GOODS_PROPERTY";

            this.uclST_STORAGE_LIST.Init();

            this.uclST_STORAGE_LIST.SetEditColumns("MANAGE_LIST_QUANTITY", Color.AliceBlue);

            foreach (TabPage tp in this.uclST_STORAGE_LIST.tabGoodsType.TabPages)
            {
                DataTable dt = (tp.Tag as ucGrid).dgv.DataSource as DataTable;

                if (null != dt)
                {
                    dt.ColumnChanged += new DataColumnChangeEventHandler(this.dtST_STORAGE_LIST_ColumnChanged);
                }
            }
        }

        private void dtIO_PLAN_LIST_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            try
            {
                bool bResult = true;

                string sResult = string.Empty;

                switch (e.Column.ColumnName)
                {
                    case "MANAGE_LIST_QUANTITY":

                        //bResult = e.ProposedValue.ToString() != string.Empty && Convert.ToInt32(e.ProposedValue) >= 0;

                        //sResult = string.Format(" must Greater than 0");

                        //if (!bResult)
                        //{
                        //    break;
                        //}

                        bResult = Convert.ToDecimal(e.Row["PLAN_LIST_QUANTITY"]) - Convert.ToDecimal(e.Row["PLAN_LIST_ORDERED_QUANTITY"]) >= Convert.ToDecimal(e.ProposedValue);

                        sResult = string.Format("入库数量错误");

                        if (!bResult)
                        {
                            break;
                        }

                        break;
                }

                if (bResult)
                {
                    e.Row.RowError = null;

                    e.Row.SetColumnError(e.Column, null);
                }
                else
                {
                    e.Row.RowError = sResult;

                    e.Row.SetColumnError(e.Column, sResult);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }
        }

        private void dtST_STORAGE_LIST_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            try
            {
                bool bResult = true;

                string sResult = string.Empty;

                switch (e.Column.ColumnName)
                {
                    case "MANAGE_LIST_QUANTITY":

                        bResult = Convert.ToDecimal(e.ProposedValue) >= 0;

                        sResult = string.Format("出库数量应大于0 ");
                        if (!bResult)
                        {
                            break;
                        }

                        bResult = Convert.ToDecimal(e.Row["STORAGE_LIST_QUANTITY"]) - Convert.ToDecimal(0.00) >= Convert.ToDecimal(e.ProposedValue);

                        sResult = string.Format("出库数量错误");

                        if (!bResult)
                        {
                            break;
                        }

                        break;
                }

                if (bResult)
                {
                    e.Row.RowError = null;

                    e.Row.SetColumnError(e.Column, null);
                }
                else
                {
                    e.Row.RowError = sResult;

                    e.Row.SetColumnError(e.Column, sResult);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if ("1" == this._mPLAN_TYPE._plan_type_inout)
            {
                if (this.txtSTOCK_BARCODE.Text.TrimEnd() == string.Empty)
                {
                    MessageBox.Show( "请扫描或输入托盘条码");
                    return;
                }

                if (this.txtSTOCK_BARCODE.Text.TrimEnd().Length != 6)
                {
                    MessageBox.Show("条码长度应为6位");
                    return;
                }

                for (int i = 0; i < this.uclIO_PLAN_LIST.tabGoodsType.TabPages.Count; i++)
                {
                    MyDataGrid mdgv = (this.uclIO_PLAN_LIST.tabGoodsType.TabPages[i].Tag as ucGrid).dgv;

                    DataTable dt = mdgv.DataSource as DataTable;
                    if (null == dt)
                    {
                        MessageBox.Show("请选择要入库的物料");

                        return;
                    }

                    if (dt.HasErrors)
                    {
                        string sError = string.Empty;

                        foreach (DataRow dr in dt.Rows)
                        {
                            sError += "\n" + dr.RowError;
                        }

                        MessageBox.Show("数据校验失败" + sError);

                        return;
                    }
                }
            }

            if ("2" == this._mPLAN_TYPE._plan_type_inout)
            {
                for (int i = 0; i < this.uclST_STORAGE_LIST.tabGoodsType.TabPages.Count; i++)
                {
                    MyDataGrid mdgv = (this.uclST_STORAGE_LIST.tabGoodsType.TabPages[i].Tag as ucGrid).dgv;

                    DataTable dt = mdgv.DataSource as DataTable;

                    if (null == dt)
                    {
                        MessageBox.Show( "请选择要出库的库存物料");

                        return;
                    }

                    if (dt.HasErrors)
                    {
                        string sError = string.Empty;

                        foreach (DataRow dr in dt.Rows)
                        {
                            sError += "\n" + dr.RowError;
                        }


                        MessageBox.Show("数据校验失败" + sError);

                        return;
                    }
                }
            }

            if (this._bZuPan)
            {

                if (this.cmbCELLMODEL.SelectedValue == null)
                {
                    this.cmbCELLMODEL.Visible = this._bZuPan;

                    this.cmbCELLMODEL.Visible = this._bZuPan;

                    MessageBox.Show( "请选择货物规格");

                    return;
                }

            }

            if (this._bAddSTOCK)
            {


                if (this.cbSTOCK.SelectedValue == null)
                {

                    MessageBox.Show("请选择托盘类型");

                    this.cbSTOCK.Visible = this._bAddSTOCK;

                    return;
                }

            }

            bool bResult = true;

            string sResult = string.Empty;

            string strMessageShow = string.Empty;

            if (Program._I_StorageService.StorageListCheckInOtherArea(this.txtSTOCK_BARCODE.Text.TrimEnd(), this.cmbAREA.SelectedValue.ToString(), out sResult))
            {
                MessageBox.Show( sResult);
                return;
            }

            MANAGE_MAIN mIO_MANAGE_INOUT = new MANAGE_MAIN();

            int MANAGE_ID = 0;

            mIO_MANAGE_INOUT._plan_id = this._mPLAN_MAIN._plan_id;

            mIO_MANAGE_INOUT._manage_type_code = this._mPLAN_TYPE._plan_type_remark;

            mIO_MANAGE_INOUT._manage_status = SSLMS.Model.MANAGE_STATUS.Waitting.ToString();

            if (this._bZuPan)
            {
                mIO_MANAGE_INOUT._stock_barcode = this.txtSTOCK_BARCODE.Text.TrimEnd();

                //mIO_MANAGE_INOUT.CELL_MODEL = this.tscbCELL_MODEL.ComboBox.SelectedValue.ToString();
            }
            else
            {
                mIO_MANAGE_INOUT._stock_barcode = string.Empty;
            }

            if ("1" == this._mPLAN_TYPE._plan_type_inout)
            {
                mIO_MANAGE_INOUT._end_cell_id = Convert.ToInt32(this.cbCELL.SelectedValue);
            }

            if ("2" == this._mPLAN_TYPE._plan_type_inout)
            {
                mIO_MANAGE_INOUT._start_cell_id = Convert.ToInt32(this.cbCELL.SelectedValue); ;
            }

            mIO_MANAGE_INOUT._manage_operator = Program._USER._user_name;

            IList<MANAGE_LIST> lsMANAGE_LIST_INOUT = new List<MANAGE_LIST>();



            if ("1".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                foreach (TabPage tp in this.uclIO_PLAN_LIST.tabGoodsType.TabPages)
                {
                    MyDataGrid dgvPLAN_LIST = (tp.Tag as ucGrid).dgv;

                    foreach (DataRow drPLAN_LIST in (tp.Tag as ucGrid).CommonCol().Rows)
                    {
                        if (!drPLAN_LIST.IsNull("check") && Convert.ToBoolean(drPLAN_LIST["check"]) == true)
                        {
                           MANAGE_LIST mIO_MANAGE_LIST = new MANAGE_LIST();

                            //DataRow drPLAN_LIST = (dgvRow.DataBoundItem as DataRowView).Row;

                            mIO_MANAGE_LIST._goods_id = Convert.ToInt32(drPLAN_LIST["GOODS_ID"]);

                            mIO_MANAGE_LIST._goods_property = Convert.ToString(drPLAN_LIST["GOODS_PROPERTY"]);

                            mIO_MANAGE_LIST._plan_list_id = Convert.ToInt32(drPLAN_LIST["PLAN_LIST_ID"]);

                            mIO_MANAGE_LIST._manage_list_quantity = Convert.ToDecimal(drPLAN_LIST["MANAGE_LIST_QUANTITY"]);

                            if (mIO_MANAGE_LIST._manage_list_quantity <= 0)
                            {
                                MessageBox.Show( "入库数量错误");

                                return;
                            }

                            mIO_MANAGE_LIST._manage_list_remark = Convert.ToString(drPLAN_LIST["PLAN_LIST_REMARK"]);

                            lsMANAGE_LIST_INOUT.Add(mIO_MANAGE_LIST);
                        }
                    }
                }
            }

            if ("2".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                foreach (TabPage tp in this.uclST_STORAGE_LIST.tabGoodsType.TabPages)
                {
                    MyDataGrid dgvSTORAGE_LIST = (tp.Tag as ucGrid).dgv;

                    foreach (DataRow drSTORAGE_LIST in (tp.Tag as ucGrid).CommonCol().Rows)
                    {
                        if (!drSTORAGE_LIST.IsNull("check") && Convert.ToBoolean(drSTORAGE_LIST["check"]))
                        {
                            MANAGE_LIST mIO_MANAGE_LIST = new MANAGE_LIST();

                            //DataRow drSTORAGE_LIST = (dgvRow.DataBoundItem as DataRowView).Row;

                            mIO_MANAGE_LIST._goods_id = Convert.ToInt32(drSTORAGE_LIST["GOODS_ID"]);

                            mIO_MANAGE_LIST._goods_property = Convert.ToString(drSTORAGE_LIST["GOODS_PROPERTY"]);

                            mIO_MANAGE_LIST._storage_list_id = Convert.ToInt32(drSTORAGE_LIST["STORAGE_LIST_ID"]);

                            mIO_MANAGE_LIST._manage_list_quantity = Convert.ToDecimal(drSTORAGE_LIST["MANAGE_LIST_QUANTITY"]);

                            if (mIO_MANAGE_LIST._manage_list_quantity <= 0)
                            {
                               MessageBox.Show( "出库数量错误");

                                return;
                            }

                            mIO_MANAGE_LIST._manage_list_remark = Convert.ToString(drSTORAGE_LIST["STORAGE_LIST_REMARK"]);

                            lsMANAGE_LIST_INOUT.Add(mIO_MANAGE_LIST);
                        }
                    }
                }


            }

            if (lsMANAGE_LIST_INOUT.Count < 1)
            {
                if ("1".Equals(this._mPLAN_TYPE._plan_type_inout))
                {
                    MessageBox.Show( "请选择要入库的物料");
                }

                if ("2".Equals(this._mPLAN_TYPE._plan_type_inout))
                {
                    MessageBox.Show("请选择要出库的库存物料");
                }

                return;
            }

            string sPLAN_LIST_ID = string.Empty;
            MANAGE_LIST[] aMANAGE_LIST_INOUT = null;

            if ("2".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                sPLAN_LIST_ID = this.uclIO_PLAN_LIST.GetCheckColumns("PLAN_LIST_ID", new char[] { ',' });

                if (string.IsNullOrEmpty(sPLAN_LIST_ID))
                {
                    MessageBox.Show("请选择要出库的物料");

                    return;
                }

                bResult = Program._I_ManageService.ManageFindManageListPlanListID(lsMANAGE_LIST_INOUT.ToArray<MANAGE_LIST>(), sPLAN_LIST_ID, out sResult, out aMANAGE_LIST_INOUT);

                if (!bResult)
                {
                    MessageBox.Show(sResult);

                    return;
                }
            }

            if (MessageBox.Show("是否保存?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question,MessageBoxDefaultButton.Button1) == DialogResult.No)
            {
                return;
            }

            if ("1".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                bResult = Program._I_ManageService.ManageCreateCommonTask(mIO_MANAGE_INOUT, lsMANAGE_LIST_INOUT.ToArray<MANAGE_LIST>(), false, true, out sResult, out MANAGE_ID);
            }

            if ("2".Equals(this._mPLAN_TYPE._plan_type_inout))
            {
                bResult = Program._I_ManageService.ManageCreateCommonTask(mIO_MANAGE_INOUT, aMANAGE_LIST_INOUT, false, true, out sResult, out MANAGE_ID);

            }

            if (bResult)
            {

                MessageBox.Show("保存成功!\n");

                if (this._bAddSTOCK && this.cbSTOCK.SelectedValue != null)
                {
                    bResult = Program._I_ManageService.ManageCreatePalletEntryTask(Program._USER, Convert.ToInt32(this.cbCELL.SelectedValue), Convert.ToInt32(this.cbSTOCK.SelectedValue), 1, this.txtSTOCK_BARCODE.Text.Trim(), false, false, out sResult, out MANAGE_ID);

                }

                this.PLAN_LIST_Bind();

                this.STORAGE_LIST_Bind();


            }
            else
            {
                MessageBox.Show( string.Format("保存失败!\n{0}", sResult));
            }

            this.txtSTOCK_BARCODE.Focus();

            this.txtSTOCK_BARCODE.SelectAll();

        }

        private void txt_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (!Keys.Enter.Equals(e.KeyCode))
                {
                    return;
                }

                this.STORAGE_LIST_Bind();
            }
            catch (Exception ex)
            {
                MessageBox.Show("系统异常" + ex.Message);
            }
        }



       
    }
}