using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;

namespace SiaSun.LMS.WPFClient.MANAGE
{
    /// <summary>
    /// 
    /// </summary>
    public partial class MANAGE_STOCK : AvalonDock.DocumentContent
    {
        int Stock_Goods_ID;    

        SiaSun.LMS.Model.MANAGE_TYPE mMANAGE_TYPE_IN = null;

        SiaSun.LMS.Model.MANAGE_TYPE mMANAGE_TYPE_OUT = null;

        List<Model.MANAGE_LIST> listMANAGE_LIST = null;

        public MANAGE_STOCK(string MANAGE_TYPE_CODE_IN,string MANAGE_TYPE_CODE_OUT, int StockGoodsID)
        {
            InitializeComponent();

            this.Stock_Goods_ID = StockGoodsID;

            this.mMANAGE_TYPE_IN = (Model.MANAGE_TYPE)MainApp._I_BaseService.GetModel("MANAGE_TYPE_SELECT_BY_MANAGE_TYPE_CODE", MANAGE_TYPE_CODE_IN).RequestObject;

            this.mMANAGE_TYPE_OUT = (Model.MANAGE_TYPE)MainApp._I_BaseService.GetModel("MANAGE_TYPE_SELECT_BY_MANAGE_TYPE_CODE", MANAGE_TYPE_CODE_OUT).RequestObject;

            this.ucQuery.U_Query += new UC.ucQuickQuery.U_QueryEventHandler
                                        ((QueryWhere) =>
                                        {
                                            QueryWhere = string.Format(" and {0}", string.IsNullOrEmpty(QueryWhere) ? "1=1" : QueryWhere);
                                            this.StorageListBind(QueryWhere);
                                        }
                                        );


        
        }


        private void DocumentContent_Loaded(object sender, RoutedEventArgs e)
        {
            this.grpbManage.Header = string.Format(this.grpbManage.Tag.ToString(), this.Title);
            try
            {
                if (mMANAGE_TYPE_IN == null || mMANAGE_TYPE_OUT == null)
                {
                    MainApp._MessageDialog.ShowException("未找到任务类型");
                    return;
                }
                else
                {
                    ManagePositin_Init();

                    this.InitQueryControl();
                    
                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        /// <summary>
        /// 位置控件初始化
        /// </summary>
        private void ManagePositin_Init()
        {
            try
            {
                this.ucManagePositionIn.U_InitControl(this.mMANAGE_TYPE_IN.MANAGE_TYPE_ID);
                this.ucManagePositionOut.U_InitControl(this.mMANAGE_TYPE_OUT.MANAGE_TYPE_ID);
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        /// <summary>
        /// 初始化查询控件
        /// </summary>
        private void InitQueryControl()
        {
            this.ucQuery.U_WindowName = this.GetType().Name;
            this.ucQuery.U_XmlTableName = "V_STORAGE_LIST";
            this.ucQuery.U_InitControl();
        }



        private void Refresh()
        {
            try
            {
                this.ucManagePositionOut.U_Refresh();
                this.ucManagePositionIn.U_Refresh();

                string queryWhere = this.ucQuery.U_GetQuery();

                this.StorageListBind(string.Format(" and {0}", string.IsNullOrEmpty(queryWhere) ? "1=1" : queryWhere));

               

            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

      

        private void StorageListBind(string QueryWhere )
        {
            this.ucStockStorageGroup.U_WindowName = this.GetType().Name;
            this.ucStockStorageGroup.U_TableName = "V_STORAGE_LIST";
            this.ucStockStorageGroup.U_XmlTableName = "V_STORAGE_LIST";
            this.ucStockStorageGroup.U_TotalColumnName = "STORAGE_LIST_QUANTITY";
            this.ucStockStorageGroup.U_OrderField = "STORAGE_LIST_ID";
            this.ucStockStorageGroup.U_Where = string.Format(" {0} and cell_id not in ( select start_cell_id from manage_main) {1} ", 
                                                            string.Format("goods_id ={0} " ,Stock_Goods_ID),
                                                            QueryWhere);
            this.ucStockStorageGroup.U_AllowOperatData = false;
            this.ucStockStorageGroup.U_AllowChecked = true;
            this.ucStockStorageGroup.U_AllowShowPage = true;

            //拆分列属性
            this.ucStockStorageGroup.U_SplitPropertyType = "GOODS_TYPE";
            this.ucStockStorageGroup.U_SplitGroupColumn = "GOODS_TYPE_ID";
            this.ucStockStorageGroup.U_SplitGroupHeader = "GOODS_TYPE.GOODS_TYPE_NAME";
            this.ucStockStorageGroup.U_SplitPropertyColumn = "GOODS_PROPERTY";

            this.ucStockStorageGroup.U_InitControl();
        }


        private void WrapPanel_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            if (btn != null)
            {
                switch (btn.Name)
                {
                    case "btnCreateTask":
                        this.CreateStockOut();
                        break;
                    case "btnRefresh":
                        this.Refresh();
                        break;
                    case "btnCreateIn":
                        this.CreateStockIn();
                        break;
                }
            }
        }

        /// <summary>
        /// 创建并下达任务
        /// </summary>
        private void CreateStockOut()
        {
            bool boolResult = true;

            string strResult = string.Empty;

            boolResult = this.ucManagePositionOut.U_CHECK_WAREHOUSE();

            if (!boolResult)
                return;

            if (MainApp._MessageDialog.ShowDialog("您确认创建任务?") == Sid.Windows.Controls.TaskDialogResult.Cancel)
                return;


            try
            {
                    boolResult = CreateSingleStockOut(out strResult);
            }
            catch (Exception ex)
            {
                boolResult = false;

                strResult = ex.Message;
            }

            if (boolResult)
            {
                //刷新
                this.Refresh();
            }

            MainApp._MessageDialog.Show(boolResult, strResult);

        }


        /// <summary>
        /// 单一托盘出库
        /// </summary>
        private bool CreateSingleStockOut(out string strResult)
        {
            bool boolResult = false;

            bool boolSingleResult = true;

            strResult = "\n";

            string sSingleReslut = string.Empty;

            try
            {

                if (!this.ucManagePositionOut.U_CHECK_WAREHOUSE())
                    return false;

                List<DataRowView> listDataRowView = this.ucStockStorageGroup.U_GetCheckedDataRows().Cast<DataRowView>().ToList();

                if (listDataRowView.Count == 0)
                {
                    strResult = string.Format("是否选中记录");

                    return false;
                }

                foreach (DataRowView drv in listDataRowView)
                {
                    drv["MANAGE_LIST_QUANTITY"] = drv["STORAGE_LIST_QUANTITY"];
                }

                var cell_id_group = from v in listDataRowView
                                    group v by v["CELL_ID"].ToString() into a
                                    select a;




                foreach (var cell_id in cell_id_group)
                {
                    int intStartPositionID = Convert.ToInt32(cell_id.Key);

                    var value_ceLl_id = from v in listDataRowView
                                        where v["CELL_ID"].ToString() == cell_id.Key
                                        select v;

                    DataRowView[] drvGroup = value_ceLl_id.Cast<DataRowView>().ToArray();

                    listMANAGE_LIST = new SiaSun.LMS.Common.CloneObjectValues().GetListFromDataTable<Model.MANAGE_LIST>(drvGroup, null);

                    SiaSun.LMS.Model.MANAGE_MAIN mMANAGE_MAIN = new Model.MANAGE_MAIN();

                    mMANAGE_MAIN.MANAGE_TYPE_CODE = mMANAGE_TYPE_OUT.MANAGE_TYPE_CODE.TrimEnd();

                    mMANAGE_MAIN.PLAN_ID = 0;

                    mMANAGE_MAIN.STOCK_BARCODE = drvGroup[0]["STOCK_BARCODE"].ToString();

                    mMANAGE_MAIN.CELL_MODEL = this.ucManagePositionOut.U_CELL_MODEL;

                    mMANAGE_MAIN.START_CELL_ID = intStartPositionID;

                    mMANAGE_MAIN.END_CELL_ID = this.ucManagePositionOut.U_END_POSITION_ID;

                    mMANAGE_MAIN.MANAGE_OPERATOR = MainApp._USER.USER_NAME;

                    mMANAGE_MAIN.MANAGE_BEGIN_TIME = SiaSun.LMS.Common.StringUtil.GetDateTime();

                    mMANAGE_MAIN.MANAGE_STATUS = SiaSun.LMS.Enum.MANAGE_STATUS.WaitingSend.ToString();

                    mMANAGE_MAIN.MANAGE_LEVEL = string.Empty;

                    mMANAGE_MAIN.MANAGE_REMARK = string.Empty;


                    boolSingleResult = MainApp._I_BaseService.Invoke(mMANAGE_TYPE_OUT.MANAGE_TYPE_CLASS.TrimEnd(),
                                         "ManageCreate",
                                          new object[] { mMANAGE_MAIN,
                                                             null,
                                                             listMANAGE_LIST,
                                                             true, 
                                                             this.ucManagePositionOut.U_AutoDownloadControlTask, 
                                                             this.ucManagePositionOut.U_AutoCompleteTask 
                                                            },
                                          out sSingleReslut);

                    if (!boolSingleResult)
                    {
                        strResult += value_ceLl_id.Cast<DataRowView>().ToArray()[0]["CELL_CODE"].ToString() + " 任务下达失败 " + sSingleReslut + "\n";

                        break;
                    }
                    else
                    {
                        strResult += value_ceLl_id.Cast<DataRowView>().ToArray()[0]["CELL_CODE"].ToString() + " 任务下达成功 " + "\n";

                        boolResult = true;

                        break;
                    }
                }

                this.Refresh();

            }
            catch (Exception ex)
            {
                boolResult = false;

                strResult = ex.Message;
            }

            return boolResult;
        }



        private void CreateStockIn()
        {
            bool boolResult = true;

            bool boolBatchResult = true;

            string strResult = string.Empty;

            string sBatchResult = string.Empty;


            if (!boolResult)
            {
                MainApp._MessageDialog.Show(false, strResult);
                return;
            }

            //判断输送位置是否合法
            boolResult = this.ucManagePositionIn.U_CHECK_WAREHOUSE();

            if (!boolResult)
            {
                return;
            }


            if (MainApp._MessageDialog.ShowDialog("您确认创建任务?") == Sid.Windows.Controls.TaskDialogResult.Cancel)
                return;

            try
            {
                int intStartPositionID = this.ucManagePositionIn.U_START_POSITION_ID;

                List<Model.MANAGE_LIST> listMANAGE_LIST = new List<Model.MANAGE_LIST>();

                Model.MANAGE_LIST mMANAGE_LIST = new Model.MANAGE_LIST();

                mMANAGE_LIST.GOODS_ID = this.Stock_Goods_ID;

                mMANAGE_LIST.MANAGE_LIST_QUANTITY = 1;

                listMANAGE_LIST.Add(mMANAGE_LIST);



                SiaSun.LMS.Model.MANAGE_MAIN mMANAGE_MAIN = new Model.MANAGE_MAIN();

                mMANAGE_MAIN.PLAN_ID = 0;

                mMANAGE_MAIN.MANAGE_TYPE_CODE = mMANAGE_TYPE_IN.MANAGE_TYPE_CODE.TrimEnd();

                mMANAGE_MAIN.STOCK_BARCODE = string.Empty;

                mMANAGE_MAIN.CELL_MODEL = this.ucManagePositionIn.U_CELL_MODEL;

                mMANAGE_MAIN.START_CELL_ID = this.ucManagePositionIn.U_START_POSITION_ID;

                mMANAGE_MAIN.END_CELL_ID = this.ucManagePositionIn.U_END_POSITION_ID;

                mMANAGE_MAIN.MANAGE_OPERATOR = MainApp._USER.USER_NAME;

                mMANAGE_MAIN.MANAGE_BEGIN_TIME = SiaSun.LMS.Common.StringUtil.GetDateTime();

                mMANAGE_MAIN.MANAGE_STATUS = SiaSun.LMS.Enum.MANAGE_STATUS.WaitingSend.ToString();

                mMANAGE_MAIN.FULL_FLAG = this.ucManagePositionIn.U_OCCUPY_PERCENT;

                mMANAGE_MAIN.MANAGE_LEVEL = string.Empty;

                mMANAGE_MAIN.MANAGE_REMARK = string.Empty;

                boolResult = MainApp._I_BaseService.Invoke(mMANAGE_TYPE_IN.MANAGE_TYPE_CLASS.TrimEnd(),
                                                             "ManageCreate",
                                                              new object[] { mMANAGE_MAIN,
                                                                                 listMANAGE_LIST,                                                                                
                                                                                 true, 
                                                                                 this.ucManagePositionIn.U_CheckStockExistStorage,
                                                                                 this.ucManagePositionIn.U_AutoCompleteTask,
                                                                                 this.ucManagePositionIn.U_AutoDownloadControlTask
                                                                                 },
                                                              out strResult);

                if (!boolResult)
                {
                    MainApp._MessageDialog.Show(boolResult, strResult);

                    boolBatchResult = false;


                }
                else
                {
                    sBatchResult += mMANAGE_MAIN.STOCK_BARCODE + "\n";

                }




            }
            catch (Exception ex)
            {
                boolResult = false;

                strResult = ex.Message;
            }

            if (sBatchResult != string.Empty)
                MainApp._MessageDialog.Show(true, sBatchResult + "\n" + "任务下达成功");


            if (boolBatchResult)
                this.Refresh();

        }


    }
}