using BLL;
using BLL.Common;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace FineUIPro.Web.EditorManage
{
    public partial class ProjectControlEditor : PageBase
    {
        #region 加载
        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // 表头过滤
            FilterDataRowItem = FilterDataRowItemImplement;
            if (!IsPostBack)
            {
                GetButtonPower();//权限设置
                this.btnSync.Hidden = true;
                if (this.CurrUser.Account == BLL.Const.Gly)
                {
                    this.Toolbar2.Hidden = false;
                }
                else
                {
                    this.Toolbar2.Hidden = true;
                }

                //项目类型
                this.drpJobType.DataTextField = "ConstText";
                this.drpJobType.DataValueField = "ConstValue";
                this.drpJobType.DataSource = BLL.ConstService.GetConstListByGroupId(BLL.Const.ProjectPlanner_JobType);
                this.drpJobType.DataBind();
                Funs.FineUIPleaseSelectJobType(this.drpJobType);

                //项目状态
                this.drpJobStatus.DataTextField = "ConstText";
                this.drpJobStatus.DataValueField = "ConstValue";
                this.drpJobStatus.DataSource = BLL.ConstService.GetConstListByGroupId(BLL.Const.ProjectPlanner_JobStatus);
                this.drpJobStatus.DataBind();
                Funs.FineUIPleaseSelectJobStatus(this.drpJobStatus);

                btnNew.OnClientClick = Window1.GetShowReference("ProjectControlEditorEdit.aspx") + "return false;";

                btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("Please select at least one item!");
                btnDelete.ConfirmText = String.Format("Are you sure you want to delete the selected &nbsp;<b><script>{0}</script></b>&nbsp;rows?", Grid1.GetSelectedCountReference());

                ddlPageSize.SelectedValue = Grid1.PageSize.ToString();
                // 绑定表格
                BindGrid();
            }
            else
            {
                if (GetRequestEventArgument() == "reloadGrid")
                {
                    BindGrid();
                }
            }
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindGrid()
        {
            string strSql = @"SELECT EProjectId," +
                "ProjectControl_JobNo," +
                "ProjectControl_JobType," +
                "ProjectControl_JobStatus," +
                "ProjectControl_JobTitle," +
                "ProjectControl_BUCode," +
                "PM_General_Priority," +
                "PM_General_Category " +
                "FROM dbo.Editor_EProject WHERE 1=1 ";
            List<SqlParameter> listStr = new List<SqlParameter>();
            if (this.drpJobType.SelectedValue != BLL.Const._Null)
            {
                strSql += " AND ProjectControl_JobType=@JobType ";
                listStr.Add(new SqlParameter("@JobType", this.drpJobType.SelectedItem.Text));
            }
            if (this.drpJobStatus.SelectedValue != BLL.Const._Null && this.drpJobStatus.SelectedValue != null)
            {
                strSql += " AND ProjectControl_JobStatus=@Status ";
                listStr.Add(new SqlParameter("@Status", this.drpJobStatus.SelectedItem.Text));
            }
            if (!string.IsNullOrEmpty(this.txtJobNO.Text.Trim()))
            {
                strSql += " AND ProjectControl_JobNo LIKE @jobNO ";
                listStr.Add(new SqlParameter("@jobNO", this.txtJobNO.Text.Trim() + "%"));
            }
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            // 2.获取当前分页数据
            //var table = this.GetPagedDataTable(Grid1, tb1);
            Grid1.RecordCount = tb.Rows.Count;
            tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion

        #region 过滤表头
        /// <summary>
        /// 过滤表头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_FilterChange(object sender, EventArgs e)
        {
            BindGrid();
        }

        /// <summary>
        /// 根据表头信息过滤列表数据
        /// </summary>
        /// <param name="sourceObj"></param>
        /// <param name="fillteredOperator"></param>
        /// <param name="fillteredObj"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        private bool FilterDataRowItemImplement(object sourceObj, string fillteredOperator, object fillteredObj, string column)
        {
            bool valid = false;
            if (column == "ProjectControl_JobNo")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "ProjectControl_JobType")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "ProjectControl_JobTitle")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "ProjectControl_JobStatus")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "ProjectControl_BUCode")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "PM_General_Priority")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "PM_General_Category")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            return valid;
        }
        #endregion

        #region  删除数据
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            this.DeleteData();
        }

        /// <summary>
        /// 右键删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            this.DeleteData();
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        private void DeleteData()
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var role = BLL.EProjectService.GeteProjectById(rowID);
                    if (role != null)
                    {
                        if (judgementDelete(rowID, false))
                        {
                            BLL.EProjectService.DeleteEproejctById(rowID);
                            ShowNotify("Deleted successfully!");
                        }
                    }
                }
                BindGrid();
                BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Delete Project control editor information");
            }
        }
        #endregion

        #region 分页、排序
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        /// <summary>
        /// 分页显示条数下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }
        #endregion

        #region 关闭弹出窗口
        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInParent("Please select at least one record!");
                return;
            }
            string Id = Grid1.SelectedRowID;
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("ProjectControlEditorEdit.aspx?eProjectId={0}&ran=" + DateTime.Now + "", Id, "编辑 - ")));
        }

        /// <summary>
        /// 右键编辑事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuEdit_Click(object sender, EventArgs e)
        {
            btnEdit_Click(sender, e);
        }

        /// <summary>
        /// Grid行双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInParent("Please select at least one record!");
                return;
            }
            string Id = e.RowID;
            //string Id = Grid1.SelectedRowID;
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("ProjectControlEditorEdit.aspx?eProjectId={0}&?ranparam=random()", Id, "编辑 - ")));
        }
        #endregion

        #region 同步文件路径
        protected void btnSync_Click(object sender, EventArgs e)
        {
            string publicFilePath = Const.PublicFilePath;
            SyncFilePathHelper.GetList(publicFilePath);
            //string strSql = "SELECT ProjectControl_JobNo FROM dbo.Editor_EProject ORDER BY ProjectControl_JobNo";
            //DataTable dt = SQLHelper.GetDataTableRunText(strSql, null);
            //if (dt.Rows.Count > 0)
            //{
            //    for (int i = 0; i < dt.Rows.Count; i++)
            //    {
            //        SyncFilePathHelper.UpdateFilePath2(publicFilePath, dt.Rows[i][0].ToString());
            //    }
            BindGrid();
            ShowNotify("Sync success!", MessageBoxIcon.Success);
        }

    
        #endregion
        #region 判断是否可删除
        /// <summary>
        /// 判断是否可以删除
        /// </summary>
        /// <returns></returns>
        private bool judgementDelete(string id, bool isShow)
        {
            string content = string.Empty;
            var pm = BLL.PMService.GetPMByEprojectId(id);
            if (pm.Count > 0)
            {
                content = "Cannot be deleted, already used in PM";
            }
            var resourcePlan = BLL.ResourcePlanService.GetResourcePlanByEProjectId(id);
            if (resourcePlan.Count > 0)
            {
                content = "Cannot be deleted, already used in Resource Plan";
            }
            if (string.IsNullOrEmpty(content))
            {
                return true;
            }
            else
            {
                if (isShow)
                {
                    Alert.ShowInTop(content, MessageBoxIcon.Warning);
                }
                return false;
            }
        }
        #endregion

        #region 权限设置
        /// <summary>
        /// 菜单按钮权限
        /// </summary>
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, BLL.Const.ProjectControlEditorMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnEdit.Hidden = false;
                    this.btnMenuEdit.Hidden = false;
                    this.Grid1.EnableRowDoubleClickEvent = true;
                }
                else
                {
                    this.Grid1.EnableRowDoubleClickEvent = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnDelete.Hidden = false;
                    this.btnMenuDelete.Hidden = false;
                }
            }
        }
        #endregion

        #region 查询
        protected void drpJobType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.drpJobStatus.Items.Clear();
            if (drpJobType.SelectedText == "Other")
            {
                BLL.ConstService.InitConstValueProjectStatus(this.drpJobStatus, BLL.Const.ProjectPlanner_JobStatus, "3", true);
            }
            if (drpJobType.SelectedText != "Other")
            {
                BLL.ConstService.InitConstValueProjectStatus(this.drpJobStatus, BLL.Const.ProjectPlanner_JobStatus, "2", true);
            }
        }

        /// <summary>
        /// 下拉框选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion

        #region 查看
        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuView_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInParent("Please select at least one record!");
                return;
            }
            string Id = Grid1.SelectedRowID;
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("ProjectControlEditorEdit.aspx?eProjectId={0}&ran=" + DateTime.Now + "&view=1", Id, "编辑 - ")));

        }
        #endregion

        #region 导入
        #region 定义项
        /// <summary>
        /// 上传预设的虚拟路径
        /// </summary>
        private string initPath = Const.ExcelUrl;

        /// <summary>
        /// 错误集合
        /// </summary>
        public static string errorInfos = string.Empty;
        #endregion

        #region 模板下载
        /// <summary>
        /// 模板下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Confirm.GetShowReference("Are you sure to download the import template?", String.Empty, MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel")));
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                string rootPath = Server.MapPath("~/");
                string uploadfilepath = rootPath + Const.FilesLinkTemplateUrl;
                string filePath = Const.FilesLinkTemplateUrl;
                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

        #region 导入
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImport_Click(object sender, EventArgs e)
        {
            string message = string.Empty;
            errorInfos = string.Empty;
            //List<Editor_EProject> userList = new List<Editor_EProject>();
            //try
            //{
            if (this.fuAttachUrl.HasFile == false)
            {
                ShowNotify("Please select Excel file!", MessageBoxIcon.Warning);
                return;
            }
            string IsTxt = Path.GetExtension(this.fuAttachUrl.FileName).ToString().Trim().ToLower();
            if (IsTxt != ".txt")
            {
                ShowNotify("Only Excel files can be selected!", MessageBoxIcon.Warning);
                return;
            }
            //if (userList != null)
            //{
            //    userList.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() + IsTxt;
            //上传文件路径
            string filePath = initFullPath + this.hdFileName.Text;
            //文件上传服务器
            this.fuAttachUrl.PostedFile.SaveAs(filePath);
            //文件上传服务器后的名称
            string fileName = rootPath + initPath + this.hdFileName.Text;

            Dictionary<string, string> dicPath = new Dictionary<string, string>();
            dicPath = GetFilePathList(fileName);
            if (dicPath.Count() > 0)
            {
                foreach (var q in dicPath)
                {
                    var ep = BLL.EProjectService.GeteProjectByJobNO(q.Key);
                    if (ep != null)
                    {
                        ep.ProjectControl_FilesLink = q.Value;
                        BLL.EProjectService.UpdateEprojectFileLink(ep);
                    }
                }
                BindGrid();
                ShowNotify("Import success!", MessageBoxIcon.Success);
            }
            else
            {
                ShowAlert("No data!", MessageBoxIcon.Warning);
                return;
            }
            #region 暂不用 由Excel变为txt导入
            ////读取Excel
            //DataSet ds = NPOIHelper.ExcelToDataSet(fileName, out errorInfos, true);
            ////验证Excel读取是否有误
            //if (!string.IsNullOrEmpty(errorInfos))
            //{
            //    ShowNotify(errorInfos, MessageBoxIcon.Warning);
            //    return;
            //}
            ////导入数据库
            //if (ds.Tables.Count > 0)
            //{
            //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //    {
            //        Editor_EProject u = new Editor_EProject();

            //        #region 数据验证和赋值
            //        string jobNo = ds.Tables[0].Rows[i]["Job_No"].ToString();
            //        if (!string.IsNullOrEmpty(jobNo))
            //        {
            //            var ep = BLL.EProjectService.GeteProjectByJobNO(jobNo);
            //            if (ep != null)
            //            {
            //                u.ProjectControl_JobNo = jobNo;
            //            }
            //            else
            //            {
            //                errorInfos += (i + 2) + "Line, [Job_No] does not exist!</br>";
            //            }
            //        }
            //        else
            //        {
            //            errorInfos += (i + 2) + "Line, [Job_No] cannot be empty!</br>";
            //        }
            //        string filesLink = ds.Tables[0].Rows[i]["Files_Link"].ToString();
            //        if (!string.IsNullOrEmpty(filesLink))
            //        {
            //            u.ProjectControl_FilesLink = filesLink;
            //        }
            //        else
            //        {
            //            errorInfos += (i + 2) + "Line, [Files_Link] cannot be empty!</br>";
            //        }                        
            //        userList.Add(u);
            //        #endregion
            //    }
            //    if (!string.IsNullOrEmpty(errorInfos))
            //    {
            //        ShowAlert(errorInfos,MessageBoxIcon.Warning);
            //        return;
            //    }
            //    if (userList.Count > 0)
            //    {
            //        foreach (var item in userList)
            //        {
            //            var newEpr = BLL.EProjectService.GeteProjectByJobNO(item.ProjectControl_JobNo);
            //            if (newEpr != null)
            //            {
            //                newEpr.ProjectControl_FilesLink = item.ProjectControl_FilesLink;
            //                BLL.EProjectService.UpdateEprojectFileLink(newEpr);
            //            }
            //        }
            //    }
            //    BindGrid();
            //    ShowNotify("Import success!", MessageBoxIcon.Success);
            //    PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            //}
            //else
            //{
            //    ShowAlert("No data!", MessageBoxIcon.Warning);
            //    return;
            //}
            //}
            //catch (Exception ex)
            //{
            //    ShowAlert("'" + ex.Message + "'", MessageBoxIcon.Warning);
            //}
            #endregion
        }
        #endregion

        private Dictionary<string,string> GetFilePathList(string fileName)
        {
            Dictionary<string, string> ListStr = new Dictionary<string, string>();
            string strLine = "";
            int i = 0;

            StreamReader sr = new StreamReader(fileName, Encoding.GetEncoding("GB2312"));
            strLine = sr.ReadLine();
            while (strLine != null)
            {
                Response.Write(strLine + "<br>");
                strLine = sr.ReadLine();
                if (!string.IsNullOrEmpty(strLine) && strLine.Contains("Transmittals"))
                {
                    string[] strArray = Regex.Split(strLine, "Transmittals");
                    if (strArray.Count() > 1)
                    {
                        string[] strPath = strArray[1].Split('\\');
                        int m = 0;
                        bool isAdd = false;
                        bool isC = false;  // 是否C部门
                        string filePath = string.Empty;
                        string jobNo = string.Empty;
                        if (strPath.Length > 2)
                        {
                            foreach (string str in strPath)
                            {
                                if (m > 0)
                                {
                                    if (m == 1)
                                    {
                                        if (str.Contains("C"))
                                        {
                                            isC = true;
                                            filePath = str;
                                        }
                                    }
                                    else
                                    {
                                        if (isC)
                                        {
                                            filePath = filePath + "\\" + str;
                                            if (BLL.SyncFilePathHelper.NumberOfDigits(str) >= 5 && !str.Contains("-"))
                                            {
                                                isAdd = true;
                                                jobNo = str;
                                                break;
                                            }
                                        }
                                    }
                                }
                                m++;
                            }
                        }
                        if (isAdd)
                        {
                            if (!string.IsNullOrEmpty(jobNo) && !ListStr.ContainsKey(jobNo))
                            {
                                ListStr.Add(jobNo, "\\\\wcnnji008219389\\Projects_Transmittals\\" + filePath);
                            }

                        }
                    }
                    i++;
                }
            }
            Response.Write(i);
            sr.Dispose();
            sr.Close();

            return ListStr;

        }



        #endregion
    }
}