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_STORAGE_IN : AvalonDock.DocumentContent
    {
        int intPlanID = 0;

        Dictionary<string, bool> dicStoageLoad = new Dictionary<string, bool>();

        Model.PLAN_MAIN mPLAN_MAIN = null;

        Model.MANAGE_TYPE mMANAGE_TYPE = null;

        string xmlTableName = string.Empty;

        string strType = string.Empty;

        public MANAGE_STORAGE_IN(int PLAN_ID, string MANAGE_TYPE_CODE, string xmlTableName, string strType) : this(PLAN_ID, MANAGE_TYPE_CODE)
        {
            this.xmlTableName = xmlTableName;

            this.strType = strType;
        }

        public MANAGE_STORAGE_IN(int PLAN_ID, string MANAGE_TYPE_CODE)
        {
            InitializeComponent();

            this.intPlanID = PLAN_ID;

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

            this.ucQueryGoods.U_Query += new UC.ucQuickQuery.U_QueryEventHandler(ucQueryGoods_U_Query);
            this.gridGoods.gridApp.MouseDoubleClick += new MouseButtonEventHandler(gridApp_MouseDoubleClick);
        }

        void table_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            bool bResult = true;
            string sResult = string.Empty;

            switch (e.Column.ColumnName)
            {
                case "STORAGE_LIST_QUANTITY":
                    bResult = (string.Empty != e.ProposedValue.ToString()) && Convert.ToInt32(e.ProposedValue) > 0;
                    sResult = "填写数量必须是大于0!";
                    break;
            }

            if (bResult)
            {
                e.Row.RowError = null;
                e.Row.SetColumnError(e.Column, null);
            }
            else
            {
                e.Row.RowError = "该行数据有错误!";
                e.Row.SetColumnError(e.Column, sResult);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        private void DocumentContent_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.InitQueryControl();

                this.GoodsBind(string.Empty);

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

        void ucQueryGoods_U_Query(string QueryWhere)
        {
            this.GoodsBind(QueryWhere);
        }

        private void GoodsBind(string QueryWhere)
        {
            try
            {
                this.gridGoods.U_WindowName = this.GetType().Name;
                this.gridGoods.U_TableName = "V_GOODS";
                this.gridGoods.U_XmlTableName = "GOODS_MAIN";
                this.gridGoods.U_OrderField = "GOODS_CODE";
                this.gridGoods.U_Where = string.Format("GOODS_CLASS_ID<>2 and GOODS_FLAG=1 and {0}", string.IsNullOrEmpty(QueryWhere) ? "1=1" : QueryWhere);
                this.gridGoods.U_AllowOperatData = false;
                this.gridGoods.U_AllowChecked = false;
                this.gridGoods.U_InitControl();
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        private void InitQueryControl()
        {
            this.ucQueryGoods.U_WindowName = this.GetType().Name;
            this.ucQueryGoods.U_XmlTableName = "GOODS_MAIN";
            this.ucQueryGoods.U_InitControl();
        }

        void gridApp_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (gridGoods.gridApp.SelectedItem == null)
                return;

            //获得物料记录
            DataRowView rowViewGoods = this.gridGoods.gridApp.SelectedItem as DataRowView;

            //获得添加行
            DataTable tableManageList = this.Manage_LIST_Add_By_GOODS(0, new string[] { rowViewGoods["GOODS_ID"].ToString() });

            //添加行数据
            this.gridStorageList.U_AddTabPageRows(tableManageList.Rows.Cast<DataRow>().ToArray());
        }

        /// <summary>
        /// 添加列表信息返回表单集合
        /// </summary>
        public DataTable Manage_LIST_Add_By_GOODS(int STORAGE_ID, IList<string> listGOODS_ID)
        {
            //创建集合
            string strSql = string.Format("SELECT * FROM V_STORAGE_LIST WHERE STORAGE_ID={0}", 0);
            using (DataTable tableStorageList = MainApp._I_BaseService.GetList(strSql))
            {
                foreach (string strGoodsID in listGOODS_ID)
                {
                    //获得物料实体
                    SiaSun.LMS.Model.GOODS_MAIN mGOODS_MAIN = MainApp._I_GoodsService.GoodsGetModelGoodsID(Convert.ToInt32(strGoodsID));

                    SiaSun.LMS.Model.GOODS_CLASS mGOODS_CLASS = MainApp._I_GoodsService.GoodsClassGetModelGoodsClassID(mGOODS_MAIN.GOODS_CLASS_ID);

                    if (mGOODS_MAIN != null && mGOODS_CLASS != null)
                    {
                        DataRow rowStorageList = tableStorageList.NewRow();
                        rowStorageList["GOODS_ID"] = mGOODS_MAIN.GOODS_ID;
                        rowStorageList["GOODS_CODE"] = mGOODS_MAIN.GOODS_CODE;
                        rowStorageList["GOODS_NAME"] = mGOODS_MAIN.GOODS_NAME;
                        rowStorageList["GOODS_TYPE_ID"] = mGOODS_CLASS.GOODS_TYPE_ID;
                        rowStorageList["GOODS_UNITS"] = mGOODS_MAIN.GOODS_UNITS;

                        //rowStorageList["GOODS_CONST_PROPERTY1"] = mGOODS_MAIN.GOODS_CONST_PROPERTY1;

                        rowStorageList["MANAGE_LIST_QUANTITY"] = string.IsNullOrEmpty(mGOODS_MAIN.GOODS_CONST_PROPERTY3) ? "1" : mGOODS_MAIN.GOODS_CONST_PROPERTY3;
                        tableStorageList.Rows.Add(rowStorageList);
                    }
                }
                return tableStorageList;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void InitManagePosition()
        {
            try
            {
                this.ucManagePosition.U_InitControl(mMANAGE_TYPE.MANAGE_TYPE_ID);
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        /// <summary>
        /// 库存明细绑定
        /// </summary>
        private void StorageListBind()
        {
            if (!dicStoageLoad.ContainsKey(this.ucManagePosition.U_STOCK_BARCODE.TrimEnd()))
            {
                dicStoageLoad.Clear();
                dicStoageLoad.Add(this.ucManagePosition.U_STOCK_BARCODE.TrimEnd(), true);
            }


            this.gridStorageList.U_WindowName = this.GetType().Name;
            this.gridStorageList.U_TableName = "V_STORAGE_LIST";
            this.gridStorageList.U_XmlTableName = this.xmlTableName == string.Empty ? "V_STORAGE_LIST" : this.xmlTableName;
            this.gridStorageList.U_TotalColumnName = "MANAGE_LIST_QUANTITY";
            this.gridStorageList.U_OrderField = "STORAGE_LIST_ID";
            this.gridStorageList.U_Where = string.Format("STOCK_BARCODE='{0}' AND AREA_TYPE= 'XuNiKu'", this.ucManagePosition.U_STOCK_BARCODE);

            //this.gridStorageList.U_AllowOperatData = true;
            this.gridStorageList.U_AllowChecked = false;
            this.gridStorageList.U_AllowShowPage = false;

            this.gridStorageList.U_AllowAdd = System.Windows.Visibility.Collapsed;
            this.gridStorageList.U_AllowEdit = System.Windows.Visibility.Collapsed;
            this.gridStorageList.U_AllowSave = System.Windows.Visibility.Collapsed;

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

            this.gridStorageList.U_InitControl();
        }

        /// <summary>
        /// 按钮事件
        /// </summary>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            if (btn != null)
            {
                switch (btn.Name)
                {
                    case "btnSave":
                        this.Confirm();
                        break;
                    case "btnRefresh":
                        this.Refresh();
                        break;
                }
            }
        }

        /// <summary>
        /// 确认
        /// </summary>
        private void Confirm()
        {
            string strResult = string.Empty;

            try
            {
                MainWindow.mainWin.Cursor = Cursors.Wait;

                this.gridStorageList.U_EndCurrentEdit();

                DataTable tableSource = this.gridStorageList.U_DataSource;

                foreach (DataRow dr in tableSource.Rows)
                {
                    if (Convert.ToDecimal(dr["MANAGE_LIST_QUANTITY"]) > 0)
                        dr["MANAGE_LIST_QUANTITY"] = dr["STORAGE_LIST_QUANTITY"];
                }

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

                var list = from v in listMANAGE_LIST
                           where v.MANAGE_LIST_QUANTITY > 0
                           select v;

                listMANAGE_LIST = list.ToList<Model.MANAGE_LIST>();

                if (tableSource == null || tableSource.Rows.Count == 0 || listMANAGE_LIST.Count == 0)
                {
                    MainApp._MessageDialog.Show(Enum.MessageConverter.Input);
                    return;
                }

                if (tableSource.HasErrors)
                {
                    MainApp._MessageDialog.Show(Enum.MessageConverter.Data);
                    return;
                }

                if (!this.gridStorageList.U_Check_Split_Property("GOODS_PROPERTY", out strResult))
                {
                    MainApp._MessageDialog.ShowResult(false, strResult);
                    return;
                }

                if (strType == "PK")
                {
                    if (!this.ucManagePosition.U_STOCK_BARCODE.Contains("-"))
                    {
                        MainApp._MessageDialog.ShowResult(false, "平库区入库托盘条码格式输入不正确!");
                        return;
                    }
                }
                else
                {
                    if (!this.ucManagePosition.U_CHECK_WAREHOUSE())
                        return;
                }

                if (MainApp._MessageDialog.ShowDialog(Enum.MessageConverter.ConfirmAssembly, this.ucManagePosition.U_STOCK_BARCODE) == Sid.Windows.Controls.TaskDialogResult.Ok)
                {
                    SiaSun.LMS.Model.MANAGE_MAIN mMANAGE_MAIN = new Model.MANAGE_MAIN();

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

                    mMANAGE_MAIN.STOCK_BARCODE = this.ucManagePosition.U_STOCK_BARCODE;

                    if (!string.IsNullOrEmpty(this.ucManagePosition.U_STOCK_BARCODE.ToString().Trim()) && this.ucManagePosition.U_STOCK_BARCODE.ToString().Trim().Contains("-"))
                    {
                        DataTable dtCell = MainApp._I_BaseService.GetList(string.Format("select * from WH_CELL where CELL_CODE='{0}'", this.ucManagePosition.U_STOCK_BARCODE.ToString().Trim()));

                        if (dtCell != null && dtCell.Rows.Count > 0)
                        {
                            if (Convert.ToInt32(dtCell.Rows[0]["AREA_ID"]) == 1 || Convert.ToInt32(dtCell.Rows[0]["AREA_ID"]) == 2)
                            {
                                MainApp._MessageDialog.ShowResult(false, "货位不在平库区!");

                                return;
                            }

                            mMANAGE_MAIN.START_CELL_ID = Convert.ToInt32(dtCell.Rows[0]["CELL_ID"]);

                            mMANAGE_MAIN.END_CELL_ID = Convert.ToInt32(dtCell.Rows[0]["CELL_ID"]);

                            mMANAGE_MAIN.CELL_MODEL = this.ucManagePosition.U_CELL_MODEL;

                            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;

                        }
                        else
                        {
                            MainApp._MessageDialog.ShowResult(false, "检查是否存在该货位!");
                            return;
                        }
                    }
                    else
                    {
                        mMANAGE_MAIN.CELL_MODEL = this.ucManagePosition.U_CELL_MODEL;

                        mMANAGE_MAIN.START_CELL_ID = this.ucManagePosition.U_START_POSITION_ID;

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

                    bool bResult = false;

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


                    //检验执行结果
                    if (bResult)
                    {
                        if (!this.rbRefresh.IsChecked.Value)
                            this.gridStorageList.U_Update();

                        this.Refresh();
                    }

                    MainApp._MessageDialog.ShowResult(bResult, strResult);

                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
            finally
            {
                MainWindow.mainWin.Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void Refresh()
        {
            this.ucManagePosition.U_Refresh();
        }
    }
}