using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web.UI;
using BLL;
using Newtonsoft.Json.Linq; 
namespace FineUIPro.Web.HJGL.MaterialManage
{
    public partial class MaterialApplyEdit : PageBase
    {
        #region 定义变量
        public string ApplyID
        {
            get
            {
                return (string)ViewState["ApplyID"];
            }
            set
            {
                ViewState["ApplyID"] = value;
            }
        }
        public string State
        {
            get
            {
                return (string)ViewState["State"];
            }
            set
            {
                ViewState["State"] = value;
            }
        }
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 请购单明细
        /// 
        public   List applyItems = new List();
        /// 
        /// 错误集合
        /// 
        public static string errorInfos = string.Empty;
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                State = "1";
                this.txtProjectName.Text = ProjectService.GetProjectNameByProjectId(CurrUser.LoginProjectId);
                UnitService.InitUnitByProjectIdUnitTypeDropDownList(this.dpApplyUnit, this.CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2, false);
                if (CurrUser.UnitId != Const.UnitId_TCC && CurrUser.UserId != Const.hfnbdId)
                {
                    this.dpApplyUnit.SelectedValue = CurrUser.UnitId;
                    this.dpApplyUnit.Enabled = false;
                }
                if (applyItems != null)
                {
                    applyItems.Clear();
                }
                errorInfos = string.Empty;
                //下一步审核人
                var db = Funs.DB;
                var userList = from x in db.Sys_User
                                join y in db.Project_ProjectUnit
                                on x.UnitId equals y.UnitId
                                join p in db.Project_ProjectUser
                                on x.UserId equals p.UserId
                                where y.UnitId == Const.UnitId_TCC && p.ProjectId == CurrUser.LoginProjectId && y.ProjectId == CurrUser.LoginProjectId
                                where p.RoleId.Contains(Const.ZBCNEngineer)
                                select new { UserId = x.UserId, UserName = x.UserName };
                drpHandleMan.DataValueField = "UserId";
                drpHandleMan.DataTextField = "UserName";
                this.drpHandleMan.DataSource = userList.ToList();
                this.drpHandleMan.DataBind();
                ListItem[] lis = new ListItem[1];
                lis[0] = new ListItem("总包负责人审核","2");
                drpHandleType.DataValueField = "Value";
                drpHandleType.DataTextField = "Text";
                this.drpHandleType.DataSource = lis;
                this.drpHandleType.DataBind();
                JObject defaultObj = new JObject();
                defaultObj.Add("ID", Guid.NewGuid().ToString());
                defaultObj.Add("MaterialCode", "");
                defaultObj.Add("LocNum", "");
                defaultObj.Add("Des", ""); 
                defaultObj.Add("Unit", "");
                defaultObj.Add("Amount_Design", "");
                defaultObj.Add("Amount_Re", "");
                defaultObj.Add("Amount_This", "");
                defaultObj.Add("Amount_Total", "");
                defaultObj.Add("Size1", "");
                defaultObj.Add("Size2", "");
                btnNew.OnClientClick = Grid1.GetAddNewRecordReference(defaultObj, false);
                // 删除选中行按钮
                btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("请至少选择一项!") + GetDeleteScript();
                ApplyID = Request.Params["Id"];
                if (!string.IsNullOrEmpty(ApplyID))
                {
                    var materialApply = BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.getMaterialApply(ApplyID);
                    if (materialApply != null)
                    {
                        this.btnSubmit.Hidden = true;
                        this.btnSave1.Hidden = true;
                        this.dpApplyUnit.SelectedValue = materialApply.ApplyUnitId;
                        this.txtApplyName.Text = materialApply.ApplyName;
                        this.txtApplyDes.Text = materialApply.ApplyDes;
                        this.txtApplyCode.Text = materialApply.ApplyCode;
                        State = materialApply.State;
                        if (materialApply.ApplyDate.HasValue)
                        {
                            this.dpApplyDate.Text = materialApply.ApplyDate.Value.ToString("yyyy-MM-dd");
                        }
                        var currentApprove = BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.getCurrMaterialApplyApprove(ApplyID);
                        //编辑 或者 重新编辑  按钮可见
                        if (CurrUser.UserId == materialApply.CreateMan && (materialApply.State == BLL.Const.MaterialApply_ReCompile || materialApply.State == BLL.Const.MaterialApply_Compile))
                        {
                            this.btnSubmit.Hidden = false;
                            this.btnSave1.Hidden = false;
                        }else    if (materialApply.State == BLL.Const.MaterialApply_Audit1 && currentApprove != null)
                        {
                            this.txtApplyName.Enabled = false;
                            this.dpApplyUnit.Enabled = false;
                            this.txtApplyCode.Enabled = false;
                            this.dpApplyDate.Enabled = false;
                            this.txtApplyDes.Enabled = false;
                            this.FrUpload.Hidden = true;
                            this.Toolbar1.Hidden = true;
                            Grid1.AllowCellEditing = false;
                            Grid1.EnableCheckBoxSelect = false;
                            this.FrApprove1.Hidden = false;
                            this.FrYesOrNo.Hidden = false;
                            this.frStap.Hidden = true;
                            this.btnSubmit.Hidden = false;
                            this.btnSave1.Hidden = false;
                        }
                        else if (materialApply.State == BLL.Const.MaterialApply_Complete)
                        {
                            this.dpApplyUnit.Enabled = false;
                            this.txtApplyName.Enabled = false;
                            this.txtApplyCode.Enabled = false;
                            this.dpApplyDate.Enabled = false;
                            this.txtApplyDes.Enabled = false;
                            this.FrUpload.Hidden = true;
                            this.Toolbar1.Hidden = true;
                            Grid1.AllowCellEditing = false;
                            Grid1.EnableCheckBoxSelect = false;
                            this.frStap.Hidden = true;
                            this.btnSubmit.Hidden = true;
                            this.btnSave1.Hidden = true;
                        }
                        else
                        {
                            this.dpApplyUnit.Enabled = false;
                            this.txtApplyName.Enabled = false;
                            this.txtApplyCode.Enabled = false;
                            this.dpApplyDate.Enabled = false;
                            this.txtApplyDes.Enabled = false;
                            this.FrUpload.Hidden = true;
                            this.Toolbar1.Hidden = true;
                            Grid1.AllowCellEditing = false;
                            Grid1.EnableCheckBoxSelect = false;
                            this.frStap.Hidden = true;
                            this.btnSubmit.Hidden = true;
                            this.btnSave1.Hidden = true;
                        }
                    }
                    applyItems.AddRange(BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.getMaterialApplyItem(ApplyID));
                    Grid1.DataSource = applyItems;
                    Grid1.DataBind();
                    var approveItems = BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.getMaterialApplyApproveList(ApplyID);
                    gvApprove.DataSource = approveItems;
                    gvApprove.DataBind();
                }
            }
        }
        #endregion
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                 Grid1.Rows.RemoveAt(e.RowIndex);  
 
            }
        }
        // 删除选中行的脚本
        private string GetDeleteScript()
        {
            return Confirm.GetShowReference("删除选中行?", String.Empty, MessageBoxIcon.Question, Grid1.GetDeleteSelectedRowsReference(), String.Empty);
        }
        #region 审核
        /// 
        /// 审核
        /// 
        /// 
        /// 
        protected void btnAudit_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.fuAttachUrl.HasFile == false)
                {
                    ShowNotify("请您选择Excel文件!", MessageBoxIcon.Warning);
                    return;
                }
                string IsXls = Path.GetExtension(this.fuAttachUrl.FileName).ToString().Trim().ToLower();
                if (IsXls != ".xls")
                {
                    ShowNotify("只可以选择Excel文件!", MessageBoxIcon.Warning);
                    return;
                }
                if (applyItems != null)
                {
                    applyItems.Clear();
                }
                if (!string.IsNullOrEmpty(errorInfos))
                {
                    errorInfos = string.Empty;
                }
                string rootPath = Server.MapPath("~/");
                string initFullPath = rootPath + initPath;
                if (!Directory.Exists(initFullPath))
                {
                    Directory.CreateDirectory(initFullPath);
                }
                this.hdFileName.Text = BLL.Funs.GetNewFileName() + IsXls;
                string filePath = initFullPath + this.hdFileName.Text;
                this.fuAttachUrl.PostedFile.SaveAs(filePath);
                //PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("PersonDataAudit.aspx?FileName={0}&ProjectId={1}", this.hdFileName.Text, Request.Params["ProjectId"], "审核 - ")));
                ImportXlsToData(rootPath + initPath + this.hdFileName.Text);
            }
            catch (Exception ex)
            {
                ShowNotify("'" + ex.Message + "'", MessageBoxIcon.Warning);
            }
        }
        #region 读Excel提取数据
        /// 
        /// 从Excel提取数据--》Dataset
        /// 
        /// Excel文件路径名
        private void ImportXlsToData(string fileName)
        {
            try
            {
                applyItems.Clear();
                string oleDBConnString = String.Empty;
                oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
                oleDBConnString += "Data Source=";
                oleDBConnString += fileName;
                oleDBConnString += ";Extended Properties=Excel 8.0;";
                OleDbConnection oleDBConn = null;
                OleDbDataAdapter oleAdMaster = null;
                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();
                oleDBConn = new OleDbConnection(oleDBConnString);
                oleDBConn.Open();
                m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (m_tableName != null && m_tableName.Rows.Count > 0)
                {
                    m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString().Trim();
                }
                string sqlMaster;
                sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";
                oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();
                AddDatasetToSQL(ds.Tables[0]);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 将Dataset的数据导入数据库
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集行数
        /// 
        private bool AddDatasetToSQL(DataTable pds)
        {
            string result = string.Empty;
            int ic, ir;
            ic = pds.Columns.Count;
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                var questionType = from x in Funs.DB.Base_QualityQuestionType select x;
                for (int i = 0; i < ir; i++)
                {
                    Model.HJGL_Material_Apply_Item item = new Model.HJGL_Material_Apply_Item
                    {
                        ID = Guid.NewGuid().ToString() ,
                        MaterialCode = pds.Rows[i][0].ToString().Trim(),
                        LocNum = pds.Rows[i][1].ToString().Trim(),
                        Des = pds.Rows[i][2].ToString().Trim(),
                        Unit = pds.Rows[i][3].ToString().Trim(),
                        Amount_Design = pds.Rows[i][4].ToString().Trim(),
                        Amount_Re = pds.Rows[i][5].ToString().Trim(),
                        Amount_This = pds.Rows[i][6].ToString().Trim(),
                        Amount_Total = pds.Rows[i][7].ToString().Trim(),
                        Size1 = pds.Rows[i][8].ToString().Trim(),
                        Size2 = pds.Rows[i][9].ToString().Trim()
                    };
                     
                    ///加入用户视图
                    applyItems.Add(item);
                }
                if (!string.IsNullOrEmpty(result))
                {
                    applyItems.Clear();
                    result = result.Substring(0, result.LastIndexOf("|"));
                    errorInfos = result;
                    Alert alert = new Alert
                    {
                        Message = result,
                        Target = Target.Self
                    };
                    alert.Show();
                }
                else
                {
                    errorInfos = string.Empty;
                    if (applyItems.Count > 0)
                    {
                        this.Grid1.Hidden = false;
                        this.Grid1.DataSource = applyItems;
                        this.Grid1.DataBind(); 
                    }
                    else
                    {
                        Alert.ShowInTop("导入数据为空!", MessageBoxIcon.Warning);
                    }
                }
            }
            else
            {
                Alert.ShowInTop("导入数据为空!", MessageBoxIcon.Warning);
            }
            return true;
        }
        #endregion
        #endregion
        #region 保存
        /// 
        /// 保存
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Model.HJGL_Material_Apply applyNew= new Model.HJGL_Material_Apply();
            applyNew.ProjectId = this.CurrUser.LoginProjectId;
            if (!string.IsNullOrEmpty(ApplyID))
            {
                applyNew.ID = ApplyID;
            }
            else
            { 
                applyNew.ID = Guid.NewGuid().ToString(); 
            }
            applyNew.CreateDate = DateTime.Now;
            applyNew.CreateMan = CurrUser.UserId;
            applyNew.ApplyUnitId = this.dpApplyUnit.SelectedValue;
            applyNew.ApplyName = this.txtApplyName.Text;
            applyNew.ApplyDes = this.txtApplyDes.Text;
            applyNew.ApplyCode = this.txtApplyCode.Text;
            applyNew.State = "1";
            applyNew.ApplyDate = Convert.ToDateTime(this.dpApplyDate.Text);
            if (string.IsNullOrEmpty(ApplyID))
            {
                BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.AddMaterialApply(applyNew);
            }
            else
            {
                BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.UpdateMaterialApply(applyNew);
            }
            int a = applyItems.Count();
             
            List applyItem = new List();
            if (Grid1.GetMergedData().Count > 0)
            {
                foreach (JObject mergedRow in Grid1.GetMergedData())
                {
                    int i = mergedRow.Value("index");  
                    JObject values = mergedRow.Value("values");
                    string ID = values.Value("ID");
                    string MaterialCode = values.Value("MaterialCode");
                    string LocNum = values.Value("LocNum");
                    string Des = values.Value("Des");
                    string Unit = values.Value("Unit");
                    string Amount_Design = values.Value("Amount_Design");
                    string Amount_Re = values.Value("Amount_Re");
                    string Amount_This = values.Value("Amount_This");
                    string Amount_Total = values.Value("Amount_Total");
                    string Size1 = values.Value("Size1");
                    string Size2 = values.Value("Size2");
                    //FineUIPro.TextBox txtMaterialCode = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtMaterialCode");
                    //FineUIPro.TextBox txtLocNum = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtLocNum");
                    //FineUIPro.TextBox txtDes = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtDes");
                    //FineUIPro.TextBox txtUnit = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtUnit");
                    //FineUIPro.TextBox txtAmount_Design = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtAmount_Design");
                    //FineUIPro.TextBox txtAmount_Re = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtAmount_Re");
                    //FineUIPro.TextBox txtAmount_This = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtAmount_This");
                    //FineUIPro.TextBox txtAmount_Total = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtAmount_Total");
                    //FineUIPro.TextBox txtSize1 = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtSize1");
                    //FineUIPro.TextBox txtSize2 = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtSize2");
                    Model.HJGL_Material_Apply_Item apply = new Model.HJGL_Material_Apply_Item
                    {
                        ID = ID,
                        ApplyID = applyNew.ID,
                        MaterialCode = MaterialCode,
                        LocNum = LocNum,
                        Des = Des,
                        Unit = Unit,
                        Amount_Design = Amount_Design,
                        Amount_Re = Amount_Re,
                        Amount_This = Amount_This,
                        Amount_Total = Amount_Total,
                        Size1 = Size1,
                        Size2 = Size2
                    };
                    applyItem.Add(apply);
                     
                }
                BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.UpdateMaterialApplyItem(applyItem);
            }
            else
            {
                Alert.ShowInTop("请输入请购内容!", MessageBoxIcon.Warning);
            }
            //for (int i = 0; i < a; i++)
            //{
            //    Model.HJGL_Material_Apply_Item apply = new Model.HJGL_Material_Apply_Item
            //    {
            //        ID = applyItems[i].ID,
            //        ApplyID = applyNew.ID,
            //        MaterialCode = applyItems[i].MaterialCode,
            //        LocNum = applyItems[i].LocNum,
            //        Des = applyItems[i].Des,
            //        Unit = applyItems[i].Unit,
            //        Amount_Design = applyItems[i].Amount_Design,
            //        Amount_Re = applyItems[i].Amount_Re,
            //        Amount_This = applyItems[i].Amount_This,
            //        Amount_Total = applyItems[i].Amount_Total,
            //        Size1 = applyItems[i].Size1,
            //        Size2 = applyItems[i].Size2
            //    };
            //    Funs.DB.HJGL_Material_Apply_Item.InsertOnSubmit(apply);
            //    //newUser.UserId = getUser.UserId;
            //    insertCount++;
            //}
            Funs.DB.SubmitChanges();
            string rootPath = Server.MapPath("~/");
            string initFullPath = rootPath + initPath;
            string filePath = initFullPath + this.hdFileName.Text;
            if (filePath != string.Empty && File.Exists(filePath))
            {
                File.Delete(filePath);//删除上传的XLS文件
            }
            ShowNotify("保存成功", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion
        #region 提交
        /// 
        /// 提交
        /// 
        /// 
        /// 
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Model.HJGL_Material_Apply applyNew = new Model.HJGL_Material_Apply();
            applyNew.ProjectId = this.CurrUser.LoginProjectId;
            if (!string.IsNullOrEmpty(ApplyID))
            {
                applyNew.ID = ApplyID;
            }
            else
            {
                applyNew.ID = Guid.NewGuid().ToString();
            }
            applyNew.CreateDate = DateTime.Now;
            applyNew.CreateMan = CurrUser.UserId;
            applyNew.ApplyUnitId = this.dpApplyUnit.SelectedValue;
            applyNew.ApplyName = this.txtApplyName.Text;
            applyNew.ApplyDes = this.txtApplyDes.Text;
            applyNew.ApplyCode = this.txtApplyCode.Text;
            applyNew.State = BLL.Const.MaterialApply_Audit1;
            applyNew.ApplyDate = Convert.ToDateTime(this.dpApplyDate.Text);
            if (string.IsNullOrEmpty(ApplyID))
            {
                BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.AddMaterialApply(applyNew);
            }
            else
            {
                BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.UpdateMaterialApply(applyNew);
            }
            int a = applyItems.Count();
            List applyItem = new List();
            if (Grid1.GetMergedData()!=null&&Grid1.GetMergedData().Count > 0)
            {
                foreach (JObject mergedRow in Grid1.GetMergedData())
                {
                    int i = mergedRow.Value("index");
                    JObject values = mergedRow.Value("values");
                    string ID = values.Value("ID");
                    string MaterialCode = values.Value("MaterialCode");
                    string LocNum = values.Value("LocNum");
                    string Des = values.Value("Des");
                    string Unit = values.Value("Unit");
                    string Amount_Design = values.Value("Amount_Design");
                    string Amount_Re = values.Value("Amount_Re");
                    string Amount_This = values.Value("Amount_This");
                    string Amount_Total = values.Value("Amount_Total");
                    string Size1 = values.Value("Size1");
                    string Size2 = values.Value("Size2");
                    //FineUIPro.TextBox txtMaterialCode = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtMaterialCode");
                    //FineUIPro.TextBox txtLocNum = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtLocNum");
                    //FineUIPro.TextBox txtDes = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtDes");
                    //FineUIPro.TextBox txtUnit = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtUnit");
                    //FineUIPro.TextBox txtAmount_Design = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtAmount_Design");
                    //FineUIPro.TextBox txtAmount_Re = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtAmount_Re");
                    //FineUIPro.TextBox txtAmount_This = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtAmount_This");
                    //FineUIPro.TextBox txtAmount_Total = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtAmount_Total");
                    //FineUIPro.TextBox txtSize1 = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtSize1");
                    //FineUIPro.TextBox txtSize2 = (FineUIPro.TextBox)Grid1.Rows[i].FindControl("txtSize2");
                    Model.HJGL_Material_Apply_Item apply = new Model.HJGL_Material_Apply_Item
                    {
                        ID = ID,
                        ApplyID = applyNew.ID,
                        MaterialCode = MaterialCode,
                        LocNum = LocNum,
                        Des = Des,
                        Unit = Unit,
                        Amount_Design = Amount_Design,
                        Amount_Re = Amount_Re,
                        Amount_This = Amount_This,
                        Amount_Total = Amount_Total,
                        Size1 = Size1,
                        Size2 = Size2
                    };
                    applyItem.Add(apply);
                }
                BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.UpdateMaterialApplyItem(applyItem);
                if (State == BLL.Const.MaterialApply_Compile)
                {
                    Model.HJGL_Material_Apply_Approve approve = new Model.HJGL_Material_Apply_Approve();
                    approve.MaterialApplyApproveId = Guid.NewGuid().ToString();
                    approve.ApproveMan = applyNew.CreateMan;
                    approve.ApproveType = BLL.Const.MaterialApply_Compile;
                    approve.MaterialApplyId = applyNew.ID;
                    approve.ApproveDate = DateTime.Now;
                    BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.AddMaterialApplyApprove(approve);
                    Model.HJGL_Material_Apply_Approve nextapprove = new Model.HJGL_Material_Apply_Approve();
                    nextapprove.MaterialApplyApproveId = Guid.NewGuid().ToString();
                    nextapprove.ApproveMan = this.drpHandleMan.SelectedValue;
                    nextapprove.ApproveType = BLL.Const.MaterialApply_Audit1;
                    nextapprove.MaterialApplyId = applyNew.ID;
                    BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.AddMaterialApplyApprove(nextapprove);
 
                }
                else if (State == BLL.Const.MaterialApply_ReCompile)
                {
                    Model.HJGL_Material_Apply_Approve approve = BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.getCurrMaterialApplyApprove(applyNew.ID);
                    approve.ApproveDate = DateTime.Now;
                    approve.ApproveIdea = this.txtOpinions.Text; 
                    BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.UpdateMaterialApplyApprove(approve);
                    Model.HJGL_Material_Apply_Approve nextapprove = new Model.HJGL_Material_Apply_Approve();
                    nextapprove.MaterialApplyApproveId = Guid.NewGuid().ToString();
                    nextapprove.ApproveMan = this.drpHandleMan.SelectedValue;
                    nextapprove.ApproveType = BLL.Const.MaterialApply_Audit1;
                    nextapprove.MaterialApplyId = applyNew.ID;
                    BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.AddMaterialApplyApprove(nextapprove);
                }
                else if(State == BLL.Const.MaterialApply_Audit1)
                {
                    Model.HJGL_Material_Apply_Approve approve = BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.getCurrMaterialApplyApprove(applyNew.ID);
                    approve.ApproveDate = DateTime.Now;
                    approve.ApproveIdea = this.txtOpinions.Text;
                    approve.IsAgree = Convert.ToBoolean(this.rblIsAgree.SelectedValue);
                    BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.UpdateMaterialApplyApprove(approve);
                 
                    if (approve.IsAgree.Value)
                    {
                        Model.HJGL_Material_Apply_Approve nextapprove = new Model.HJGL_Material_Apply_Approve();
                        nextapprove.MaterialApplyApproveId = Guid.NewGuid().ToString();
                        nextapprove.ApproveMan = applyNew.CreateMan;
                        nextapprove.ApproveType = BLL.Const.MaterialApply_Complete;
                        nextapprove.MaterialApplyId = applyNew.ID;
                        nextapprove.ApproveDate = DateTime.Now.AddSeconds(10);
                        BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.AddMaterialApplyApprove(nextapprove);   
                        applyNew.State = BLL.Const.MaterialApply_Complete;
                        BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.UpdateMaterialApply(applyNew);
                    }
                    else
                    {
                        Model.HJGL_Material_Apply_Approve nextapprove = new Model.HJGL_Material_Apply_Approve();
                        nextapprove.MaterialApplyApproveId = Guid.NewGuid().ToString();
                        nextapprove.ApproveMan = this.CurrUser.UserId;
                        nextapprove.ApproveType = BLL.Const.MaterialApply_ReCompile;
                        nextapprove.MaterialApplyId = applyNew.ID;
                        BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.AddMaterialApplyApprove(nextapprove);
                        applyNew.State = BLL.Const.MaterialApply_ReCompile;
                        BLL.HJGL.MaterialManage.HJGL_MaterialApplyService.UpdateMaterialApply(applyNew);
                    }
                  
                  
                }
            }
            else
            {
                Alert.ShowInTop("请输入请购内容!", MessageBoxIcon.Warning);
            }
            //for (int i = 0; i < a; i++)
            //{
            //    Model.HJGL_Material_Apply_Item apply = new Model.HJGL_Material_Apply_Item
            //    {
            //        ID = applyItems[i].ID,
            //        ApplyID = applyNew.ID,
            //        MaterialCode = applyItems[i].MaterialCode,
            //        LocNum = applyItems[i].LocNum,
            //        Des = applyItems[i].Des,
            //        Unit = applyItems[i].Unit,
            //        Amount_Design = applyItems[i].Amount_Design,
            //        Amount_Re = applyItems[i].Amount_Re,
            //        Amount_This = applyItems[i].Amount_This,
            //        Amount_Total = applyItems[i].Amount_Total,
            //        Size1 = applyItems[i].Size1,
            //        Size2 = applyItems[i].Size2
            //    };
            //    Funs.DB.HJGL_Material_Apply_Item.InsertOnSubmit(apply);
            //    //newUser.UserId = getUser.UserId;
            //    insertCount++;
            //}
            Funs.DB.SubmitChanges();
            string rootPath = Server.MapPath("~/");
            string initFullPath = rootPath + initPath;
            string filePath = initFullPath + this.hdFileName.Text;
            if (filePath != string.Empty && File.Exists(filePath))
            {
                File.Delete(filePath);//删除上传的XLS文件
            }
            ShowNotify("保存成功", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion
        #region 关闭弹出窗口
        /// 
        /// 关闭导入弹出窗口
        /// 
        /// 
        /// 
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            if (Session["applyItems"] != null)
            {
                applyItems = Session["applyItems"] as List;
            }
            if (applyItems.Count > 0)
            {
                this.Grid1.Hidden = false;
                this.Grid1.DataSource = applyItems;
                this.Grid1.DataBind();
            }
        }
        #endregion
        #region 下载模板
        /// 
        /// 下载模板按钮
        /// 
        /// 
        /// 
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Confirm.GetShowReference("确定下载导入模板吗?", String.Empty, MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel")));
        }
        /// 
        /// 下载导入模板
        /// 
        /// 
        /// 
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                string rootPath = Server.MapPath("~/");
                string filePath = Const.MaterialApplyTemplateUrl;
                string uploadfilepath = rootPath + filePath;
                string fileName = Path.GetFileName(filePath);
                FileInfo info = new FileInfo(uploadfilepath);
                long fileSize = info.Length;
                Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.ContentType = "excel/plain";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.AddHeader("Content-Length", fileSize.ToString().Trim());
                Response.TransmitFile(uploadfilepath, 0, fileSize);
                Response.End();
            }
        }
       
        protected string ConvertProjectName(object state)
        {
            if (state != null)
            {
                var type= Funs.DB.Base_QualityQuestionType.Where(u=>u.QualityQuestionTypeId==state.ToString()).FirstOrDefault();
                if (type != null)
                {
                    return type.QualityQuestionType;
                }
            }
            return "";
        }
        protected string ConvertState(object state)
        {
            if (state != null)
            {
                if (state.ToString() == BLL.Const.MaterialApply_ReCompile)
                {
                    return "重新编制";
                }
                else if (state.ToString() == BLL.Const.MaterialApply_Compile)
                {
                    return "编制";
                }
                else if (state.ToString() == BLL.Const.MaterialApply_Audit1)
                {
                    return "总包负责人审批";
                }
                
                else if (state.ToString() == BLL.Const.MaterialApply_Complete)
                {
                    return "审批完成";
                }
                
                else
                {
                    return "";
                }
            }
            return "";
        }
        /// 
        /// 获取人员名称
        /// 
        /// 
        /// 
        protected string ConvertUserName(object userid)
        {
            string name = string.Empty;
            if (userid != null)
            {
                var user = BLL.UserService.GetUserByUserId(userid.ToString());
                if (user != null)
                {
                    name = user.UserName;
                }
            }
            return name;
        }
        #endregion
    }
}