using BLL;
using System;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.HSSE.CostGoods
{
    public partial class CostLedgerNew : PageBase
    {
        private static string headerStr;
        #region 定义项
        /// 
        /// 主键
        /// 
        public string getdatetime
        {
            get
            {
                return (string)ViewState["getdatetime"];
            }
            set
            {
                ViewState["getdatetime"] = value;
            }
        }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getdatetime = Request.Params["getdatetime"];
                if (string.IsNullOrEmpty(getdatetime))
                {
                    txtDate.Text = DateTime.Now.ToString("yyyy-MM");
                }
                else {
                    txtDate.Text =Convert.ToDateTime(getdatetime).ToString("yyyy-MM");
                }
               
                loadAll();
            }
        }
        protected void TextBox_TextChanged(object sender, EventArgs e) {
            //loadAll();
            //重定向页面
            //Response.Redirect("TargetPage.aspx?getdatetime="+ txtDate.Text);
           
            Response.Redirect(Request.Url.ToString().Split('?')[0]+ "?getdatetime=" + txtDate.Text);
        }
        /// 
        /// 根据日期加载所有
        /// 
        protected void loadAll() {
            this.gvTotalPayRegistration.DataSource = null;
            this.gvTotalPayRegistration.DataBind();
            var pid = CurrUser.LoginProjectId;
            var result = Funs.DB.CostGoods_HseExpense.FirstOrDefault(x => x.ProjectId == CurrUser.LoginProjectId && x.PayMonth == txtDate.Text);
            if (result != null)
            {
                DateTime startTime = Convert.ToDateTime(result.PayDate.Value.Year + "-" + result.PayDate.Value.Month + "-1");
                DateTime endTime = startTime.AddMonths(1);
                headerStr = string.Empty;
                headerStr += "编号#类别";
                DataTable dt = new DataTable();
                dt.Columns.Add("R0");   //编号
                dt.Columns.Add("R1");   //类别
                var units = BLL.UnitService.GetMainAndSubUnitByProjectIdList(result.ProjectId);
                //如果不是五环,只能看到自己单位的
                //如果不是中国五环工程有限公司,只加载自己的
                if (CurrUser.UnitId == CommonService.GetThisUnitId() || CurrUser.UserId == Const.hfnbdId)
                {
                }
                else
                {
                    var unit = new Model.Base_Unit()
                    {
                        UnitId = CurrUser.UnitId,
                        UnitName = UnitService.getUnitNamesUnitIds(CurrUser.UnitId)
                    };
                    units = new System.Collections.Generic.List();
                    units.Add(unit);
                }
                int a = 0;
                for (int i = 0; i < units.Count; i++)
                {
                    headerStr += "#" + units[i].UnitName + " 当月累计,当年累计";
                    dt.Columns.Add("M" + a);   //当月累计
                    a++;
                    dt.Columns.Add("M" + a);   //当年累计
                    a++;
                }
                DataRow row1 = dt.NewRow();
                row1[0] = "1";
                row1[1] = "完善、改造和维护安全防护设备、设施";
                int b = 2;
                var yearHseExpense = Funs.DB.CostGoods_HseExpense.Where(x => x.ProjectId == pid && x.PayDate.Value.Year == endTime.Year);
                var monthHseExpense = Funs.DB.CostGoods_HseExpense.Where(x => x.ProjectId == pid && x.PayDate >= startTime && x.PayDate <= endTime);
                var xmzje = Funs.DB.CostGoods_FeeRegistration.Where(x => x.ProjectId == pid);
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType1);
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType1) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "2";
                row1[1] = "应急救援和演练";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType2) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType2) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "3";
                row1[1] = "重大危险源管理;隐患整改;安全生产信息化";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType3) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType3) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "4";
                row1[1] = "安全检查、评估评价、咨询与标准化建设";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType4) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType4) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "5";
                row1[1] = "作业人员防护用品";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType5) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType5) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "6";
                row1[1] = "安全生产宣传、教育、培训及奖励";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType6) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType6) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "7";
                row1[1] = "“四新”推广应用支出";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType7) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType7) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "8";
                row1[1] = "安全设施及特种设备检测检验、检定校准";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType8) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType8) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "9";
                row1[1] = "安全生产责任保险";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType9) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType9) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "10";
                row1[1] = "其他与安全生产直接相关的支出";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType10) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType10) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "投入小计";
                row1[1] = "投入小计";
                for (int i = 0; i < units.Count; i++)
                {
                    row1[b] = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType1 + x.SMonthType2
                    + x.SMonthType3 + x.SMonthType4 + x.SMonthType5 + x.SMonthType6 + x.SMonthType7
                    + x.SMonthType8 + x.SMonthType9 + x.SMonthType10) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                    row1[b] = yearHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType1 + x.SMonthType2
                    + x.SMonthType3 + x.SMonthType4 + x.SMonthType5 + x.SMonthType6 + x.SMonthType7
                    + x.SMonthType8 + x.SMonthType9 + x.SMonthType10) ?? 0;
                    row1[b] = Funs.GetNewDecimalOrZero(row1[b].ToString()).ToString("N2");
                    b++;
                }
                dt.Rows.Add(row1);
                b = 2;
                row1 = dt.NewRow();
                row1[0] = "剩余金额";
                row1[1] = "剩余金额";
                for (int i = 0; i < units.Count; i++)
                {
                    //登记总金额-项目累计
                    var Allmoney = xmzje.FirstOrDefault(x => x.UnitId == units[i].UnitId).Cost;
                    var xmlj = monthHseExpense.Where(x => x.UnitId == units[i].UnitId).Sum(x => x.SMonthType1 + x.SMonthType2
                    + x.SMonthType3 + x.SMonthType4 + x.SMonthType5 + x.SMonthType6 + x.SMonthType7
                    + x.SMonthType8 + x.SMonthType9 + x.SMonthType10) ?? 0;
                    var syje = Allmoney - xmlj;
                    row1[b] = syje;
                    b++;
                    row1[b] = syje;
                    b++;
                }
                dt.Rows.Add(row1);
                this.gvTotalPayRegistration.DataSource = dt;
                this.gvTotalPayRegistration.DataBind();
            }
            else {
                headerStr = string.Empty;
                headerStr += "编号#类别";
                DataTable dt = new DataTable();
                dt.Columns.Add("R0");   //编号
                dt.Columns.Add("R1");   //类别
                var units = BLL.UnitService.GetMainAndSubUnitByProjectIdList(CurrUser.LoginProjectId);
                //如果不是五环,只能看到自己单位的
                //如果不是中国五环工程有限公司,只加载自己的
                if (CurrUser.UnitId == CommonService.GetThisUnitId() || CurrUser.UserId == Const.hfnbdId)
                {
                }
                else
                {
                    var unit = new Model.Base_Unit()
                    {
                        UnitId = CurrUser.UnitId,
                        UnitName = UnitService.getUnitNamesUnitIds(CurrUser.UnitId)
                    };
                    units = new System.Collections.Generic.List();
                    units.Add(unit);
                }
                int a = 0;
                for (int i = 0; i < units.Count; i++)
                {
                    headerStr += "#" + units[i].UnitName + " 当月累计,当年累计";
                    dt.Columns.Add("M" + a);   //当月累计
                    a++;
                    dt.Columns.Add("M" + a);   //当年累计
                    a++;
                }
                this.gvTotalPayRegistration.DataSource = dt;
                this.gvTotalPayRegistration.DataBind();
            }
        }
        #region 在控件被绑定后激发
        /// 
        /// 在控件被绑定后激发
        /// 
        /// 
        /// 
        protected void gvTotalPayRegistration_DataBound(object sender, EventArgs e)
        {
            var units = BLL.UnitService.GetMainAndSubUnitByProjectIdList(CurrUser.LoginProjectId);
            if (CurrUser.UnitId == CommonService.GetThisUnitId() || CurrUser.UserId == Const.hfnbdId)
            {
            }
            else
            {
                var unit = new Model.Base_Unit()
                {
                    UnitId = CurrUser.UnitId,
                    UnitName = UnitService.getUnitNamesUnitIds(CurrUser.UnitId)
                };
                units = new System.Collections.Generic.List();
                units.Add(unit);
            }
            for (int i = 0; i < this.gvTotalPayRegistration.Rows.Count - 1; i++) {
                GridViewRow gvrNext = this.gvTotalPayRegistration.Rows[i + 1];
                if (gvrNext.Cells[0].Text == gvrNext.Cells[1].Text) {
                    gvrNext.Cells[1].Visible = false;
                    gvrNext.Cells[0].ColumnSpan = 2;
                }
                if (gvrNext.Cells[0].Text=="剩余金额")
                {
                    var item = 2;
                    for (int j = 0; j < units.Count; j++)
                    {
                        if (gvrNext.Cells[item].Text == gvrNext.Cells[item+1].Text) {
                            gvrNext.Cells[item].Visible = false;
                            gvrNext.Cells[item + 1].ColumnSpan = 2;
                        }
                        item += 2;
                    }
                }
            }
        }
        #endregion
        #region Grid创建行
        /// 
        /// Grid创建行
        /// 
        /// 
        /// 
        protected void gvTotalPayRegistration_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        #endregion
        #region 导出
        /// 
        /// 导出
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Write("");
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("项目HSE费用投入登记表" + filename, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentType = "application/ms-excel";
            this.EnableViewState = false;
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            this.gvTotalPayRegistration.RenderControl(oHtmlTextWriter);
            Response.Write(oStringWriter.ToString());
            Response.Flush();
            Response.End();
        }
        /// 
        /// 重载VerifyRenderingInServerForm方法,否则运行的时候会出现如下错误提示:“类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内”
        /// 
        /// 
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
        #endregion
    }
}