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.TEMPLATE
{
    public partial class MANAGE_TEMPLATE_OUT : AvalonDock.DocumentContent
    {

        Model.MANAGE_TYPE mMANAGE_TYPE = null;

        DataRowView[] listDataRowView = null;

        string STORAGE_AREA_TYPE = string.Empty;

        /// <summary>
        /// 
        /// </summary>
        public MANAGE_TEMPLATE_OUT( string MANAGE_TYPE_CODE, string AREA_TYPE)
        {
            InitializeComponent();

            STORAGE_AREA_TYPE = AREA_TYPE;

            this.mMANAGE_TYPE = (Model.MANAGE_TYPE)MainApp._I_BaseService.GetModel("MANAGE_TYPE_SELECT_BY_MANAGE_TYPE_CODE", MANAGE_TYPE_CODE).RequestObject;

        }

        private void DocumentContent_Loaded(object sender, RoutedEventArgs e)
        {
            this.InitManagePosotion();

            this.GOODS_BIND();

            this.cmbGoods.SelectionChanged += new SelectionChangedEventHandler
                ( ( cmbGoodsSender,cmbGoodsE)=>
                    {
                        if (this.cmbGoods.SelectedValue != null)
                        {
                            IList<SiaSun.LMS.Model.GOODS_TEMPLATE> listGOODS_TEMPLATE = MainApp._I_GoodsService.GoodsTemplateGetList(Convert.ToInt32(this.cmbGoods.SelectedValue));

                            this.cmbTemplate.DisplayMemberPath = "GOODS_TEMPLATE_NAME";
                            this.cmbTemplate.SelectedValuePath = "GOODS_TEMPLATE_ID";
                            this.cmbTemplate.ItemsSource = listGOODS_TEMPLATE;
                         }
                    }
                );


            this.cmbTemplate.SelectionChanged += new SelectionChangedEventHandler
                ((cmbTemplateSender, cmbTemplateE) =>
                   {
                       if (this.cmbTemplate.SelectedValue != null)
                       {
                           this.TemplateList_Bind(Convert.ToInt32(this.cmbTemplate.SelectedValue));

                           this.StorageListBind(string.Format(" storage_id = -1"));
                       }
                   }

                 );
        }

        private void GOODS_BIND()
        {
            try
            {

                IList<SiaSun.LMS.Model.GOODS_MAIN> listGOODS_MAIN = MainApp._I_GoodsService.GoodsGetListGoodsClassID(3);

                this.cmbGoods.DisplayMemberPath = "GOODS_NAME";
                this.cmbGoods.SelectedValuePath = "GOODS_ID";
                this.cmbGoods.ItemsSource = listGOODS_MAIN;
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        private void InitManagePosotion()
        {
            this.ucManagePosition.U_InitControl(mMANAGE_TYPE.MANAGE_TYPE_ID);
        }

        private void TemplateList_Bind(int TEMPLATE_ID)
        {
            //数据源属性
            this.gridTemplateList.U_Clear();
            this.gridTemplateList.U_WindowName = this.GetType().Name;
            this.gridTemplateList.U_TableName = "V_GOODS_TEMPLATE_LIST";
            this.gridTemplateList.U_XmlTableName = "V_GOODS_TEMPLATE_LIST";
            this.gridTemplateList.U_Fields = "*";
            this.gridTemplateList.U_Where = string.Format("GOODS_TEMPLATE_ID  ={0}", TEMPLATE_ID);
            this.gridTemplateList.U_OrderField = "GOODS_TEMPLATE_LIST_ID";

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

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

            try
            {
                this.gridTemplateList.U_InitControl();
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        private void StorageListBind(string QueryWhere)
        {
            this.ucStorageList.U_WindowName = this.GetType().Name;
            this.ucStorageList.U_TableName = "V_STORAGE_LIST";
            this.ucStorageList.U_XmlTableName = "V_STORAGE_LIST";
            //this.ucStorageList.U_AppendFieldStyles = this.GetColumnDescriptionList();
            this.ucStorageList.U_TotalColumnName = "STORAGE_LIST_QUANTITY";
            this.ucStorageList.U_OrderField = "STORAGE_LIST_ID";
            this.ucStorageList.U_Where = QueryWhere;
            //this.ucStorageList.U_Where = string.Format("STOCK_BARCODE='{0}' AND AREA_TYPE= 'XuNiKu'", txtStockBarCode.Text);
            this.ucStorageList.U_AllowOperatData = false;
            this.ucStorageList.U_AllowChecked = true;
            this.ucStorageList.U_AllowShowPage = true;

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

            this.ucStorageList.U_InitControl();
        }

        private void WrapPanel_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            if (btn != null)
            {
                switch (btn.Name)
                {
                    case "btnConfirm":
                        this.CreateTask();
                        break;
                    case "btnQuery":
                        this.Query();
                        break;
                }
            }
        }

        /// <summary>
        /// 创建输送任务
        /// </summary>
        private void CreateTask()
        {
            bool boolResult = true;

            string strResult = string.Empty;

            try
            {
                if (!this.ucManagePosition.U_CHECK_WAREHOUSE())
                    return;


                listDataRowView = this.ucStorageList.U_GetCheckedDataRows();

                if (listDataRowView.Length == 0)
                {
                    MainApp._MessageDialog.Show(Enum.MessageConverter.SelectCount);
                    return;
                }

                //获得列表
                IDictionary<string, Model.WH_CELL> dicStack = this.GetPalletKeyValuePair(listDataRowView);

                //判断是否选中移库记录
                if (dicStack.Count == 0)
                {
                    MainApp._MessageDialog.Show(Enum.MessageConverter.CheckStack);
                    return;
                }


                DataRowView[] drvPLAN_LIST = this.gridTemplateList.U_GetCheckedDataRows();

                if (drvPLAN_LIST.Length == 0)
                {
                    MainApp._MessageDialog.Show(Enum.MessageConverter.SelectCount);
                    return;
                }

                List<Model.PLAN_LIST> listPLAN_LIST = new SiaSun.LMS.Common.CloneObjectValues().GetListFromDataTable<Model.PLAN_LIST>(drvPLAN_LIST.Cast<DataRowView>().ToArray(), null);

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

                if (MainApp._MessageDialog.ShowDialog(Enum.MessageConverter.ConfirmCreateTask, this.Title) == Sid.Windows.Controls.TaskDialogResult.Ok)
                {
                    //获得所有的选定的条码
                    foreach (KeyValuePair<string, Model.WH_CELL> stackCell in dicStack)
                    {
                        
                        //获得起始位置
                        int intStartAearID = stackCell.Value.AREA_ID;
                        int intStartPositionID = stackCell.Value.CELL_ID;



                        boolResult = MainApp._I_BaseService.Invoke(mMANAGE_TYPE.MANAGE_TYPE_CLASS.TrimEnd(), 
                                                                     "ManageCreate", 
                                                                      new object[] { 
                                                                                     MainApp._USER, 
                                                                                     null, 
                                                                                     mMANAGE_TYPE.MANAGE_TYPE_CODE.TrimEnd(), 
                                                                                     string.Empty,
                                                                                     intStartPositionID, 
                                                                                     this.ucManagePosition.U_END_POSITION_ID, 
                                                                                     listMANAGE_LIST,
                                                                                     true, 
                                                                                     false, 
                                                                                     false 
                                                                                    }, 
                                                                     out strResult);

                        //判断结果
                        if (!boolResult)
                        {
                            break;
                        }
                    }

                    MainApp._MessageDialog.ShowResult(boolResult, strResult);

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

        ///// <summary>
        ///// 获得托盘集合列表
        ///// </summary>
        private IDictionary<string, Model.WH_CELL> GetPalletKeyValuePair(DataRowView[] listDataRowView)
        {
            IDictionary<string, Model.WH_CELL> dicStack = new Dictionary<string, Model.WH_CELL>();
            foreach (DataRowView rowView in listDataRowView)
            {
                string stack =  rowView["STOCK_BARCODE"].ToString();
                if (stack != string.Empty)
                {
                    //获得货位编号
                    SiaSun.LMS.Model.WH_CELL mWH_CELL = (Model.WH_CELL)MainApp._I_BaseService.GetModel("WH_CELL_SELECT_BY_ID", Convert.ToInt32(rowView["CELL_ID"])).RequestObject;
                    if (mWH_CELL != null && !dicStack.ContainsKey(stack))
                    {
                        dicStack.Add(stack, mWH_CELL);
                    }
                }
            }
            return dicStack;
        }


        private void Query()
        {
            DataRowView[] checkDataRowView = this.gridTemplateList.U_GetCheckedDataRows();

            if (checkDataRowView.Length == 0)
            {
                MainApp._MessageDialog.Show(Enum.MessageConverter.SelectCount);
                return;
            }

            this.ucManagePosition.U_Refresh();

            string sTEMPLATE_LIST_ID = string.Empty;

            foreach (DataRowView drv in checkDataRowView)
            {
                sTEMPLATE_LIST_ID += drv["GOODS_TEMPLATE_LIST_ID"].ToString() + ",";
            }

            sTEMPLATE_LIST_ID = sTEMPLATE_LIST_ID.TrimEnd(',');

            string GOODS_PROPERTY = string.Empty;

            //IList<SiaSun.LMS.Model.GOODS_PROPERTY> lsGOODS_PROPERTY = MainApp._I_GoodsService.GoodsPropertyGetListGoodsTypeID(this.gridTemplateList.U_GetSelectedGoodsTypeID());

            //foreach (SiaSun.LMS.Model.GOODS_PROPERTY mGOODS_PROPERTY in lsGOODS_PROPERTY)
            //{
            //    GOODS_PROPERTY += string.Format(" AND ISNULL({0}.{1},{2}.{1}) = {2}.{1}", "PLAN_LIST", mGOODS_PROPERTY.GOODS_PROPERTY_FIELD, "V_STORAGE_LIST");
            //}

            string sQUERY = " (SELECT count(0) FROM GOODS_TEMPLATE_LIST WHERE V_STORAGE_LIST.GOODS_ID= GOODS_TEMPLATE_LIST.GOODS_ID {2} {0} AND  ( template_id = 0 or template_id is null) and GOODS_TEMPLATE_LIST_ID in ({1}))>0";

            this.StorageListBind(string.Format(sQUERY, GOODS_PROPERTY, sTEMPLATE_LIST_ID, this.STORAGE_AREA_TYPE == string.Empty ? string.Empty : string.Format(" AND V_STORAGE_LIST.AREA_TYPE = '{0}' ", this.STORAGE_AREA_TYPE)));
        }
        


    }
}