using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FineUIPro.Web.CCP
{
    public partial class CCPUpload : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hidId.Text = Request["id"];
                hidContractNo.Text = Request["contractNo"];
                hidccpNo.Text = Request["ccpno"];
                hidtype.Text = Request["type"];
                if (hidtype.Text == "view")
                {
                    Form2.Hidden = true;
                }
                Panel1.Title = "File Management(" + string.Format("{0:d3}", int.Parse(hidccpNo.Text)) + ")";
                if (!string.IsNullOrEmpty(hidId.Text))
                {
                    BindGrid(hidId.Text, hidContractNo.Text);
                }
            }
        }


        #region 绑定数据
        /// <summary>
        /// 绑定数据
        /// </summary>
        public void BindGrid(string id, string contractNo)
        {
            var fileManageList = new List<Model.FilesManagement>();
            Expression<Func<Model.FilesManagement, bool>> express = PredicateExtensions.True<Model.FilesManagement>();
            if (!string.IsNullOrEmpty(id))
            {
                express = express.And(p => p.FO == string.Format("{0}_合同({1})_类型({2})", hidId.Text, hidContractNo.Text, ddlType.SelectedValue));
            }
            fileManageList = Funs.DB.FilesManagement.Where(express).OrderByDescending(p => p.UploadDate).ToList();
            Grid1.RecordCount = fileManageList.Count;
            var table = this.GetPagedDataTable(Grid1, fileManageList);
            Grid1.DataSource = table;
            Grid1.DataBind();
            for (int i = 0; i < Grid1.Rows.Count; i++)
            {
                if (hidtype.Text == "view")
                {
                    Grid1.Columns[5].Hidden = true;
                }
                System.Web.UI.WebControls.LinkButton lblLock = ((System.Web.UI.WebControls.LinkButton)(this.Grid1.Rows[i].FindControl("lblLock")));
                string url = lblLock.CommandArgument.ToString();
                if (!string.IsNullOrEmpty(url))
                {
                    url = url.Replace('\\', '/');
                    lblLock.Text = BLL.UploadAttachmentService.ShowAttachment("../", url);
                }
            }
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid(hidId.Text, hidContractNo.Text);
        }

        /// <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(hidId.Text, hidContractNo.Text);
        }

        #endregion

        #region 保存
        /// <summary>
        /// 保存
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            FilesManagement fileModel = new FilesManagement();
            if (ccpFile.HasFile)
            {
                string fileName = ccpFile.ShortFileName;
                //文件预上传路径
                string url = "File\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + "\\";
                string path = Funs.RootPath + url;

                //文件路径
                string filePath = ccpFile.PostedFile.FileName;
                if (!string.IsNullOrEmpty(filePath))
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string filePathUrl = path + fileName;
                    ccpFile.SaveAs(filePathUrl);
                    fileModel.FileName = fileName;
                    fileModel.FileType = ddlType.SelectedValue;
                    fileModel.FileLength = ccpFile.PostedFile.ContentLength.ToString();
                    fileModel.FileUrl = url + fileName;
                }

            }

            fileModel.FileId = Guid.NewGuid().ToString();
            fileModel.FO = string.Format("{0}_合同({1})_类型({2})", hidId.Text, hidContractNo.Text, ddlType.SelectedValue);
            fileModel.UploadUser = CurrUser.UserName;
            fileModel.UploadDate = DateTime.Now;
            fileModel.Remark = txtRemark.Text.Trim();
            Funs.DB.FilesManagement.InsertOnSubmit(fileModel);
            Funs.DB.SubmitChanges();

            Form2.Reset();
            BindGrid(hidId.Text, hidContractNo.Text);
        }
        #endregion

        #region 列点击事件
        /// <summary>
        /// 列点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            var fileid = Grid1.DataKeys[e.RowIndex][0].ToString();
            var fileModel = Funs.DB.FilesManagement.FirstOrDefault(p => p.FileId == fileid);
            if (e.CommandName == "Delete")
            {
                if (!string.IsNullOrEmpty(fileid))
                {

                    if (fileModel.FileUrl != null)
                    {
                        if (File.Exists(Server.MapPath("~/") + fileModel.FileUrl))
                        {
                            Directory.Delete(Server.MapPath("~/") + fileModel.FileUrl.Replace(fileModel.FileName, ""), true);
                        }
                    }
                    Funs.DB.FilesManagement.DeleteOnSubmit(fileModel);
                    Funs.DB.SubmitChanges();
                }
                BindGrid(hidId.Text, hidContractNo.Text);
                ShowNotify("Delete Successful!");
            }
            else if (e.CommandName == "IsDownload")
            {
                var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, BLL.Const.CPTViewListMenuId);
                if (buttonList.Contains(BLL.Const.BtnAttachment))
                {
                    ShowFile(fileModel.FileUrl);
                }
                else
                {
                    ShowNotify("No permission, please contact the administrator", MessageBoxIcon.Warning);
                    return;
                }
            }

        }
        #endregion
    }
}