using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FineUIPro.Web.TestRun.DriverGoods
{
    public partial class GoodsBuyEdit : PageBase
    {
        #region 加载
        /// 
        /// 页面加载
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string id = Request.Params["GoodsBuyId"];
                if (!string.IsNullOrEmpty(id))
                {
                    Model.DriverGoods_GoodsBuy data = BLL.GoodsBuyService.GetGoodsBuyById(id);
                    if (data != null)
                    {
                        this.hdId.Text = id;
                        this.txtCode.Text = data.Code;
                        if (!string.IsNullOrEmpty(data.BuyCode))
                        {
                            this.hdBuyCode.Text = data.BuyCode;
                            this.txtBuyName.Text = GoodsBuyService.ConvertBugType(data.BuyCode);
                        }
                        this.txtUnitCode.Text = data.UnitCode;
                        var list = from x in Funs.DB.View_DriverGoods_GoodsBuyItem where x.GoodsBuyId == id orderby x.Code select x;
                        this.Grid1.DataSource = list;
                        this.Grid1.DataBind();
                        if (list.Count() > 0)
                        {
                            var ids = list.Select(x => x.GoodsModelId).ToArray();
                            this.hdItemsString.Text = Funs.GetStringByArray(ids);
                        }
                    }
                }
                else
                {
                    this.hdBuyCode.Text = Request.Params["BuyCode"];
                    this.txtBuyName.Text = GoodsBuyService.ConvertBugType(this.hdBuyCode.Text);
                }
            }
        }
        #endregion
        #region 附件上传
        /// 
        /// 附件上传
        /// 
        /// 
        /// 
        protected void btnAttach_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.hdId.Text))   //新增记录
            {
                this.hdId.Text = SQLHelper.GetNewID(typeof(Model.DriverGoods_GoodsBuy));
            }
            PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?type=0&toKeyId={0}&path=FileUpload/TestRun/DriverGoods/GoodsBuy&menuId={1}", this.hdId.Text, BLL.Const.GoodsBuyMenuId)));
        }
        #endregion
        #region 保存
        /// 
        /// 保存按钮
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string id = Request.Params["GoodsBuyId"];
            Model.DriverGoods_GoodsBuy newData = new Model.DriverGoods_GoodsBuy();
            newData.Code = this.txtCode.Text.Trim();
            newData.BuyName = this.txtBuyName.Text.Trim();
            newData.BuyCode = this.hdBuyCode.Text.Trim();
            newData.UnitCode = this.txtUnitCode.Text.Trim();
            newData.CompileMan = this.CurrUser.UserId;
            newData.ApprovalDate = DateTime.Now;
            newData.ProjectId = this.CurrUser.LoginProjectId;
            if (!string.IsNullOrEmpty(id))
            {
                newData.GoodsBuyId = id;
                BLL.GoodsBuyService.UpdateGoodsBuy(newData);
            }
            else
            {
                if (!string.IsNullOrEmpty(this.hdId.Text))
                {
                    newData.GoodsBuyId = this.hdId.Text.Trim();
                }
                else
                {
                    newData.GoodsBuyId = SQLHelper.GetNewID(typeof(Model.DriverGoods_GoodsBuy));
                    this.hdId.Text = newData.GoodsBuyId;
                }
                BLL.GoodsBuyService.AddGoodsBuy(newData);
            }
            BLL.GoodsBuyItemService.DeleteGoodsBuyItemByGoodsBuyId(newData.GoodsBuyId);
            var details = jerqueSaveList();
            foreach (var detail in details)
            {
                Model.DriverGoods_GoodsBuyItem item = new Model.DriverGoods_GoodsBuyItem();
                item.GoodsBuyItemId = SQLHelper.GetNewID();
                item.GoodsBuyId = newData.GoodsBuyId;
                item.GoodsModelId = detail.GoodsModelId;
                item.Num = detail.Num;
                item.RequiredTime = detail.RequiredTime;
                BLL.GoodsBuyItemService.AddGoodsBuyItem(item);
            }
            ShowNotify("保存成功!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion
        #region 搜索
        /// 
        /// 搜索
        /// 
        /// 
        /// 
        protected void btnNew_Click(object sender, EventArgs e)
        {
            string window = String.Format("ShowGoodsModel.aspx?Ids={0}", hdItemsString.Text, "查找 - ");
            PageContext.RegisterStartupScript(Window1.GetSaveStateReference(hdItemsString.ClientID) + Window1.GetShowReference(window));
        }
        #endregion
        #region  保存Grid集合
        /// 
        /// 检查并保存集合
        /// 
        private List jerqueSaveList()
        {
            var models = from x in Funs.DB.DriverGoods_GoodsModel where x.ProjectId == this.CurrUser.LoginProjectId select x;
            List details = new List();
            foreach (JObject mergedRow in Grid1.GetMergedData())
            {
                JObject values = mergedRow.Value("values");
                int i = mergedRow.Value("index");
                Model.View_DriverGoods_GoodsBuyItem detail = new Model.View_DriverGoods_GoodsBuyItem();
                detail.GoodsModelId = this.Grid1.Rows[i].RowID;
                Model.DriverGoods_GoodsModel model = models.FirstOrDefault(x => x.GoodsModelId == detail.GoodsModelId);
                detail.Purpose = model.Purpose;
                detail.Description = model.Description;
                detail.Attachment = model.Attachment;
                detail.Remark = model.Remark;
                detail.Num = values.Value("Num");
                string requiredTime = values.Value("RequiredTime");
                if (!string.IsNullOrEmpty(requiredTime))
                {
                    detail.RequiredTime = Convert.ToDateTime(requiredTime);
                }
                details.Add(detail);
            }
            return details;
        }
        #endregion
        #region 关闭弹出窗口
        /// 
        /// 关闭弹出窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            if (!string.IsNullOrEmpty(hdItemsString.Text))
            {
                string[] ids = hdItemsString.Text.Split(',');
                var details = jerqueSaveList();
                var models = from x in Funs.DB.DriverGoods_GoodsModel where x.ProjectId == this.CurrUser.LoginProjectId select x;
                foreach (var id in ids)
                {
                    var oldDetail = details.FirstOrDefault(x => x.GoodsModelId == id);
                    if (oldDetail == null)   //添加集合没有的新纪录
                    {
                        Model.DriverGoods_GoodsModel model = models.FirstOrDefault(x => x.GoodsModelId == id);
                        if (model != null)
                        {
                            Model.View_DriverGoods_GoodsBuyItem detail = new Model.View_DriverGoods_GoodsBuyItem();
                            detail.GoodsModelId = model.GoodsModelId;
                            detail.Purpose = model.Purpose;
                            detail.Description = model.Description;
                            detail.Quantity = model.Quantity;
                            detail.Attachment = model.Attachment;
                            detail.Remark = model.Remark;
                            details.Add(detail);
                        }
                    }
                }
                this.Grid1.DataSource = details;
                this.Grid1.DataBind();
            }
        }
        #endregion
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string itemId = Grid1.DataKeys[e.RowIndex][0].ToString();
            List details = jerqueSaveList();
            if (e.CommandName == "delete")
            {
                foreach (Model.View_DriverGoods_GoodsBuyItem detail in details)
                {
                    if (detail.GoodsModelId == itemId)
                    {
                        details.Remove(detail);
                        break;
                    }
                }
                Grid1.DataSource = details;
                Grid1.DataBind();
            }
        }
    }
}