using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using Newtonsoft.Json.Linq;
using BLL;
namespace FineUIPro.Web.HJGL.MaterialManage
{
    public partial class ShowStockIn : PageBase
    {
        /// 
        /// 计划ID
        /// 
        private string UsingPlanId
        {
            get
            {
                return (string)ViewState["UsingPlanId"];
            }
            set
            {
                ViewState["UsingPlanId"] = value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.UsingPlanId = Request.Params["UsingPlanId"];
                var plan = BLL.UsingPlanService.GetUsingPlanById(this.UsingPlanId);
                var welder = BLL.WelderService.GetWelderById(plan.UsingManOne);
                decimal usedAmount = BLL.UsingMatService.GetUsingAmountSum(this.UsingPlanId);
                string strUsing = string.Empty;
                if (plan != null && welder != null)
                {
                    strUsing = "焊工:" + welder.WED_Code + "-" + welder.WED_Name + "计划领用焊材数量为:" + plan.Amount.Value.ToString();
                }
                if (usedAmount > 0)
                {
                    strUsing = strUsing + "已领用:" + usedAmount.ToString();
                }
                this.lbUsingMatInfo.Text = strUsing;
                // 绑定表格
                BindGrid();
            }
        }
        #region 绑定数据
        /// 
        /// 绑定数据
        /// 
        private void BindGrid()
        {
            var plan = BLL.UsingPlanService.GetUsingPlanById(this.UsingPlanId);
            string strSql = @" SELECT StockIn.StockInId, StockIn.WeldId,StockIn.Warrantybook,
                                      WeldInfo.ConsumablesCode,WeldInfo.ConsumablesName,WeldInfo.SteelFormat,
                                      case WeldInfo.ConsumablesType when '1' then '焊丝' when '2' then '焊条' when '3' then '焊剂' else '' end as WeldTypeName,'根' AS WeldUnit,store.UnitStoreName,
                                      (StockIn.Amount-ISNULL(StockIn.UsingAmount,0)) AS StockAmount,
									  StockIn.HeartNo, StockIn.RecycleAmount, @OneAmount as  OneAmount 
                                 FROM Weld_StockIn AS StockIn
                                     LEFT JOIN Base_Consumables AS WeldInfo ON WeldInfo.ConsumablesId = StockIn.WeldId
									 LEFT JOIN dbo.Weld_UnitStore store ON store.UnitStoreId = StockIn.UnitStoreId
                                WHERE (StockIn.Amount-ISNULL(StockIn.UsingAmount,0)+ISNULL(StockIn.RecycleAmount,0))>0 
                                       AND StockIn.WeldId=@WeldId AND (StockIn.Amount-ISNULL(StockIn.UsingAmount,0))>0 and store.UnitId=@UnitId ";
            List listStr = new List();
            listStr.Add(new SqlParameter("@UnitId", plan.UsingUnit));
            if (plan != null)
            {
                listStr.Add(new SqlParameter("@OneAmount", plan.Amount));
                listStr.Add(new SqlParameter("@WeldId", plan.WeldId));
            }
            else
            {
                listStr.Add(new SqlParameter("@WeldId", null));
            }
            //if (CurrUser.UnitId != null)
            //{
            //    listStr.Add(new SqlParameter("@UnitId", CurrUser.UnitId));
            //}
            //else
            //{
            //    listStr.Add(new SqlParameter("@UnitId", null));
            //}
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            // 2.获取当前分页数据
            Grid1.RecordCount = tb.Rows.Count;
            //tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetSortTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        #endregion
        #region 确定按钮
        /// 
        /// 确定按钮
        /// 
        /// 
        /// 
        protected void btnSure_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string selectRowId = Grid1.SelectedRowID;
            decimal oneAmount = 0;
            decimal twoAmount = 0;
            JArray mergedData = Grid1.GetMergedData();
            foreach (JObject mergedRow in mergedData)
            {
                JObject values = mergedRow.Value("values");
                string stockInId = values.Value("StockInId");
                if (Grid1.SelectedRowIDArray.Contains(stockInId))
                {
                    if (values.Value("OneAmount") != "" && values.Value("StockAmount") != "")
                    {
                        if (values.Value("OneAmount") > values.Value("StockAmount"))
                        {
                            Alert.ShowInTop("一次领用数量的库存不足!", MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    if (values.Value("TwoAmount") != "" && values.Value("RecycleAmount") != "")
                    {
                        if (values.Value("TwoAmount") > values.Value("RecycleAmount"))
                        {
                            Alert.ShowInTop("二次领用数量的库存不足!", MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    if (values.Value("OneAmount") != "")
                    {
                        oneAmount += values.Value("OneAmount");
                    }
                    if (values.Value("TwoAmount") != "")
                    {
                        twoAmount += values.Value("TwoAmount");
                    }
                }
            }
            var plan = BLL.UsingPlanService.GetUsingPlanById(this.UsingPlanId);
            if (plan != null)
            {
                if (oneAmount + twoAmount > plan.Amount)
                {
                    Alert.ShowInTop("领用数量要不能大于计划数量,请重新录入数量!", MessageBoxIcon.Warning);
                    return;
                }
                string UsingMan = string.Empty;
                string UsingMatId = string.Empty;
                foreach (JObject mergedRow in mergedData)
                {
                    JObject values = mergedRow.Value("values");
                    string stockInId = values.Value("StockInId");
                    if (Grid1.SelectedRowIDArray.Contains(stockInId))
                    {
                        var stockIn = BLL.StockInService.GetStockInById(stockInId);
                        Model.Weld_UsingMat usingMat = new Model.Weld_UsingMat();
                        usingMat.UsingMatId = SQLHelper.GetNewID(typeof(Model.Weld_UsingMat));
                        UsingMatId = usingMat.UsingMatId;
                        var project = BLL.ProjectService.GetProjectByProjectId(plan.ProjectId);
                        usingMat.ProjectId = plan.ProjectId;
                        usingMat.UsingPlanId = this.UsingPlanId;
                        usingMat.Amount = Funs.GetNewDecimalOrZero(values.Value("OneAmount"));
                        usingMat.TwoAmount = Funs.GetNewDecimalOrZero(values.Value("TwoAmount"));
                        usingMat.UsingMan = plan.UsingManOne;
                        UsingMan = usingMat.UsingMan;
                        usingMat.UsingDate = DateTime.Now;
                        usingMat.Warrantybook = stockIn.Warrantybook;
                        if (!string.IsNullOrEmpty(stockIn.Number))
                        {
                            usingMat.Number = stockIn.Number;
                        }
                        else
                        {
                            string perfix = project.ProjectCode + "-";
                            usingMat.Number = BLL.SQLHelper.RunProcNewIdByProjectId("SpGetNewCodeByProjectId", "dbo.Weld_UsingMat", "Number", plan.ProjectId, perfix);
                        }
                        usingMat.StockInId = stockInId;
                        usingMat.UsePosition = plan.UsePosition;
                        usingMat.WeldId = plan.WeldId;
                        var user = BLL.UserService.GetUserByUserId(CurrUser.UserId);
                        if (user != null)
                        {
                            usingMat.StoreMan = user.UserId;
                        }
                        if (usingMat.Amount + usingMat.TwoAmount > 0)
                        {
                            BLL.UsingMatService.AddUsingMat(usingMat);
                            // 修改库存已使用的数量
                            BLL.StockInService.UpdateStockInUsingAmount(usingMat.StockInId, usingMat.Amount, usingMat.TwoAmount);
                        }
                        else
                        {
                            ShowNotify("请填写领用数量!");
                        }
                        //string window = String.Format("UsingMatCheck.aspx?keyId={0}&grid=1&isFinger=1&FingerOrFace={1}", UsingMatId, "2", "编辑 - ");
                        //PageContext.RegisterStartupScript(Window1.GetSaveStateReference(UsingMan)
                        //  + Window1.GetShowReference(window));
                    }
                }
                PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
                ShowNotify("领料完成,请点击焊材领用记录进行确认!", MessageBoxIcon.Success);
            }
            //if (Grid1.SelectedRowIndexArray.Length == 0)
            //{
            //    Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
            //    return;
            //}
            //string[] selectRowId = Grid1.SelectedRowIDArray;
            //string stockIds = string.Empty;
            //foreach (string s in selectRowId)
            //{
            //    stockIds = stockIds + s + ",";
            //}
            //string StockItem = string.Empty;
            //decimal oneTotalNum = 0;
            //decimal twoTotalNum = 0;
            //JArray mergedData = Grid1.GetMergedData();
            //foreach (JObject mergedRow in mergedData)
            //{
            //    string oneAmount = "0";
            //    string twoAmount = "0";
            //    JObject values = mergedRow.Value("values");
            //    string stockInId = values.Value("StockInId");
            //    if (selectRowId.Contains(stockInId))
            //    {
            //        if (values.Value("OneAmount") != "" && values.Value("StockAmount") != "")
            //        {
            //            if (values.Value("OneAmount") > values.Value("StockAmount"))
            //            {
            //                Alert.ShowInTop("一次领用数量的库存不足!", MessageBoxIcon.Warning);
            //                return;
            //            }
            //        }
            //        if (values.Value("TwoAmount") != "" && values.Value("RecycleAmount") != "")
            //        {
            //            if (values.Value("TwoAmount") > values.Value("RecycleAmount"))
            //            {
            //                Alert.ShowInTop("二次领用数量的库存不足!", MessageBoxIcon.Warning);
            //                return;
            //            }
            //        }
            //        if (values.Value("OneAmount") != "")
            //        {
            //            oneAmount = values.Value("OneAmount");
            //            oneTotalNum = oneTotalNum + values.Value("OneAmount");
            //        }
            //        if (values.Value("TwoAmount") != "")
            //        {
            //            twoAmount = values.Value("TwoAmount");
            //            twoTotalNum = twoTotalNum + values.Value("TwoAmount");
            //        }
            //        StockItem = StockItem + stockInId + "," + oneAmount + "," + twoAmount + "|";
            //    }
            //}
            //var plan = BLL.UsingPlanService.GetUsingPlanById(this.UsingPlanId);
            //if (oneTotalNum + twoTotalNum > plan.Amount)
            //{
            //    Alert.ShowInTop("领用数量要不能大于计划数量,请重新录入数量!", MessageBoxIcon.Warning);
            //    return;
            //}
            //else
            //{
            //    StockItem = StockItem.Substring(0, StockItem.Length - 1);
            //    string itemsString = this.UsingPlanId + "$" + StockItem;
            //    PageContext.RegisterStartupScript(ActiveWindow.GetWriteBackValueReference(itemsString)
            //           + ActiveWindow.GetHidePostBackReference());
            //}
        }
        #endregion
    }
}