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 System.Drawing;

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

        List<Model.MANAGE_LIST> listMANAGE_LIST = null;

        DataRowView[] listDataRowView = null;

        #region  构造函数

        public ManageDownOutBox(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}{2}",
                                          this.ucSplitPanel.U_GetSplitPropertyWhere(),
                                          string.IsNullOrEmpty(QueryWhere) ? "1=1" : QueryWhere,
                                          string.Format(" AND AREA_TYPE = 'LiKu' "));

                                          this.StorageListBind(QueryWhere);
                                      }
                                    );
        }

        #endregion

        #region 系统方法

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

            //属性控件
            this.InitSplitPropertyPanel();
            //查询控件
            this.InitQueryControl();

            Plan_Type_Bind();
        }

        #endregion

        #region 自定义方法

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


        /// <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 Plan_Type_Bind()
        {
            this.cbbPLAN_TYPE.DisplayMemberPath = "PLAN_TYPE_NAME";
            this.cbbPLAN_TYPE.SelectedValuePath = "PLAN_TYPE_CODE";
            try
            {
                string strSQL = string.Format(@"SELECT PLAN_TYPE_CODE,
                                                   PLAN_TYPE_NAME 
                                              FROM PLAN_TYPE
                                                WHERE PLAN_TYPE_INOUT = '2'
                                                  AND PLAN_TYPE_FLAG= '1' 
                                                  ORDER BY PLAN_TYPE_ORDER");

                this.cbbPLAN_TYPE.ItemsSource = MainApp._I_BaseService.GetList(strSQL).DefaultView;

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

        private void Register_DataTable_Event()
        {
            //当输入列值改变后验证数据是否合法
            foreach (TabItem tabItem in this.ucStorageGroup.tabSplitProperty.Items)
            {
                if (tabItem.HasContent)
                {
                    DataTable tableSource = (tabItem.Content as UC.ucCommonDataGrid).U_DataSource.Table;

                    tableSource.ColumnChanged -= new DataColumnChangeEventHandler(table_ColumnChanged);
                    tableSource.ColumnChanged += new DataColumnChangeEventHandler(table_ColumnChanged);
                }
            }
        }

        /// <summary>
        /// 表单数据校验
        /// </summary>
        private void table_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            bool bResult = true;
            string sResult = string.Empty;
            //判断列
            switch (e.Column.ColumnName)
            {
                case "MANAGE_LIST_QUANTITY":

                    //bResult = (string.Empty != e.ProposedValue.ToString()) && Convert.ToDecimal(e.ProposedValue) > 0;

                    //sResult = "请输入大于0的数量";

                    //bResult = (Convert.ToDecimal(e.ProposedValue) <= Convert.ToDecimal(e.Row["STORAGE_LIST_QUANTITY"]));

                    //sResult = string.Format("出库数量不能大于库存数量!");

                    break;
            }

            if (bResult)
            {
                e.Row.RowError = null;
                e.Row.SetColumnError(e.Column, null);
            }
            else
            {
                e.Row.RowError = "数据校验失败";
                e.Row.SetColumnError(e.Column, sResult);
            }
        }

        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 CELL_STATUS <> 'PalletH' and GOODS_CONST_PROPERTY7=0 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();

            Register_DataTable_Event();
        }

        #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.CreateTaskOut();
                        break;
                    case "btnRefresh":
                        this.Refresh();
                        break;
                }
            }
        }

        /// <summary>
        /// 创建下架出库任务
        /// </summary>
        private void CreateTaskOut()
        {
            bool boolResult = false;
            bool boolSingleResult = true;
            string strResult = string.Empty;           
            string sSingleReslut = string.Empty;

            ////循环判断带marking
            //string d = "TKMQWRWF";
            //string b = "AB,CD,WF,123";
            //string[] c = b.Split(',');
            //foreach (string s in c)
            //{
            //    if (d.Contains(s))

            //    {
            //        boolResult = true;


            //    }
            //}

            try
            {
                //获得选中记录
                 listDataRowView = this.ucStorageGroup.U_GetCheckedDataRows();

                this.ucStorageGroup.U_EndCurrentEdit();
                //string AA= listDataRowView[0]["GOODS_PROPERTY1"].ToString();

                boolResult = this.ucManagePosition.U_CHECK_WAREHOUSE();

                if (!boolResult)
                    return;

                #region 校验表单数据

                if (this.ucStorageGroup.U_DataSource.HasErrors)
                {
                    MainApp._MessageDialog.Show(false, "表单存在不合法的数据");
                    return;
                }
                
                if (listDataRowView.Length == 0)
                {
                    MainApp._MessageDialog.Show(false,"请选中要出库的记录");
                    return;
                }
                string[] batchno = new string[listDataRowView.Length];
                for (int i = 0; i < listDataRowView.Length; i++)
                {
                    batchno[i] = listDataRowView[i]["GOODS_CODE"].ToString();


                }
                for (int j = 0; j < batchno.Length - 1; j++)
                {
                    if (!batchno[j].Equals(batchno[j + 1]))
                    {
                        MainApp._MessageDialog.Show(false, "当前有不同批次的物料,重新选择后再进行出库");
                        return;

                    }

                }

                DataTable dt_cell = MainApp._I_BaseService.GetList(string.Format(@"select * from wh_cell where cell_code = '12097'", this.ucManagePosition.U_END_POSITION_ID));

                if (this.ucManagePosition.U_END_POSITION_ID !=16646)
                {
                    MainApp._MessageDialog.Show(false, "该物料不能出到纸箱出口");
                    return;

                }
                #endregion

                #region 校验出库类型

                if (this.cbbPLAN_TYPE.SelectedValue == null)
                {
                    MainApp._MessageDialog.Show(false, "请选择出库类型");
                    return;
                }

                #endregion

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


                
                if (MainApp._MessageDialog.ShowDialog("确认下达【下架出库】任务") == 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);

                        var list = listMANAGE_LIST.Where(v => v.MANAGE_LIST_QUANTITY >= 0);

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

                        //无计划下架出库,清空计划
                        foreach (Model.MANAGE_LIST mMANAGE_LIST in listMANAGE_LIST)
                        {
                            DataTable dt_STORAGE_LIST = MainApp._I_BaseService.GetList(string.Format(@"select * from V_STORAGE_LIST where STORAGE_LIST_id = {0}", mMANAGE_LIST.STORAGE_LIST_ID));
                            if (dt_STORAGE_LIST.Rows.Count<=0)
                            {
                                MainApp._MessageDialog.Show(false, "未找到物料明细");
                                return;        
                            }
                            DataTable dt_GOODS_MAIN = MainApp._I_BaseService.GetList(string.Format(@"select * from GOODS_MAIN where GOODS_ID = {0}", mMANAGE_LIST.GOODS_ID));
                            if (dt_GOODS_MAIN.Rows.Count <= 0)
                            {
                                MainApp._MessageDialog.Show(false, "未找到该物料属性,系统无此物料");
                                return;
                            }
                            
                            mMANAGE_LIST.PLAN_LIST_ID = 0;
                            mMANAGE_LIST.MANAGE_LIST_QUANTITY =Convert.ToDecimal(dt_STORAGE_LIST.Rows[0]["STORAGE_LIST_QUANTITY"].ToString());
                            mMANAGE_LIST.GOODS_PROPERTY2 = dt_GOODS_MAIN.Rows[0]["GOODS_CODE"].ToString();
                            DataTable dt_whcell = MainApp._I_BaseService.GetList(string.Format(@"select * from wh_cell where cell_id = {0}", this.ucManagePosition.U_END_POSITION_ID));
                            if (dt_whcell != null && dt_whcell.Rows[0]["CELL_CODE"].ToString().Equals("12043"))
                            {
                                DataTable dtcontrol = MainApp._I_BaseService.GetList(string.Format(@"select * from io_control where end_device_code='12043'"));
                                if (dtcontrol.Rows.Count > 0)
                                {
                                    foreach (DataRow dr in dtcontrol.Rows)
                                    {
                                        if (!dr["control_remark"].Equals(mMANAGE_LIST.GOODS_PROPERTY2))
                                        {
                                            //判断该盘是否进主线
                                            if (dr["control_status"].ToString().Equals("50"))
                                            {
                                                continue;
                                            }
                                            else
                                            {
                                                MainApp._MessageDialog.Show(false, "当前有未执行完的其他批次物料,请稍后再进行出库");
                                                return;
                                            }

                                        }
                                    }
                                }
                                else
                                {


                                }
                            }
                        }

                        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;

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

                        mMANAGE_MAIN.PLAN_TYPE_CODE = this.cbbPLAN_TYPE.SelectedValue.ToString();

                        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;

                        //if (this.ucManagePosition.U_END_POSITION_ID ==13209 && mSTORAGE_MAIN.CELL_MODEL.Equals("1"))
                        //{
                        //    MainApp._MessageDialog.Show(false, "该物料在高货位不能出库到叠料架机,请更换物料或出库位置稍后再进行出库");
                        //    return;
                                                
                        //}
                        //if (this.ucManagePosition.U_END_POSITION_ID == 13209 && Convert.ToInt32( listMANAGE_LIST[0].GOODS_ID)==)
                        //{
                        //    MainApp._MessageDialog.Show(false, "该物料在高货位不能出库到叠料架机,请更换物料或出库位置稍后再进行出库");
                        //    return;

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

                        mMANAGE_MAIN.MANAGE_LEVEL = string.Empty;

                        mMANAGE_MAIN.MANAGE_REMARK = string.Empty;

                        //未输入出库数量,下达【实盘下架】任务
                        if (listMANAGE_LIST.Count == 0)
                        {
                            //#region ManageDown类型

                            //Model.MANAGE_TYPE mNEW_MANAGE_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 = SiaSun.LMS.Enum.MANAGE_TYPE.ManageDown.ToString();
                            //mMANAGE_MAIN.PLAN_TYPE_CODE = string.Empty;        
                            //#endregion
                            //listMANAGE_LIST = new SiaSun.LMS.Common.CloneObjectValues().GetListFromDataTable<Model.MANAGE_LIST>(value_storage_id.Cast<DataRowView>().ToArray(), null);
                            //boolSingleResult = MainApp._I_BaseService.Invoke(mNEW_MANAGE_TYPE.MANAGE_TYPE_CLASS.TrimEnd(),
                            //                     "ManageCreate",
                            //                      new object[] {mMANAGE_MAIN,
                            //                                 listMANAGE_LIST,
                            //                                 true,
                            //                                 this.cbControl.IsChecked
                            //                                },
                            //                      out sSingleReslut);
                            boolSingleResult = false;
                            sSingleReslut = "请输入数量";

                        }
                        else
                        {
                            boolSingleResult = MainApp._I_BaseService.Invoke(mMANAGE_TYPE.MANAGE_TYPE_CLASS.TrimEnd(),
                                                 "ManageCreate",
                                                  new object[] { mMANAGE_MAIN,
                                                             listMANAGE_LIST,
                                                             true,
                                                             this.cbControl.IsChecked
                                                            },
                                                  out sSingleReslut);
                        }

                        if (!boolSingleResult)
                        {
                            strResult += value_storage_id.Cast<DataRowView>().ToArray()[0]["CELL_CODE"].ToString() + " 任务下达失败 " + sSingleReslut + "\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.ucManagePosition.U_Update();
            //this.Plan_Type_Bind();
        }

        #endregion

    }
}