using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using BLL;
using Newtonsoft.Json.Linq;
using System.Web.UI;
using System.IO;
namespace FineUIPro.Web.HJGL.MaterialManage
{
    public partial class UsingMat : PageBase
    {
        #region 定义变量
        /// 
        /// 焊工Id
        /// 
        private string WelderId
        {
            get
            {
                return (string)ViewState["WelderId"];
            }
            set
            {
                ViewState["WelderId"] = value;
            }
        }
        private string UsingPlanId
        {
            get
            {
                return (string)ViewState["UsingPlanId"];
            }
            set
            {
                ViewState["UsingPlanId"] = value;
            }
        }
        protected string hfSpeak = "";
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //this.WelderId = Request.Params["welderId"];//指纹
                //string identityCard = Request.Params["identityCard"];//人脸识别
                string welderCode = Request.Params["welderCode"]; //焊工号录入
                string welderQRCode = Request.Params["welderQRCode"];
                if (!string.IsNullOrEmpty(welderQRCode) && (welderQRCode.Contains("¥") || welderQRCode.Contains("$")))
                {
                    string identityCard = string.Empty;
                    DateTime? dtime = new DateTime();
                    if (welderQRCode.Contains("¥"))
                    {
                        identityCard = welderQRCode.Split('¥')[0];
                        dtime = ConvertUnixTimeStampToDateTime(welderQRCode.Split('¥')[1]);
                    }
                    if (welderQRCode.Contains("$"))
                    {
                        identityCard = welderQRCode.Split('$')[0];
                        dtime = ConvertUnixTimeStampToDateTime(welderQRCode.Split('$')[1]);
                    }
                    var w = BLL.WelderService.GetWelderByIdentityCard(identityCard);
                    if (w != null && dtime != null)
                    {
                        if (dtime.Value.AddMinutes(2) > DateTime.Now)
                        {
                            welderCode = w.WED_Code;
                        }
                        else
                        {
                            Alert.ShowInTop("二维码超时,请重新扫码进入!", MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    else
                    {
                        Alert.ShowInTop("您不是焊工,无法领料!", MessageBoxIcon.Warning);
                        return;
                    }
                }
                //if (!string.IsNullOrEmpty(identityCard))
                //{
                //    //FingerOrFace = "1";//0-指纹,1-人脸识别
                //    var w = BLL.HJGL_PersonManageService.GetWelderByIdentityCard(identityCard);
                //    if (w != null)
                //    {
                //        this.WelderId = w.WED_ID;
                //    }
                //    else
                //    {
                //        Alert.ShowInTop("请先采集人脸", MessageBoxIcon.Warning);
                //        return;
                //    }
                //}
                if (!string.IsNullOrEmpty(welderCode))
                {
                    string welderId = string.Empty;
                    var q = from x in BLL.Funs.DB.BS_Welder where x.WED_Code == welderCode && x.WED_IfOnGuard == true select x;
                    if (q.Count() == 1)
                    {
                        this.WelderId = q.First().WED_ID;
                        //if (this.CurrUser.RoleId != Const.cgbgyId)
                        //{
                        //    Alert.ShowInTop("登录的用户必需为仓库保管员角色!", MessageBoxIcon.Warning);
                        //    return;
                        //}
                        //else
                        //{
                        //}
                    }
                    else if (q.Count() > 1)
                    {
                        Alert.ShowInTop("存在相同的焊工号,请排查!", MessageBoxIcon.Warning);
                        return;
                    }
                    else
                    {
                        Alert.ShowInTop("该焊工号不存在或不在岗!", MessageBoxIcon.Warning);
                        return;
                    }
                }
                //this.ProjectId = Request.Params["projectId"];
                //if (WelderId != null)
                //{
                //    var w = BLL.HJGL_PersonManageService.GetWelderByWenId(WelderId);
                //    ClientScript.RegisterStartupScript(ClientScript.GetType(), "", "");
                //}
                #region 默认退料:24小时 暂取消
                //string strSql = @"SELECT m.UsingMatId, m.UsingDate, wtype.WeldTypeName
                //                    FROM dbo.Weld_UsingMat m
                //                          LEFT JOIN dbo.Weld_UsingPlan usingPlan ON usingPlan.UsingPlanId = m.UsingPlanId 
                //                         LEFT JOIN dbo.Weld_WeldInfo weld ON weld.WeldId = m.WeldId
                //                         LEFT JOIN dbo.Weld_WeldType wtype ON wtype.WeldTypeId = weld.WeldTypeId
                //                   WHERE  m.IsWelderConfirm=1 AND m.IsStoreManConfirm=1
                //                          AND (IsClose IS NULL OR IsClose=0) 
                //                          AND usingPlan.UsingManOne=@WelderId ";
                //List listStr = new List();
                //listStr.Add(new SqlParameter("@WelderId", this.WelderId));
                //SqlParameter[] parameter = listStr.ToArray();
                //DataTable dt = SQLHelper.GetDataTableRunText(strSql, parameter);
                //if (dt.Rows.Count > 0)
                //{
                //    for (int i = 0; i < dt.Rows.Count; i++)
                //    {
                //        DateTime usingDate = Convert.ToDateTime(dt.Rows[i]["UsingDate"]);
                //        string type = dt.Rows[i]["WeldTypeName"].ToString();
                //        string usingMatId = dt.Rows[i]["UsingMatId"].ToString();
                //        if (usingDate.AddHours(24) < DateTime.Now)
                //        {
                //            BLL.UsingMatService.UsingMatIsColse(usingMatId, true);
                //            var recycleMat = BLL.RecycleMatService.GetRecycleMatByUsingMatId(usingMatId);
                //            var mat = BLL.UsingMatService.GetUsingMatById(usingMatId);
                //            var stockman = BLL.StoremanInfoService.GetStoremanByUserId(CurrUser.UserId);
                //            // 超过24小时默认退回焊条头
                //            if (recycleMat == null && type == "焊条")
                //            {
                //                Model.Weld_RecycleMat newRecycleMat = new Model.Weld_RecycleMat();
                //                newRecycleMat.ProjectId = mat.ProjectId;
                //                newRecycleMat.WeldId = mat.WeldId;
                //                newRecycleMat.UsingPlanId = mat.UsingPlanId;
                //                newRecycleMat.ReturnMatTop = Convert.ToInt32(mat.Amount);
                //                newRecycleMat.RecycleMan = mat.UsingMan;
                //                //if (this.drpStoreMan.SelectedValue != null && this.drpStoreMan.SelectedValue!=Const._Null)
                //                //{
                //                //    newRecycleMat.StockMan = this.drpStoreMan.SelectedValue;
                //                //}
                //                //else
                //                //{
                //                //    ShowNotify("请用保管员账号!");
                //                //    return;
                //                //}
                //                if (stockman != null)
                //                {
                //                    newRecycleMat.StockMan = stockman.StoremanId;
                //                }
                //                newRecycleMat.RecycleDate = usingDate.AddHours(8);
                //                newRecycleMat.Warrantybook = mat.Warrantybook;
                //                newRecycleMat.Number = mat.Number;
                //                newRecycleMat.UsePosition = mat.UsePosition;
                //                newRecycleMat.UsingMatId = usingMatId;
                //                newRecycleMat.IsStoreManConfirm = false;
                //                newRecycleMat.IsWelderConfirm = false;
                //                newRecycleMat.RecycleMatId = SQLHelper.GetNewID(typeof(Model.Weld_RecycleMat));
                //                BLL.RecycleMatService.AddRecycleMat(newRecycleMat);
                //                // 未按时退回焊条头
                //                BLL.UsingMatService.UsingMatIsOnTime(usingMatId, false);
                //            }
                //        }
                //    }
                //}
                #endregion
                BindGrid1(); // 未完结
                BindGrid2();//未领用领料计划
                BindGrid3();//焊材领用
                //BindGrid4();
            }
        }
        #endregion
        #region 绑定数据
        /// 
        /// 未完结
        /// 
        private void BindGrid1()
        {
            string strSql = @"SELECT m.UsingMatId, m.ProjectId,case when project.ProjectCode is not null then project.ProjectCode else usingPlan.ProjectId end as ProjectCode, m.UsePosition, m.WeldId,weld.ConsumablesName,
                                     weld.ConsumablesCode,weld.SteelFormat,m.Amount, m.UsingMan,welder.WED_Code, 
                                     m.UsingDate,r.RecycleAmount, r.ReturnMatTop AS RecycleTopAmount
                              FROM dbo.Weld_UsingMat m
                                   LEFT JOIN dbo.Weld_UsingPlan usingPlan ON usingPlan.UsingPlanId = m.UsingPlanId 
                                   LEFT JOIN dbo.Weld_RecycleMat r ON m.UsingMatId=r.UsingMatId
                                   LEFT JOIN dbo.Base_Consumables weld ON weld.ConsumablesId = m.WeldId
                                   LEFT JOIN dbo.Base_Project project ON project.ProjectId = m.ProjectId
                                   LEFT JOIN dbo.BS_Welder welder ON welder.WED_ID=m.UsingMan
                              WHERE  m.IsWelderConfirm=1 AND m.IsStoreManConfirm=1 
                                     AND (IsClose IS NULL OR IsClose=0) 
                                     AND usingPlan.UsingManOne=@WelderId";
            List listStr = new List();
            listStr.Add(new SqlParameter("@WelderId", this.WelderId));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            //tb = GetFilteredTable(Grid1.FilteredData, tb);
            //var table = this.GetSortTable(Grid1, tb); 
            Grid1.DataSource = tb;
            Grid1.DataBind();
        }
        /// 
        /// 绑定未领用领料计划
        /// 
        private void BindGrid2()
        {
            string strSql = @"SELECT UsingPlan.UsingPlanId, UsingPlan.WeldId, UsingPlan.ProjectId,UsingPlan.UsePosition, 
                                     UsingPlan.Amount, UsingPlan.InPutDate,UsingPlan.IsFinish,WeldInfo.ConsumablesCode,
                                     WeldInfo.ConsumablesName,WeldInfo.SteelFormat,case when project.ProjectCode is not null then project.ProjectCode else usingPlan.ProjectId end as ProjectCode,UsingPlan.OrderTime,
                                     (CASE WHEN UsingPlan.UsingManOne=@WelderId THEN Welder.WED_Code ELSE Welder2.WED_Code END) AS WED_Code
                              FROM dbo.Weld_UsingPlan AS UsingPlan
                                   LEFT JOIN Base_Consumables AS WeldInfo ON WeldInfo.ConsumablesId = UsingPlan.WeldId
                                   LEFT JOIN Base_Project AS Project ON Project.ProjectId = UsingPlan.ProjectId
                                   LEFT JOIN BS_Welder AS Welder ON Welder.WED_ID = UsingPlan.UsingManOne
                                   LEFT JOIN BS_Welder AS Welder2 ON Welder2.WED_ID = UsingPlan.UsingManTwo
                                   LEFT JOIN dbo.Weld_UsingMat usingMat ON usingMat.UsingPlanId = UsingPlan.UsingPlanId
                             WHERE (UsingPlan.IsCancel=0 OR UsingPlan.IsCancel IS NULL)
                                   AND UsingPlan.IsSubmit=1 AND convert(char(10),UsingPlan.OrderDate,120)=convert(char(10),GetDate(),120)
                                   AND usingMat.UsingMatId IS NULL  --一条计划只给领用一次
                                   --AND (UsingPlan.IsNeedConfirm IS NULL OR UsingPlan.IsNeedConfirm = 0) -- 不需要确认
                                   AND UsingPlan.UsingManOne=@WelderId";
            List listStr = new List();
            listStr.Add(new SqlParameter("@WelderId", this.WelderId));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid2.RecordCount = tb.Rows.Count;
            Grid2.DataSource = tb;
            Grid2.DataBind();
        }
        /// 
        /// 焊材领用
        /// 
        private void BindGrid3()
        {
            string strSql = @"SELECT m.UsingMatId, m.ProjectId,case when project.ProjectCode is not null then project.ProjectCode else usingPlan.ProjectId end as ProjectCode, m.UsePosition, m.WeldId, m.UsingPlanId,
                                     m.Amount,m.TwoAmount, m.UsingMan, m.UsingDate,m.StoreMan,m.Warrantybook,m.Number,m.StockInId,
                                    (CASE WHEN m.IsWelderConfirm=1 THEN '已确认' ELSE '未确认' END) AS WelderConfirm,
                                    (CASE WHEN m.IsStoreManConfirm=1 THEN '已确认' ELSE '未确认' END) AS StoreManConfirm
                              FROM dbo.Weld_UsingMat m
                                   LEFT JOIN Base_Project AS project ON project.ProjectId = m.ProjectId
                                   LEFT JOIN dbo.Weld_UsingPlan usingPlan ON usingPlan.UsingPlanId = m.UsingPlanId 
                              WHERE (m.IsWelderConfirm IS NULL OR m.IsWelderConfirm=0 OR
                                     m.IsStoreManConfirm IS NULL OR m.IsStoreManConfirm=0) AND 
                                     m.UsingMan=@WelderId ";
            List listStr = new List();
            listStr.Add(new SqlParameter("@WelderId", this.WelderId));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid3.RecordCount = tb.Rows.Count;
            //tb = GetFilteredTable(Grid3.FilteredData, tb);
            //var table = this.GetSortTable(Grid3, tb); 
            Grid3.DataSource = tb;
            Grid3.DataBind();
        }
        #endregion
        #region 一键退料
        protected void btnOnekeyReturnMat_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            var stockman = BLL.UserService.GetUserByUserId(CurrUser.UserId);
            string[] UsingMatIds = Grid1.SelectedRowIDArray;
            foreach (string usingMatId in UsingMatIds)
            {
                var mat = BLL.UsingMatService.GetUsingMatById(usingMatId);
                var recycleMat = BLL.RecycleMatService.GetRecycleMatByUsingMatId(usingMatId);
                var weld = BLL.Base_ConsumablesService.GetConsumablesByConsumablesId(mat.WeldId);
                var type = string.Empty;
                var dropValue = BLL.DropListService.HJGL_ConsumablesTypeList().FirstOrDefault(x => x.Value == weld.ConsumablesType);
                if (dropValue != null)
                {
                    type = dropValue.Text;
                }
                // 退回焊条头
                if (recycleMat == null)
                {
                    Model.Weld_RecycleMat newRecycleMat = new Model.Weld_RecycleMat();
                    newRecycleMat.ProjectId = mat.ProjectId;
                    newRecycleMat.WeldId = mat.WeldId;
                    newRecycleMat.UsingPlanId = mat.UsingPlanId;
                    newRecycleMat.RecycleAmount = 0;
                    if (type == "焊条")
                    {
                        decimal oneNum = mat.Amount != null ? mat.Amount.Value : 0;
                        decimal twoNum = mat.TwoAmount != null ? mat.TwoAmount.Value : 0;
                        newRecycleMat.ReturnMatTop = Convert.ToInt32(oneNum + twoNum);
                    }
                    newRecycleMat.RecycleMan = this.WelderId;
                    if (stockman != null)
                    {
                        newRecycleMat.StockMan = stockman.UserId;
                    }
                    newRecycleMat.RecycleDate = DateTime.Now;
                    newRecycleMat.Warrantybook = mat.Warrantybook;
                    newRecycleMat.Number = mat.Number;
                    newRecycleMat.UsePosition = mat.UsePosition;
                    newRecycleMat.UsingMatId = usingMatId;
                    newRecycleMat.IsStoreManConfirm = true;
                    newRecycleMat.IsWelderConfirm = true;
                    newRecycleMat.RecycleMatId = SQLHelper.GetNewID(typeof(Model.Weld_RecycleMat));
                    BLL.RecycleMatService.AddRecycleMat(newRecycleMat);
                    // 非违规
                    BLL.UsingMatService.UsingMatIsOnTime(usingMatId, false);
                    // 闭环
                    BLL.UsingMatService.UsingMatIsColse(usingMatId, true);
                }
            }
            BindGrid1();
            ShowNotify("焊材已退回仓库!");
        }
        #endregion
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(String.Format("window.location.href = 'WelderUsing.aspx';"));
        }
        #region 退料按钮事件
        /// 
        /// Grid1行点击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "ReturnMat")
            {
                //if (!string.IsNullOrEmpty(this.Grid1.SelectedRowID))
                //{
                string window = String.Format("RecycleMatEdit.aspx?usingMatId={0}&welderId={1}", e.RowID, this.WelderId, "编辑 - ");
                PageContext.RegisterStartupScript(Window4.GetSaveStateReference(hdItemsString.ClientID) + Window4.GetShowReference(window));
                //}
            }
        }
        /// 
        /// Grid2行点击事件
        /// 
        /// 
        /// 
        protected void Grid2_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "UsingWeld")
            {
                if (!string.IsNullOrEmpty(this.Grid2.SelectedRowID))
                {
                    bool isUsing = true;
                    var usingPlan = BLL.UsingPlanService.GetUsingPlanById(this.Grid2.SelectedRowID);
                    var weld = BLL.Base_ConsumablesService.GetConsumablesByConsumablesId(usingPlan.WeldId);
                    string weldTypeId = weld.ConsumablesType;
                    for (int i = 0; i < Grid1.Rows.Count; i++)
                    {
                        string usingMatId = Grid1.DataKeys[i][0].ToString();
                        var usingMat = BLL.UsingMatService.GetUsingMatById(usingMatId);
                        var uWeld = BLL.Base_ConsumablesService.GetConsumablesByConsumablesId(usingMat.WeldId);
                        if (uWeld != null && uWeld.ConsumablesType == weldTypeId)
                        {
                            isUsing = false;
                            break;
                        }
                    }
                    if (isUsing)
                    {
                        string window = String.Format("ShowStockIn.aspx?UsingPlanId={0}", this.Grid2.SelectedRowID, "编辑 - ");
                        PageContext.RegisterStartupScript(Window1.GetSaveStateReference(hdItemsString.ClientID) + Window1.GetShowReference(window));
                    }
                    else
                    {
                        ShowNotify("有未完结的领料计划,处理后才能领用!");
                    }
                }
            }
        }
        //protected void Grid4_RowCommand(object sender, GridCommandEventArgs e)
        //{
        //    if (e.CommandName == "WeldName")
        //    {
        //        if (!string.IsNullOrEmpty(this.Grid4.SelectedRowID))
        //        {
        //            var rec = BLL.RecycleMatService.GetRecycleMatById(this.Grid4.SelectedRowID);
        //            string window = String.Format("../Recycle/RecycleMatEdit.aspx?usingMatId={0}&welderId={1}", rec.UsingMatId, this.WelderId, "编辑 - ");
        //            PageContext.RegisterStartupScript(Window4.GetSaveStateReference(hdItemsString.ClientID) + Window4.GetShowReference(window));
        //        }
        //    }
        //}
        #endregion
        #region 弹出编辑窗口关闭事件
        /// 
        /// 弹出编辑窗体关闭事件
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            if (!string.IsNullOrEmpty(hdItemsString.Text))
            {
                string hdItems = hdItemsString.Text.Trim();
                // this.UsingPlanId = hdItems.Split('$')[0];
                //var plan = BLL.UsingPlanService.GetUsingPlanById(this.UsingPlanId);
                //decimal usedAmount = BLL.UsingMatService.GetUsingAmountSum(this.UsingPlanId);
                this.GetUsingMat(hdItems);
            }
        }
        protected void Window4_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid1(); // 未完结
            BindGrid2();//未领用领料计划
            BindGrid3();//焊材领用
        }
        /// 
        /// 领料
        /// 
        /// 
        private void GetUsingMat(string hdItems)
        {
            this.UsingPlanId = hdItems.Split('$')[0];
            string stockInItem = hdItems.Split('$')[1];
            //string oneAmount = hdItems.Split('|')[2];
            //string twoAmount = hdItems.Split('|')[3];
            //var stockIn = BLL.StockInService.GetStockInById(stockInId);
            if (!string.IsNullOrEmpty(stockInItem))
            {
                string[] stocks = stockInItem.Split('|');
                int recordNum = stocks.Length;
                List usingMats = new List();
                foreach (string stock in stocks)
                {
                    string keyId = stock.Split(',')[0];
                    string oneAmount = stock.Split(',')[1];
                    string twoAmount = stock.Split(',')[2];
                    var stockIn = BLL.StockInService.GetStockInById(keyId);
                    Model.Weld_UsingMat usingMat = new Model.Weld_UsingMat();
                    usingMat.UsingMatId = SQLHelper.GetNewID(typeof(Model.Weld_UsingMat));
                    usingMat.StockInId = keyId;
                    if (stockIn != null && !string.IsNullOrEmpty(this.UsingPlanId))
                    {
                        var usingPlan = BLL.UsingPlanService.GetUsingPlanById(this.UsingPlanId);
                        var project = BLL.ProjectService.GetProjectByProjectId(usingPlan.ProjectId);
                        usingMat.ProjectId = usingPlan.ProjectId;
                        usingMat.WeldId = stockIn.WeldId;
                        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", usingPlan.ProjectId, perfix);
                        }
                        usingMat.UsingPlanId = this.UsingPlanId;
                        if (usingPlan != null)
                        {
                            usingMat.UsePosition = usingPlan.UsePosition;
                            usingMat.Amount = Funs.GetNewDecimal(oneAmount);
                            usingMat.TwoAmount = Funs.GetNewDecimal(twoAmount);
                            //if (recordNum == 1)
                            //{
                            //    // 库存数量不足
                            //    if ((stockIn.Amount - (stockIn.UsingAmount??0)) < usingPlan.Amount)
                            //    {
                            //        usingMat.Amount = stockIn.Amount - (stockIn.UsingAmount??0);
                            //    }
                            //    else
                            //    {
                            //        usingMat.Amount = usingPlan.Amount;
                            //    }
                            //}
                            //else  //如不止一条记录,先用退回的材料
                            //{
                            //    // 库存数量不足
                            //    if (!string.IsNullOrEmpty(stockIn.Number))
                            //    {
                            //        if ((stockIn.Amount - (stockIn.UsingAmount ?? 0)) < usingPlan.Amount)
                            //        {
                            //            usingMat.Amount = stockIn.Amount - (stockIn.UsingAmount ?? 0);
                            //        }
                            //        else
                            //        {
                            //            usingMat.Amount = usingPlan.Amount;
                            //        }
                            //    }
                            //}
                        }
                    }
                    usingMat.UsingMan = this.WelderId;
                    usingMat.UsingDate = DateTime.Now;
                    usingMats.Add(usingMat);
                }
                this.Grid3.DataSource = usingMats;
                this.Grid3.DataBind();
            }
        }
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
        }
        protected void Window3_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid1();
            BindGrid3();
        }
        #endregion
        #region 保存
        /// 
        /// 保存按钮
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.UsingMatSave();
            BindGrid2();
            BindGrid3();
            //if (IsHaveStock())
            //{
            //    if (IsHavePlanAmount())
            //    {
            //        this.UsingMatSave();
            //        BindGrid2();
            //        BindGrid3();
            //    }
            //    else
            //    {
            //        PageContext.RegisterStartupScript(Confirm.GetShowReference("领用的量和计划的不一至,点击确定保存,点取消重新录入数量!",
            //                                          String.Empty,
            //                                          MessageBoxIcon.Question,
            //                    PageManager1.GetCustomEventReference(false, "Confirm_OK"), // 第一个参数 false 用来指定当前不是AJAX请求
            //                    PageManager1.GetCustomEventReference("Confirm_Cancel")));
            //    }
            //}
            //else
            //{
            //    ShowNotify("库存不足,或者领用量不能为空,请重新录入领用数量!");
            //    return;
            //}
        }
        /// 
        /// 点口确定对话框
        /// 
        /// 
        /// 
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                this.UsingMatSave();
                BindGrid2();
                BindGrid3();
            }
            else if (e.EventArgument == "Confirm_Cancel")
            {
                if (!string.IsNullOrEmpty(hdItemsString.Text))
                {
                    string hdItems = hdItemsString.Text.Trim();
                    this.GetUsingMat(hdItems);
                }
                // AJAX回发
                ShowNotify("取消重新录入数量!");
            }
        }
        /// 
        /// 是否有库存
        /// 
        /// 
        private bool IsHaveStock()
        {
            int i = 0;
            bool haveStock = true;
            if (Grid3.GetMergedData().Count > 0)
            {
                JArray mergedData = Grid3.GetMergedData();
                foreach (JObject mergedRow in mergedData)
                {
                    JObject values = mergedRow.Value("values");
                    decimal amount = 0;
                    if (string.IsNullOrEmpty(values.Value("Amount")))
                    {
                        haveStock = false;
                        break;
                    }
                    else
                    {
                        amount = values.Value("Amount");
                    }
                    string stockInId = values.Value("StockInId");
                    string usingMatId = Grid3.DataKeys[i][0].ToString();
                    var usingMat = BLL.UsingMatService.GetUsingMatById(usingMatId);
                    var stock = BLL.StockInService.GetStockInById(stockInId);
                    decimal? oldAmount = 0;
                    if (usingMat != null)
                    {
                        oldAmount = usingMat.Amount;
                    }
                    decimal? stockAmount = stock.Amount - (stock.UsingAmount ?? 0);
                    if (amount > stockAmount + oldAmount)
                    {
                        haveStock = false;
                        break;
                    }
                    i++;
                }
            }
            return haveStock;
        }
        /// 
        /// 领料是否和计划一至
        /// 
        /// 
        private bool IsHavePlanAmount()
        {
            decimal usingAmount = 0;
            bool havePlanAmount = true;
            var plan = BLL.UsingPlanService.GetUsingPlanById(this.UsingPlanId);
            if (plan != null)
            {
                decimal planAmount = plan.Amount ?? 0;
                if (Grid3.GetMergedData().Count > 0)
                {
                    JArray mergedData = Grid3.GetMergedData();
                    foreach (JObject mergedRow in mergedData)
                    {
                        JObject values = mergedRow.Value("values");
                        if (!string.IsNullOrEmpty(values.Value("Amount")))
                        {
                            usingAmount = usingAmount + values.Value("Amount");
                        }
                    }
                }
                if (usingAmount != planAmount)
                {
                    havePlanAmount = false;
                }
            }
            return havePlanAmount;
        }
        private void UsingMatSave()
        {
            int i = 0;
            if (Grid3.GetMergedData().Count > 0)
            {
                JArray mergedData = Grid3.GetMergedData();
                foreach (JObject mergedRow in mergedData)
                {
                    JObject values = mergedRow.Value("values");
                    Model.Weld_UsingMat newUsingMat = new Model.Weld_UsingMat();
                    string usingMatId = Grid3.DataKeys[i][0].ToString();
                    string projectId = Grid3.DataKeys[i][1].ToString();
                    newUsingMat.ProjectId = projectId;
                    newUsingMat.Amount = values.Value("Amount");
                    newUsingMat.TwoAmount = values.Value("TwoAmount");
                    newUsingMat.UsingMan = this.WelderId;
                    newUsingMat.UsingDate = values.Value("UsingDate");
                    newUsingMat.Warrantybook = values.Value("Warrantybook");
                    newUsingMat.Number = values.Value("Number");
                    newUsingMat.StockInId = values.Value("StockInId");
                    newUsingMat.UsingMatId = usingMatId;
                    var usingMat = BLL.UsingMatService.GetUsingMatById(usingMatId);
                    decimal? oldAmount = 0;
                    //decimal? planAmount = 0;
                    decimal? twoAmount = 0;
                    if (usingMat != null)
                    {
                        this.UsingPlanId = usingMat.UsingPlanId;
                        oldAmount = usingMat.Amount;
                        twoAmount = usingMat.TwoAmount;
                    }
                    var usingPlan = BLL.UsingPlanService.GetUsingPlanById(this.UsingPlanId);
                    if (usingPlan != null)
                    {
                        newUsingMat.UsingPlanId = this.UsingPlanId;
                        if (!string.IsNullOrEmpty(usingPlan.UsePosition))
                        {
                            newUsingMat.UsePosition = usingPlan.UsePosition;
                        }
                        if (!string.IsNullOrEmpty(usingPlan.WeldId))
                        {
                            newUsingMat.WeldId = usingPlan.WeldId;
                        }
                        //decimal? usingAmount = BLL.UsingMatService.GetUsingAmountSum(this.UsingPlanId) + newUsingMat.Amount - oldAmount;
                        //planAmount = usingPlan.Amount.HasValue ? usingPlan.Amount.Value : 0;//计划值
                    }
                    //// 焊条的领用不能超过计划的量
                    //var weldInfo = BLL.WeldInfoService.GetWeldInfoById(newUsingMat.WeldId);
                    //var weldType = BLL.WeldTypeService.GetWeldTypeById(weldInfo.WeldTypeId);
                    //if (weldType != null && weldType.WeldTypeName.Contains("焊条"))
                    //{
                    //    if (newUsingMat.Amount > planAmount)
                    //    {
                    //        ShowNotify("焊条的领用不能超过计划的量!");
                    //        return;
                    //    }
                    //}
                    System.Web.UI.WebControls.DropDownList drpStoreMan = (System.Web.UI.WebControls.DropDownList)Grid3.Rows[i].FindControl("drpStoreMan");
                    if (!string.IsNullOrEmpty(drpStoreMan.SelectedValue) && drpStoreMan.SelectedValue != "0")
                    {
                        newUsingMat.StoreMan = drpStoreMan.SelectedValue;
                    }
                    else
                    {
                        ShowNotify("请选择保管员!");
                        return;
                    }
                    if (newUsingMat.Amount + newUsingMat.TwoAmount > 0)
                    {
                        if (usingMat == null)
                        {
                            BLL.UsingMatService.AddUsingMat(newUsingMat);
                            // 修改库存已使用的数量
                            BLL.StockInService.UpdateStockInUsingAmount(newUsingMat.StockInId, newUsingMat.Amount, newUsingMat.TwoAmount);
                        }
                        else
                        {
                            if (usingMat.IsStoreManConfirm == true || usingMat.IsWelderConfirm == true)
                            {
                                ShowNotify("焊工已确认,不能修改!");
                                return;
                            }
                            else
                            {
                                BLL.UsingMatService.UpdateUsingMat(newUsingMat);
                                // 修改库存已使用的数量
                                decimal? realUsingAmount = newUsingMat.Amount - oldAmount;
                                decimal? realTwoAmount = twoAmount - newUsingMat.TwoAmount;
                                BLL.StockInService.UpdateStockInUsingAmount(newUsingMat.StockInId, realUsingAmount, realTwoAmount);
                            }
                        }
                    }
                    else
                    {
                        ShowNotify("请填写领用数量!");
                    }
                    i++;
                }
            }
            ShowNotify("数据保存成功!(表格数据已重新绑定)");
        }
        #endregion
        #region 双击领料确认
        protected void Grid3_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            string weldMatId = e.RowID;
            var mat = BLL.UsingMatService.GetUsingMatById(weldMatId);
            if (mat != null)
            {
                // FingerOrFace=2 表示不通过人脸和指纹
                string window = String.Format("UsingMatCheck.aspx?keyId={0}&grid=1&isFinger=1&FingerOrFace={1}", weldMatId, "2", "编辑 - ");
                PageContext.RegisterStartupScript(Window3.GetSaveStateReference(this.WelderId)
                  + Window3.GetShowReference(window));
            }
            else
            {
                ShowNotify("请先保存记录!");
            }
        }
        /// 
        /// 双击退料确认
        /// 
        /// 
        /// 
        //protected void Grid4_RowDoubleClick(object sender, GridRowClickEventArgs e)
        //{
        //    string weldMatId = e.RowID;
        //    var mat = BLL.RecycleMatService.GetRecycleMatById(weldMatId);
        //    if (mat != null)
        //    {
        //        // FingerOrFace=2 表示不通过人脸和指纹
        //        string window = String.Format("UsingMatCheck.aspx?keyId={0}&grid=2&isFinger=1&FingerOrFace={1}", weldMatId, "2", "编辑 - ");
        //        PageContext.RegisterStartupScript(Window3.GetSaveStateReference(this.WelderId)
        //          + Window3.GetShowReference(window));
        //    }
        //    else
        //    {
        //        ShowNotify("请先保存记录!");
        //    }
        //}
        #endregion
        #region  行绑定获取保管员
        /// 
        /// 行绑定获取保管员
        /// 
        /// 
        /// 
        protected void Grid3_RowDataBound(object sender, GridRowEventArgs e)
        {
            System.Web.UI.WebControls.DropDownList drpStoreMan = (System.Web.UI.WebControls.DropDownList)Grid3.Rows[e.RowIndex].FindControl("drpStoreMan");
            Funs.PleaseSelect(drpStoreMan);
            drpStoreMan.Items.AddRange(BLL.UserService.GetProjectUserListItemByProjectId(this.CurrUser.LoginProjectId));
            var usingMat = BLL.UsingMatService.GetUsingMatById(e.RowID);
            if (usingMat != null)
            {
                if (!string.IsNullOrEmpty(usingMat.StoreMan))
                {
                    drpStoreMan.SelectedValue = usingMat.StoreMan;
                }
            }
            else
            {
                var curUser = BLL.UserService.GetUserByUserId(this.CurrUser.UserId);
                if (curUser != null)
                {
                    drpStoreMan.SelectedValue = curUser.UserId;
                }
            }
        }
        #endregion
        #region 打印
        /// 
        /// 打印
        /// 
        /// 
        /// 
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            string weldMatId = this.Grid3.SelectedRowID;
            if (!string.IsNullOrEmpty(weldMatId))
            {
                string weldSpec = string.Empty;//规格
                string weldName = string.Empty;//材质牌号
                string welderName = string.Empty;//焊工姓名
                string number = string.Empty;//流水号
                string storeName = string.Empty;//保管员
                string usingDate = string.Empty;//时间
                var material = BLL.UsingMatService.GetUsingMatById(weldMatId);
                if (material != null)
                {
                    if (!string.IsNullOrEmpty(material.WeldId))
                    {
                        var weldInfo = Base_ConsumablesService.GetConsumablesByConsumablesId(material.WeldId);
                        if (weldInfo != null)
                        {
                            weldSpec = weldInfo.SteelFormat;
                            weldName = weldInfo.ConsumablesCode;
                        }
                    }
                    if (!string.IsNullOrEmpty(material.UsingMan))
                    {
                        var welder = WelderService.GetWelderById(material.UsingMan);
                        if (welder != null)
                        {
                            welderName = welder.WED_Name + "(" + welder.WED_Code + ")";
                        }
                    }
                    number = material.Number;
                    if (!string.IsNullOrEmpty(material.StoreMan))
                    {
                        var store = BLL.UserService.GetUserByUserId(material.StoreMan);
                        if (store != null)
                        {
                            storeName = store.UserName;
                        }
                    }
                    usingDate = material.UsingDate.Value.ToShortDateString() + " " + material.UsingDate.Value.ToShortTimeString();
                }
                Dictionary keyValuePairs = new Dictionary();
                keyValuePairs.Add("WeldSpec", weldSpec);
                keyValuePairs.Add("WeldName", weldName);
                keyValuePairs.Add("WelderName", welderName);
                keyValuePairs.Add("Number", number);
                keyValuePairs.Add("StoreName", storeName);
                keyValuePairs.Add("UsingDate", usingDate);
                BLL.Common.FastReportService.ResetData();
                BLL.Common.FastReportService.AddFastreportParameter(keyValuePairs);
                string initTemplatePath = "";
                string rootPath = Server.MapPath("~/");
                initTemplatePath = "File\\Fastreport\\材料标签.frx";
                if (File.Exists(rootPath + initTemplatePath))
                {
                    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../TrustManage/Fastreport.aspx?ReportPath={0}", rootPath + initTemplatePath)));
                }
                //string reportId = BLL.Const.CLGL_MaterialLabelReportId;
                //PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../../Common/ReportPrint/ExReportPrint.aspx?ispop=1&reportId={0}&replaceParameter={1}&varValue={2}&projectId=0", reportId, weldMatId, "", "打印 - ")));
            }
            else
            {
                ShowNotify("请选中要打印的材料!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 不用了
        /// 
        /// 打印领料标签
        /// 
        /// 
        /// 
        //protected void btnPrint_Click(object sender, EventArgs e)
        //{
        //    if (!string.IsNullOrEmpty(this.Grid3.SelectedRowID))
        //    {
        //        string reportId = BLL.Const.CLGL_MaterialLabelReportId;
        //        PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../../Common/ReportPrint/ExReportPrint.aspx?ispop=1&reportId={0}&replaceParameter={1}&varValue={2}&projectId=0", reportId, this.Grid3.SelectedRowID, string.Empty, "打印 - ")));
        //    }
        //    else
        //    {
        //        ShowNotify("请选中要打印的领料标签");
        //    }
        //}
        #endregion
        #region 格式化字符串
        protected string ConvertIsReview(object stockInId)
        {
            string reStr = "否";
            if (stockInId != null)
            {
                var stockIn = BLL.StockInService.GetStockInById(stockInId.ToString());
                if (stockIn != null && stockIn.ReviewDate != null)
                {
                    reStr = "是";
                }
            }
            return reStr;
        }
        /// 
        /// 根据ID获取领取人姓名
        /// 
        /// 
        /// 
        protected string ConvertString(object usingMan)
        {
            if (usingMan != null)
            {
                var person = BLL.WelderService.GetWelderById(usingMan.ToString());
                if (person != null)
                {
                    return person.WED_Name;
                }
            }
            return null;
        }
        protected string ConvertWeldName(object weldId)
        {
            if (weldId != null)
            {
                var weldInfo = BLL.Base_ConsumablesService.GetConsumablesByConsumablesId(weldId.ToString());
                if (weldInfo != null)
                {
                    return weldInfo.ConsumablesName;
                }
            }
            return null;
        }
        protected string ConvertWeldCode(object weldId)
        {
            if (weldId != null)
            {
                var weldInfo = BLL.Base_ConsumablesService.GetConsumablesByConsumablesId(weldId.ToString());
                if (weldInfo != null)
                {
                    return weldInfo.ConsumablesCode;
                }
            }
            return null;
        }
        /// 
        /// 
        /// 
        /// 
        /// 时间戳,单位为毫秒(0),秒(1),默认毫秒
        /// 
        private DateTime? ConvertUnixTimeStampToDateTime(string unixTimeStamp)
        {
            if (!string.IsNullOrEmpty(unixTimeStamp))
            {
                double timeStamp = double.Parse(unixTimeStamp);
                //create a new datetime value based on the unix epoch
                DateTime converted = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                //add the timestamp to the value
                //DateTime newdatetime = (unit == 1 ? converted.AddSeconds(timeStamp) : converted.AddMilliseconds(timeStamp));
                DateTime newdatetime = converted.AddMilliseconds(timeStamp);
                //convert to localtime
                return newdatetime.ToLocalTime();
            }
            else
            {
                return null;
            }
        }
        #endregion
    }
}