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>
    /// MANAGE_MOVE_OUT.xaml 的交互逻辑
    /// </summary>
    public partial class MANAGE_DOWN : AvalonDock.DocumentContent
    {
        Model.MANAGE_TYPE mMANAGE_TYPE = null;

        List<Model.MANAGE_LIST> listMANAGE_LIST = null;

        /// <summary>
        ///
        /// </summary>
        public MANAGE_DOWN(string MANAGE_TYPE_CODE)
        {
            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} AND {1}", this.ucSplitPanel.U_GetSplitPropertyWhere(), string.IsNullOrEmpty(QueryWhere) ? "1=1" : QueryWhere);
                      this.StorageListBind(QueryWhere);
                  }
                );
        }

        //加载窗体
        private void DocumentContent_Loaded(object sender, RoutedEventArgs e)
        {
            //输送位置
            this.InitManagePosotion();
            //属性控件
            this.InitSplitPropertyPanel();
            //查询控件
            this.InitQueryControl();

        }

        /// <summary>
        /// 初始化输送位置控件
        /// </summary>
        private void InitManagePosotion()
        {
            this.ucManagePosition.U_InitControl(mMANAGE_TYPE.MANAGE_TYPE_ID);
        }


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

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

        private void StorageListBind(string QueryWhere)
        {
            this.ucStorageGroup.U_WindowName = this.GetType().Name;
            this.ucStorageGroup.U_TableName = "V_STORAGE_LIST";
            this.ucStorageGroup.U_XmlTableName = "V_STORAGE_LIST";
            //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_status <> 'Pallet'  AND AREA_TYPE= 'LiKu' and cell_id not in ( select start_cell_id from manage_main) and {0} ",
                                                            QueryWhere);

            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();
        }

        /// <summary>
        /// 按钮事件
        /// </summary>
        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 "btnRefresh":
                        this.Refresh();
                        break;
                }
            }
        }

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

            bool boolSingleResult = true;

            string strResult = "\n";

            string sSingleReslut = string.Empty;

            try
            {
                //校验填写仓库信息是否合法
                if (!this.ucManagePosition.U_CHECK_WAREHOUSE())
                    return;

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

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

                //校验是否选中记录
                if (listDataRowView.Count == 0)
                {
                    MainApp._MessageDialog.Show(false, "是否选中记录");
                    return;
                }

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


                if (MainApp._MessageDialog.ShowDialog("确认创建输送任务") == Sid.Windows.Controls.TaskDialogResult.Ok)
                {

                    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.MANAGE_TYPE_CODE.TrimEnd();

                        mMANAGE_MAIN.PLAN_ID = 0;

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

                        mMANAGE_MAIN.CELL_MODEL = this.ucManagePosition.U_CELL_MODEL;

                        mMANAGE_MAIN.START_CELL_ID = intStartPositionID;

                        mMANAGE_MAIN.END_CELL_ID = this.ucManagePosition.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.MANAGE_TYPE_CLASS.TrimEnd(),
                                             "ManageCreate",
                                              new object[] { mMANAGE_MAIN,
                                                             listMANAGE_LIST,
                                                             true,                                                            
                                                             this.ucManagePosition.U_AutoCompleteTask ,
                                                             this.ucManagePosition.U_AutoDownloadControlTask, 
                                                            },
                                              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();
                }


                MainApp._MessageDialog.Show(boolResult, strResult);

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

        /// <summary>
        /// 获得托盘集合列表
        /// </summary>
        private IDictionary<string, Model.WH_CELL> GetPalletKeyValuePair(List<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;
        }

        /// <summary>
        /// 刷新
        /// </summary>
        private void Refresh()
        {
            //刷新
            this.ucManagePosition.U_Update();

            this.ucStorageGroup.U_InitControl();
        }


    }
}