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 ElectrodeBakeRecordEditIn : PageBase
    {
        #region 定义变量
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 材料到货登记记录
        /// 
        public List electrodeBakes = new List();
        /// 
        /// 错误集合
        /// 
        public static string errorInfos = string.Empty;
        #endregion
 
      
        #region 定义项
        /// 
        /// 主键
        /// 
        public string ElectrodeID
        {
            get
            {
                return (string)ViewState["ElectrodeID"];
            }
            set
            {
                ViewState["ElectrodeID"] = value;
            }
        }
        private bool AppendToEnd = false;
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)    
        {
            if (!IsPostBack)
            {
                this.ElectrodeID = Request.Params["ElectrodeID"];
                ///焊条 
                this.drpWME_ID.DataTextField = "ConsumablesName";
                this.drpWME_ID.DataValueField = "ConsumablesName";
                var totalWeldMaterials = from x in Funs.DB.Base_Consumables select x;
                this.drpWME_ID.DataSource = totalWeldMaterials;
                this.drpWME_ID.DataBind();
                // 删除选中单元格的客户端脚本
                string deleteScript = GetDeleteScript();
                // 新增数据初始值
                JObject defaultObj = new JObject();
                defaultObj.Add("ElectrodeModel", "1");
                defaultObj.Add("CardCode", "2");
                defaultObj.Add("BatchCode", "3");
                defaultObj.Add("InLibCode", "4");
                defaultObj.Add("Specifications", "5");
                defaultObj.Add("ElectrodeCount", "6");
                defaultObj.Add("OvenElectricHours", "7");
                defaultObj.Add("OvenElectricMinute", "8");
                defaultObj.Add("OvenElectricTemperature", "9");
                defaultObj.Add("ConstantTemperature", "10");
                defaultObj.Add("ConstantStartHours", "11");
                defaultObj.Add("ConstantStartMinute", "12");
                defaultObj.Add("ConstantEndHours", "13");
                defaultObj.Add("ConstantEndMinute", "14");
                defaultObj.Add("MoveInBoxHours", "15");
                defaultObj.Add("MoveInBoxMinute", "16");
                defaultObj.Add("MoveInTemperature", "17");
                defaultObj.Add("BakeNumber", "1");
                defaultObj.Add("BakeHead", this.CurrUser.UserName);
                defaultObj.Add("Delete", String.Format("
", deleteScript, IconHelper.GetResolvedIconUrl(Icon.Delete)));
                // 在第一行新增一条数据
                btnNew.OnClientClick = Grid1.GetAddNewRecordReference(defaultObj, AppendToEnd);
                // 删除选中行按钮
                btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("请至少选择一项!") + deleteScript;
                
                
            }
        }
        #endregion
        
        #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 (electrodeBakes != null)
                {
                    electrodeBakes.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
            {
                electrodeBakes.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)
            {
                 for (int i = 0; i < ir; i++)
                {
                    JObject defaultObj = new JObject();
                    defaultObj.Add("ElectrodeID", Guid.NewGuid().ToString()); 
                    
                    if (!string.IsNullOrEmpty(pds.Rows[i][0].ToString().Trim()))
                    {
                         defaultObj.Add("ElectrodeModel", pds.Rows[i][0].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "型号" + "," + "此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][1].ToString().Trim()))
                    {
                        var mat = Funs.DB.Base_Consumables.FirstOrDefault(x => x.ConsumablesName == pds.Rows[i][1].ToString().Trim());
                        if (mat != null)
                        {
                            defaultObj.Add("WMT_MatName", pds.Rows[i][1].ToString().Trim());
                        }
                        else
                        {
                            result += "第" + (i + 2).ToString() + "行," + "牌号"+ pds.Rows[i][1].ToString().Trim() + "," + "不存在!" + "|";
                        }
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "牌号" + "," + "此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][2].ToString().Trim()))
                    {
                         defaultObj.Add("BatchCode", pds.Rows[i][2].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "批号" + "," + "此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][3].ToString().Trim()))
                    {
                         defaultObj.Add("InLibCode", pds.Rows[i][3].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "入库自编号" + "," + "此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][4].ToString().Trim()))
                    {
                         defaultObj.Add("Specifications", pds.Rows[i][4].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "规格mm" + "," + "此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][5].ToString().Trim()))
                    {
                         defaultObj.Add("ElectrodeCount", pds.Rows[i][5].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "数量kg" + "," + "此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][5].ToString().Trim())&& pds.Rows[i][6].ToString().Trim().Split(':').Length>0)
                    { 
                        defaultObj.Add("OvenElectricHours", pds.Rows[i][6].ToString().Trim().Split(':')[0]);
                        defaultObj.Add("OvenElectricMinute", pds.Rows[i][6].ToString().Trim().Split(':')[1]);
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "烘箱送电时间" + "," + "此项为必填项或格式不正确!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][7].ToString().Trim()))
                    {
                         defaultObj.Add("OvenElectricTemperature", pds.Rows[i][7].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "烘箱送电温度" + "," + "此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][8].ToString().Trim()))
                    {
                         defaultObj.Add("ConstantTemperature", pds.Rows[i][8].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "恒温温度" + "," + "此项为必填项!" + "|";
                    }
                     
                    if (!string.IsNullOrEmpty(pds.Rows[i][9].ToString().Trim()) && pds.Rows[i][9].ToString().Trim().Split(':').Length > 0)
                    { 
                        defaultObj.Add("ConstantStartHours", pds.Rows[i][9].ToString().Trim().Split(':')[0]);
                        defaultObj.Add("ConstantStartMinute", pds.Rows[i][9].ToString().Trim().Split(':')[1]);
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "恒温开始时间" + "," + "此项为必填项或格式不正确!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][10].ToString().Trim()) && pds.Rows[i][10].ToString().Trim().Split(':').Length > 0)
                    { 
                        defaultObj.Add("ConstantEndHours", pds.Rows[i][10].ToString().Trim().Split(':')[0]);
                        defaultObj.Add("ConstantEndMinute", pds.Rows[i][10].ToString().Trim().Split(':')[1]);
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "恒温结束时间" + "," + "此项为必填项或格式不正确!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][11].ToString().Trim()) && pds.Rows[i][11].ToString().Trim().Split(':').Length > 0)
                    { 
                        defaultObj.Add("MoveInBoxHours", pds.Rows[i][11].ToString().Trim().Split(':')[0]);
                        defaultObj.Add("MoveInBoxMinute", pds.Rows[i][11].ToString().Trim().Split(':')[1]);
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "移入保温箱时间" + "," + "此项为必填项或格式不正确!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][12].ToString().Trim()))
                    {
                         defaultObj.Add("MoveInTemperature", pds.Rows[i][12].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "移入保温箱温度" + "," + "此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(pds.Rows[i][13].ToString().Trim()))
                    {
                         defaultObj.Add("BakeHead", pds.Rows[i][13].ToString().Trim());
                    }
                    else
                    {
                        result += "第" + (i + 2).ToString() + "行," + "烘烤负责人" + "," + "此项为必填项!" + "|";
                    }
                    ///加入用户视图
                    electrodeBakes.Add(defaultObj);
                }
                if (!string.IsNullOrEmpty(result))
                {
                    electrodeBakes.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 (electrodeBakes.Count > 0)
                    {
                        this.Grid1.Hidden = false;
                        this.Grid1.DataSource = electrodeBakes;
                        this.Grid1.DataBind();
                        Alert.ShowInTop("审核完成,请点击保存!", MessageBoxIcon.Success);
                    }
                    else
                    {
                        Alert.ShowInTop("导入数据为空!", MessageBoxIcon.Warning);
                    }
                }
            }
            else
            {
                Alert.ShowInTop("导入数据为空!", MessageBoxIcon.Warning);
            }
            return true;
        }
        #endregion
        #endregion
        /// 
        /// 
        /// 
        /// 
        /// 
        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 设置LinkButtonField的点击客户端事件
            LinkButtonField deleteField = Grid1.FindColumn("Delete") as LinkButtonField;
            deleteField.OnClientClick = GetDeleteScript();
        }
        /// 
        /// 
        /// 
        /// 
        private string GetDeleteScript()
        {
            if (!CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_ElectrodeBakeMenuId, Const.BtnDelete))
            {
                ShowNotify("您没有这个权限,请与管理员联系!");
                return null;
            }
            else
            {
                return Confirm.GetShowReference("删除选中行?", String.Empty, MessageBoxIcon.Question, Grid1.GetDeleteSelectedRowsReference(), String.Empty);
            }
        }
        #region 排序
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            //BindGrid();
        }
        #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.ElectrodeBakeRecordTemplateUrl;
                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();
            }
        }
        #endregion
        /// 
        /// 
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_ElectrodeBakeMenuId, Const.BtnSave))
            {
                ShowNotify("您没有这个权限,请与管理员联系!");
                return;
            }
            JArray teamGroupData = Grid1.GetMergedData();
            foreach (JObject teamGroupRow in teamGroupData)
            {
                int i = teamGroupRow.Value("index");
                //string status = teamGroupRow.Value("status");
                JObject values = teamGroupRow.Value("values");
                GridRow row = Grid1.Rows[i];
                System.Web.UI.WebControls.HiddenField ElectrodeID = (System.Web.UI.WebControls.HiddenField)(row.FindControl("hdElectrodeID"));
                Model.HJGL_ElectrodeBake newElectrodeBakeItem = new Model.HJGL_ElectrodeBake();
                newElectrodeBakeItem.ProjectId = CurrUser.LoginProjectId;
                newElectrodeBakeItem.CompileDate = DateTime.Now;
                newElectrodeBakeItem.CompileMan = CurrUser.UserId;
                newElectrodeBakeItem.ElectrodeID = ElectrodeID.Value;
                newElectrodeBakeItem.ElectrodeModel = values.Value("ElectrodeModel");
                //newElectrodeBakeItem.CardCode = values.Value("CardCode");
                newElectrodeBakeItem.BatchCode = values.Value("BatchCode");
                newElectrodeBakeItem.InLibCode = values.Value("InLibCode");
                newElectrodeBakeItem.Specifications = values.Value("Specifications");
                newElectrodeBakeItem.ElectrodeCount = Funs.GetNewInt(values.Value("ElectrodeCount"));
                newElectrodeBakeItem.OvenElectricHours = Funs.GetNewInt(values.Value("OvenElectricHours"));
                newElectrodeBakeItem.OvenElectricMinute = Funs.GetNewInt(values.Value("OvenElectricMinute"));
                newElectrodeBakeItem.OvenElectricTemperature = Funs.GetNewInt(values.Value("OvenElectricTemperature"));
                newElectrodeBakeItem.ConstantTemperature = Funs.GetNewInt(values.Value("ConstantTemperature"));
                newElectrodeBakeItem.ConstantStartHours = Funs.GetNewInt(values.Value("ConstantStartHours"));
                newElectrodeBakeItem.ConstantStartMinute = Funs.GetNewInt(values.Value("ConstantStartMinute"));
                newElectrodeBakeItem.ConstantEndHours = Funs.GetNewInt(values.Value("ConstantEndHours"));
                newElectrodeBakeItem.ConstantEndMinute = Funs.GetNewInt(values.Value("ConstantEndMinute"));
                newElectrodeBakeItem.MoveInBoxHours = Funs.GetNewInt(values.Value("MoveInBoxHours"));
                newElectrodeBakeItem.MoveInBoxMinute = Funs.GetNewInt(values.Value("MoveInBoxMinute"));
                newElectrodeBakeItem.MoveInTemperature = Funs.GetNewInt(values.Value("MoveInTemperature"));
                newElectrodeBakeItem.BakeNumber = Funs.GetNewInt(values.Value("BakeNumber"));
                newElectrodeBakeItem.BakeHead = values.Value("BakeHead");
                var mat = Funs.DB.Base_Consumables.FirstOrDefault(x => x.ConsumablesName == values.Value("WMT_MatName"));
                if (mat != null)
                {
                    newElectrodeBakeItem.WMT_ID = mat.ConsumablesId;
                }
                BLL.HJGL_ElectrodeBakeService.AddElectrodeBake(newElectrodeBakeItem); 
            }
            //Alert.ShowInTop("保存成功!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
        }
    }
    
}