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;
using SiaSun.LMS.Common;
using Sid.Windows.Controls;

namespace SiaSun.LMS.WPFClient.TASK
{
    /// <summary>
    /// 
    /// </summary>
    public partial class ManageDown : AvalonDock.DocumentContent
    {
        Model.MANAGE_TYPE mMANAGE_TYPE = null;

        List<Model.MANAGE_LIST> listMANAGE_LIST = null;

        string xmlTable = string.Empty;
        string AREA_TYPE = string.Empty;

        #region  构造函数
        public ManageDown()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="MANAGE_TYPE_CODE"></param>
        /// <param name="MANAGE_FLAG"></param>
        public ManageDown(string MANAGE_TYPE_CODE):this()
        {
            InitializeComponent();

            this.mMANAGE_TYPE = (Model.MANAGE_TYPE)MainApp._I_BaseService.GetModel("MANAGE_TYPE_SELECT_BY_MANAGE_TYPE_CODE", MANAGE_TYPE_CODE).RequestObject;
            
            this.ucQuery.U_Query += new UC.ucQuickQuery.U_QueryEventHandler
                                   ( (QueryWhere)=>
                                      {
                                          QueryWhere = string.Format("{0}{1}",
                                          string.IsNullOrEmpty(QueryWhere) ? "1=1" : QueryWhere,
                                          string.Format(" AND AREA_TYPE = 'LiKu' "));
                                          this.QueryStorage(QueryWhere);
                                      }
                                    );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MANAGE_TYPE_CODE"></param>
        /// <param name="AREA_TYPE"></param>
        public ManageDown(string MANAGE_TYPE_CODE, string AREA_TYPE,string xmlTable)
            : this()
        {
            InitializeComponent();

            this.mMANAGE_TYPE = (Model.MANAGE_TYPE)MainApp._I_BaseService.GetModel("MANAGE_TYPE_SELECT_BY_MANAGE_TYPE_CODE", MANAGE_TYPE_CODE).RequestObject;
            this.xmlTable = xmlTable;
            this.AREA_TYPE = AREA_TYPE;
            this.ucQuery.U_Query += new UC.ucQuickQuery.U_QueryEventHandler
                                   ((QueryWhere) =>
                                   {
                                       QueryWhere = string.Format("{0}{1}",
                                       string.IsNullOrEmpty(QueryWhere) ? "1=1" : QueryWhere,
                                       string.Format(" AND AREA_TYPE IN ('{0}')", AREA_TYPE.Replace("|","','")));
                                       this.QueryStorage(QueryWhere);
                                   }
                                    );
        }


        #endregion

        #region 系统方法

        private void DocumentContent_Loaded(object sender, RoutedEventArgs e)
        {
            //查询控件
            this.InitQueryControl();

            //初始化属性面板
            this.InitSplitPropertyPanel();
            Area_Bind();
        }

        #endregion

        #region 自定义方法

        /// <summary>
        /// 初始化属性面板
        /// </summary>
        private void InitSplitPropertyPanel()
        {
            this.ucSplitPanel.U_SplitPropertyType = "GOODS_TYPE";
            this.ucSplitPanel.U_SplitGroupColumn = "GOODS_TYPE_ID";
            this.ucSplitPanel.U_SplitGroupHeader = "GOODS_TYPE_NAME";
            this.ucSplitPanel.U_SplitPropertyColumn = "GOODS_PROPERTY";
            this.ucSplitPanel.U_InitControl();
        }

        //下架目标作业区
        private void Area_Bind()
        {
            this.cbbAREA.DisplayMemberPath = "AREA_NAME";
            this.cbbAREA.SelectedValuePath = "AREA_ID";
            try
            {
                this.cbbAREA.ItemsSource = MainApp._I_CellService.AREA_GetList(0, "XuNiKu").DefaultView;

                if (this.cbbAREA.Items.Count > 0)
                {
                    this.cbbAREA.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        private void cbbAREA_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source == null)
                return;

            this.cbbCELL.DisplayMemberPath = "CELL_NAME";
            this.cbbCELL.SelectedValuePath = "CELL_ID";
            try
            {
                string strSQL = string.Format(@"SELECT CELL_ID,
                                                   CELL_NAME 
                                              FROM WH_CELL
                                                WHERE CELL_FLAG='1' AND
                                                  CELL_TYPE = 'Station' AND
                                                  CELL_MODEL!='-1'
                                                  AND CELL_INOUT != 'In' 
                                                  AND AREA_ID = {0}
                                                  ORDER BY CELL_ID", this.cbbAREA.SelectedValue);
                DataTable dt = MainApp._I_BaseService.GetList(strSQL);
                DataRow dr = dt.NewRow();
                dr["CELL_ID"] = "0";
                dr["CELL_NAME"] = "---";
                dt.Rows.InsertAt(dr, 0);
                this.cbbCELL.ItemsSource = dt.DefaultView;

                if (this.cbbCELL.Items.Count > 0)
                {
                    this.cbbCELL.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }


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


        private void StorageListBind(string QueryWhere)
        {
            this.ucStorageGroup.U_WindowName = this.GetType().Name;
            this.ucStorageGroup.U_TableName = xmlTable;
            this.ucStorageGroup.U_XmlTableName = xmlTable;
            //this.ucStorageGroup.U_AppendFieldStyles = this.GetColumnDescriptionList();
            this.ucStorageGroup.U_TotalColumnName = "STORAGE_LIST_QUANTITY";
            this.ucStorageGroup.U_OrderField = "STORAGE_LIST_ID";
            
            //实盘下架时,不显示托盘库存
            this.ucStorageGroup.U_Where = string.Format(" CELL_ID NOT IN ( SELECT START_CELL_ID FROM MANAGE_MAIN) AND {0} {1}",
                                                            QueryWhere,
                                                            string.Format(" AND CELL_STATUS <> 'Pallet' AND RUN_STATUS='Enable'"));

            this.ucStorageGroup.U_AllowOperatData = false;
            this.ucStorageGroup.U_AllowChecked = true;
            this.ucStorageGroup.U_AllowShowPage = true;

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

            this.ucStorageGroup.U_InitControl();
        }

        private void QueryStorage(string QueryWhere)
        {
            string strSplitWhere = this.ucSplitPanel.U_GetSplitPropertyWhere();
            string strDetailWhere = string.Empty;
            if (this.ucDetail.DetailList.Count > 0)
            {
                strDetailWhere = string.Format("'{0}'", string.Join("','", this.ucDetail.DetailList));
            }

            string strWhere =string.Format("{0} AND {1} AND {2}",
                string.IsNullOrEmpty(strSplitWhere) ? "1=1" : strSplitWhere,
                string.IsNullOrEmpty(strDetailWhere) ? "1=1" : string.Format("STORAGE_LIST_ID IN (SELECT STORAGE_LIST_ID FROM STORAGE_DETAIL WHERE GOODS_BARCODE in ({0}))", strDetailWhere),
                string.IsNullOrEmpty(QueryWhere) ? "1=1" : QueryWhere);

            this.StorageListBind(strWhere);
        }

        #endregion

        #region 按钮事件

        private void WrapPanel_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            if (btn != null)
            {
                switch (btn.Name)
                {
                    case "btnConfirm":
                        this.CreateMultipleDown();
                        //this.CreateTaskOut();
                        break;
                    case "btnRefresh":
                        this.Refresh();
                        break;
                }
            }
        }

        /// <summary>
        /// 一次调用服务,创建多个下架任务(适用于双深货位)
        /// </summary>
        private void CreateMultipleDown()
        {
            bool boolResult = false;

            string strResult = string.Empty;

            try
            {
                if (this.ucStorageGroup.tabSplitProperty.SelectedItem == null)
                {
                    MainApp._MessageDialog.Show(false, "请查询可用库存");
                    return;
                }
  
                //获得选中记录
                DataRowView[] drvStorage = this.ucStorageGroup.U_GetCheckedDataRows();

                if (drvStorage.Length == 0)
                {
                    MainApp._MessageDialog.Show(false, "请选择要下架的库存记录");
                    return;
                }

                List<Model.STORAGE_MAIN> listSTORAGE_MAIN = new SiaSun.LMS.Common.CloneObjectValues().GetListFromDataTable<Model.STORAGE_MAIN>(drvStorage, null);


                if (MainApp._MessageDialog.ShowDialog(string.Format("确认下达【实盘下架】任务")) == Sid.Windows.Controls.TaskDialogResult.Ok)
                {
                        boolResult = MainApp._I_BaseService.Invoke(mMANAGE_TYPE.MANAGE_TYPE_CLASS.TrimEnd(),
                                                                                                         "ManageCreate",
                                                                                                          new object[] { listSTORAGE_MAIN,
                                                                                                                     Convert.ToInt32(this.cbbAREA.SelectedValue),
                                                                                                                     Convert.ToInt32(this.cbbCELL.SelectedValue),
                                                                                                                     this.cbControl.IsChecked,
                                                                                                                     MainApp._USER.USER_NAME
                                                                                                                    },
                                                                                                                              out strResult);

                    if (boolResult)
                    {
                        this.Refresh();
                    }

                    TaskDialog.Show("系统提示", "执行消息", boolResult ? "成功" + "\n" + strResult : "失败" + "\n" + strResult);
                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }


        /// <summary>
        /// 连续调用服务 创建多个下架任务(适用于普通货位)
        /// </summary>
        private void CreateTaskOut()
        {
            bool boolResult = false;

            bool boolSingleResult = true;

            string strResult = string.Empty;

            string sSingleResult = string.Empty;

            try
            {
                //获得选中记录
                List<DataRowView> listDataRowView = this.ucStorageGroup.U_GetCheckedDataRows().Cast<DataRowView>().ToList();

                if (listDataRowView.Count == 0)
                {
                    MainApp._MessageDialog.Show(false, "请选择要下架的记录");

                    return;
                }

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

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

                if (MainApp._MessageDialog.ShowDialog(string.Format("确认下达【实盘下架】任务")) == Sid.Windows.Controls.TaskDialogResult.Ok)
                {
                    //获得所有的选定的条码
                    foreach (var storage_id in storage_id_group)
                    {
                        var value_storage_id = from v in listDataRowView
                                                  where v["STORAGE_ID"].ToString() == storage_id.Key 
                                           select v;

                        listMANAGE_LIST = new SiaSun.LMS.Common.CloneObjectValues().GetListFromDataTable<Model.MANAGE_LIST>(value_storage_id.Cast<DataRowView>().ToArray(), null);

                        //无计划下架出库,清空计划
                        foreach (Model.MANAGE_LIST mMANAGE_LIST in listMANAGE_LIST)
                        {
                            mMANAGE_LIST.PLAN_LIST_ID = 0;
                        }

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

                        SiaSun.LMS.Model.STORAGE_MAIN mSTORAGE_MAIN = (Model.STORAGE_MAIN)MainApp._I_BaseService.GetModel("STORAGE_MAIN_SELECT_BY_ID", Convert.ToInt32(storage_id.Key)).RequestObject;

                        mMANAGE_MAIN.PLAN_ID = 0;

                        //this.mMANAGE_TYPE = (Model.MANAGE_TYPE)MainApp._I_BaseService.GetModel("MANAGE_TYPE_SELECT_BY_MANAGE_TYPE_CODE", Enum.MANAGE_TYPE.ManageDown.ToString()).RequestObject;

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

                        mMANAGE_MAIN.PLAN_TYPE_CODE = string.Empty;

                        mMANAGE_MAIN.STOCK_BARCODE = mSTORAGE_MAIN.STOCK_BARCODE;

                        mMANAGE_MAIN.CELL_MODEL = mSTORAGE_MAIN.CELL_MODEL;

                        mMANAGE_MAIN.FULL_FLAG = mSTORAGE_MAIN.FULL_FLAG;

                        mMANAGE_MAIN.START_CELL_ID = mSTORAGE_MAIN.CELL_ID;

                        mMANAGE_MAIN.END_CELL_ID = Convert.ToInt32(this.cbbCELL.SelectedValue);

                        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.Waiting.ToString();

                        mMANAGE_MAIN.MANAGE_LEVEL = string.Empty;

                        mMANAGE_MAIN.MANAGE_REMARK = string.Empty;

                        boolSingleResult = MainApp._I_BaseService.Invoke(mMANAGE_TYPE.MANAGE_TYPE_CLASS.TrimEnd(),
                                                                                                         "ManageCreate",
                                                                                                          new object[] { mSTORAGE_MAIN.STORAGE_ID,
                                                                                                                     mSTORAGE_MAIN.STOCK_BARCODE,
                                                                                                                     mMANAGE_MAIN.END_CELL_ID,
                                                                                                                     Convert.ToInt32(this.cbbAREA.SelectedValue),
                                                                                                                     this.cbControl.IsChecked,
                                                                                                                     true,
                                                                                                                     MainApp._USER.USER_NAME
                                                                                                                    },
                                                                                                                              out sSingleResult);

                        if (!boolSingleResult)
                        {
                            strResult += value_storage_id.Cast<DataRowView>().ToArray()[0]["CELL_CODE"].ToString() + " 任务下达失败 " + sSingleResult + "\n";
                            boolResult = false;
                            break;
                        }
                        else
                        {
                            strResult += value_storage_id.Cast<DataRowView>().ToArray()[0]["CELL_CODE"].ToString() + " 任务下达成功 " + "\n";

                            boolResult = true;
                        }
                    }

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

                    MainApp._MessageDialog.Show(boolResult, strResult);
                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        private void Refresh()
        {
            this.ucStorageGroup.U_Update();
            this.cbControl.IsChecked = true;
        }

        #endregion

    }
}