using BLL;
using Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.ZHGL.Environmental
{
    public partial class ProjectEnergyReportSave : PageBase
    {
        #region 定义变量
        /// 
        /// 报表主键Id
        /// 
        public string EnergyReportId
        {
            get
            {
                return (string)ViewState["EnergyReportId"];
            }
            set
            {
                ViewState["EnergyReportId"] = value;
            }
        }
        /// 
        /// 定义集合
        /// 
        private static List items = new List();
        #endregion
        #region 加载页面
        ///  
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Params["type"] != "-1")
                {
                    this.GetButtonPower();
                }
                items.Clear();
                BLL.ConstValue.InitConstValueDropDownList(this.drpQuarters, ConstValue.Group_0011, false);
                BLL.ConstValue.InitConstValueDropDownList(this.drpYear, ConstValue.Group_0008, false);
                this.drpUnit.DataTextField = "UnitName";
                drpUnit.DataValueField = "UnitId";
                drpUnit.DataSource = BLL.UnitService.GetThisUnitDropDownList();
                drpUnit.DataBind();
                this.drpUnit.Readonly = true;
                string unitId = Request.QueryString["UnitId"];
                string year = Request.QueryString["Year"];
                string quarters = Request.QueryString["Quarters"];
                EnergyReportId = Request.QueryString["EnergyReportId"];
                if (!string.IsNullOrEmpty(Request.QueryString["type"]))
                {
                    this.btnSave.Hidden = true;
                }
                else
                {
                    this.btnSave.Hidden = false;
                }
                if (!String.IsNullOrEmpty(EnergyReportId))
                {
                    items = BLL.ProjectEnergyreportItemService.GetShowItems(EnergyReportId);
                    this.Grid1.DataSource = items;
                    this.Grid1.DataBind();
                    var report = BLL.ProjectEnergyReportService.GetEnvironmental_ProjectEnergyReportById(EnergyReportId);
                    if (report != null)
                    {
                        //this.btnCopy.Hidden = true;
                        //if (this.CurrUser.UserId == BLL.Const.sysglyId || this.CurrUser.UserId == BLL.Const.hfnbdId)
                        //{
                        //    this.btnSave.Hidden = false;
                        //}
                        if (report.UpState == BLL.Const.UpState_3)
                        {
                            this.btnSave.Hidden = true;
                        }
                        drpQuarters.SelectedValue = report.Quarters.ToString();
                        drpYear.SelectedValue = report.Year.ToString();
                        drpUnit.SelectedValue = report.UnitId;
                        if (report.FillingDate != null)
                        {
                            txtFillingDate.Text = string.Format("{0:yyyy-MM-dd}", report.FillingDate);
                        }
                        txtDutyPerson.Text = report.DutyPerson;
                    }
                }
                else
                {
                    //this.btnCopy.Hidden = false;
                    drpQuarters.SelectedValue = quarters;
                    drpYear.SelectedValue = year;
                    txtFillingDate.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                    txtDutyPerson.Text = this.CurrUser.UserName;
                    //增加明细集合
                    GetNewItems(year, quarters);
                    this.Grid1.DataSource = items;
                    this.Grid1.DataBind();
                }
            }
            else
            {
                string arg = GetRequestEventArgument(); // 此函数所在文件:PageBase.cs
                if (arg == "UPDATE_SUMMARY")
                {
                    SaveData();
                }
            }
        }
        void SaveData()
        {
            List _EnergyReportItems = new List();
            foreach (JObject mergedRow in Grid1.GetMergedData())
            {
                JObject values = mergedRow.Value("values");
                string sortIndex = values.Value("SortIndex");
                var newItem = items.FirstOrDefault(x => x.SortIndex == sortIndex);
                if (newItem != null)
                {
                    newItem.EnergyReportItemId = SQLHelper.GetNewID();
                    newItem.EnergyReportId = EnergyReportId;
                    newItem.SortIndex = values.Value("SortIndex");
                    newItem.BusinessCategory = values.Value("BusinessCategory");
                    newItem.Throughput_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("Throughput_BasePeriod")).ToString();
                    newItem.Throughput_LastPeriod = Funs.GetNewDecimalOrZero(values.Value("Throughput_LastPeriod")).ToString();
                    newItem.Throughput_ThisPeriod = Funs.GetNewDecimalOrZero(values.Value("Throughput_ThisPeriod")).ToString();
                    newItem.Throughput_UnitOfMeasurement = values.Value("Throughput_UnitOfMeasurement");
                    newItem.Yield_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("Yield_BasePeriod")).ToString();
                    newItem.Yield_LastPeriod = Funs.GetNewDecimalOrZero(values.Value("Yield_LastPeriod")).ToString();
                    newItem.Yield_ThisPeriod = Funs.GetNewDecimalOrZero(values.Value("Yield_ThisPeriod")).ToString();
                    newItem.Yield_UnitOfMeasurement = values.Value("Yield_UnitOfMeasurement");
                    newItem.OutputValue_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("OutputValue_BasePeriod")).ToString();
                    newItem.OutputValue_LastYear = Funs.GetNewDecimalOrZero(values.Value("OutputValue_LastYear")).ToString();
                    newItem.OutputValue_ThisYear = Funs.GetNewDecimalOrZero(values.Value("OutputValue_ThisYear")).ToString();
                    newItem.OperationScale_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("OperationScale_BasePeriod")).ToString();
                    newItem.OperationScale_LastYear = Funs.GetNewDecimalOrZero(values.Value("OperationScale_LastYear")).ToString();
                    newItem.OperationScale_ThisYear = Funs.GetNewDecimalOrZero(values.Value("OperationScale_ThisYear")).ToString();
                    newItem.OperationScale_UnitOfMeasurement = values.Value("OperationScale_UnitOfMeasurement");
                    newItem.ServiceOperatingIncome_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("ServiceOperatingIncome_BasePeriod")).ToString();
                    newItem.ServiceOperatingIncome_LastYear = Funs.GetNewDecimalOrZero(values.Value("ServiceOperatingIncome_LastYear")).ToString();
                    newItem.ServiceOperatingIncome_ThisYear = Funs.GetNewDecimalOrZero(values.Value("ServiceOperatingIncome_ThisYear")).ToString();
                    _EnergyReportItems.Add(newItem);
                }
            }
            this.Grid1.DataSource = _EnergyReportItems;
            this.Grid1.DataBind();
            _EnergyReportItems.RemoveAll(x => x.SortIndex == "01");
            var q = (from x in _EnergyReportItems
                     group x by x.EnergyReportId into g
                     select new
                     {
                         g.Key,
                         Throughput_BasePeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.Throughput_BasePeriod)),
                         Throughput_LastPeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.Throughput_LastPeriod)),
                         Throughput_ThisPeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.Throughput_ThisPeriod)),
                         Yield_BasePeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.Yield_BasePeriod)),
                         Yield_LastPeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.Yield_LastPeriod)),
                         Yield_ThisPeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.Yield_ThisPeriod)),
                         OutputValue_BasePeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.OutputValue_BasePeriod)),
                         OutputValue_LastYear = g.Sum(x => Funs.GetNewDecimalOrZero(x.OutputValue_LastYear)),
                         OutputValue_ThisYear = g.Sum(x => Funs.GetNewDecimalOrZero(x.OutputValue_ThisYear)),
                         OperationScale_BasePeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.OperationScale_BasePeriod)),
                         OperationScale_LastYear = g.Sum(x => Funs.GetNewDecimalOrZero(x.OperationScale_LastYear)),
                         OperationScale_ThisYear = g.Sum(x => Funs.GetNewDecimalOrZero(x.OperationScale_ThisYear)),
                         ServiceOperatingIncome_BasePeriod = g.Sum(x => Funs.GetNewDecimalOrZero(x.ServiceOperatingIncome_BasePeriod)),
                         ServiceOperatingIncome_LastYear = g.Sum(x => Funs.GetNewDecimalOrZero(x.ServiceOperatingIncome_LastYear)),
                         ServiceOperatingIncome_ThisYear = g.Sum(x => Funs.GetNewDecimalOrZero(x.ServiceOperatingIncome_ThisYear)),
                     }
                    ).FirstOrDefault();
            this.Grid1.Rows[0].Values[4] = q.Throughput_BasePeriod;
            this.Grid1.Rows[0].Values[5] = q.Throughput_LastPeriod;
            this.Grid1.Rows[0].Values[6] = q.Throughput_ThisPeriod;
            this.Grid1.Rows[0].Values[9] = q.Yield_BasePeriod;
            this.Grid1.Rows[0].Values[10] = q.Yield_LastPeriod;
            this.Grid1.Rows[0].Values[11] = q.Yield_ThisPeriod;
            this.Grid1.Rows[0].Values[14] = q.OutputValue_BasePeriod;
            this.Grid1.Rows[0].Values[15] = q.OutputValue_LastYear;
            this.Grid1.Rows[0].Values[16] = q.OutputValue_ThisYear;
            this.Grid1.Rows[0].Values[19] = q.OperationScale_BasePeriod;
            this.Grid1.Rows[0].Values[20] = q.OperationScale_LastYear;
            this.Grid1.Rows[0].Values[21] = q.OperationScale_ThisYear;
            this.Grid1.Rows[0].Values[24] = q.ServiceOperatingIncome_BasePeriod;
            this.Grid1.Rows[0].Values[25] = q.ServiceOperatingIncome_LastYear;
            this.Grid1.Rows[0].Values[26] = q.ServiceOperatingIncome_ThisYear;
        }
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            Model.Environmental_ProjectEnergyReportItem a = (Model.Environmental_ProjectEnergyReportItem)e.DataItem;
            e.DataItem.ToString();
            //string SortIndex = Convert.ToString(row["SortIndex"]);
            if (a.SortIndex == "01")
            {
                for (int i = 0; i < e.CellCssClasses.Count(); i++)
                {
                    e.CellCssClasses[i] = "f-grid-cell-uneditable";
                }
            }
        }
        #endregion
        #region 关闭窗口
        /// 
        /// 关闭窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            var report = BLL.ProjectEnergyReportService.GetEnvironmental_ProjectEnergyReportById(EnergyReportId);
            this.btnSave.Hidden = false;
        }
        #endregion
        #region 保存、上报
        /// 
        /// 保存数据
        /// 
        /// 
        private void Save(string type)
        {
            //string EnergyReportId = Request.QueryString["EnergyReportId"];
            Model.Environmental_ProjectEnergyReport report = new Environmental_ProjectEnergyReport
            {
                ProjectId=this.CurrUser.LoginProjectId,
                Year = Funs.GetNewIntOrZero(drpYear.SelectedValue),
                Quarters = Funs.GetNewIntOrZero(drpQuarters.SelectedValue)
            };
            if (!string.IsNullOrEmpty(txtFillingDate.Text.Trim()))
            {
                report.FillingDate = Convert.ToDateTime(txtFillingDate.Text.Trim());
            }
            report.DutyPerson = txtDutyPerson.Text.Trim();
            if (String.IsNullOrEmpty(EnergyReportId))
            {
                Environmental_ProjectEnergyReport old = ProjectEnergyReportService.GetEnergyReportByProjectIdDate(this.CurrUser.LoginProjectId, Funs.GetNewIntOrZero(drpYear.SelectedValue), Funs.GetNewIntOrZero(drpQuarters.SelectedValue));
                if (old == null)
                {
                    report.EnergyReportId = SQLHelper.GetNewID(typeof(Model.Environmental_ProjectEnergyReport));
                    report.UpState = BLL.Const.UpState_2;
                    report.FillingMan = this.CurrUser.UserName;
                    BLL.ProjectEnergyReportService.AddEnvironmental_ProjectEnergyReport(report);
                    BLL.LogService.AddSys_Log(this.CurrUser, report.Year.ToString() + "-" + report.Quarters.ToString(), report.EnergyReportId, BLL.Const.ProjectEnergyReportMenuId, BLL.Const.BtnAdd);
                }
                else
                {
                    ShowNotify("该月份记录已存在!", MessageBoxIcon.Warning);
                    return;
                }
            }
            else
            {
                Model.Environmental_ProjectEnergyReport oldReport = BLL.ProjectEnergyReportService.GetEnvironmental_ProjectEnergyReportById(EnergyReportId);
                report.EnergyReportId = EnergyReportId;
                report.UpState = BLL.Const.UpState_2;
                BLL.ProjectEnergyReportService.UpdateEnvironmental_ProjectEnergyReport(report);
                BLL.LogService.AddSys_Log(this.CurrUser, report.Year.ToString() + "-" + report.Quarters.ToString(), report.EnergyReportId, BLL.Const.ProjectEnergyReportMenuId, BLL.Const.BtnModify);
            }
            EnergyReportId = report.EnergyReportId;
            BLL.ProjectEnergyreportItemService.DeleteEnergyReportItemByChemicalReportId(report.EnergyReportId);
            GetItems(report.EnergyReportId);
            ProjectEnergyreportItemService.AddBulkEnvironmental_ProjectEnergyReportItem(items);
            if (type == "updata")     //数据同步
            {
                if (report.UpState == BLL.Const.UpState_2)
                {
                    //string code = CNCECHSSEWebService.UpChemicalReport(report.EnergyReportId, this.CurrUser);
                    //if (code == "1")
                    //{
                    //    ShowNotify("同步成功!", MessageBoxIcon.Success);
                    //    PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                    //    return;
                    //}
                    //else
                    //{
                    //    Alert.ShowInParent("同步异常,请退出后重试!", MessageBoxIcon.Error);
                    //}
                }
                else
                {
                    ShowNotify("当前单据状态不能同步!", MessageBoxIcon.Warning);
                    return;
                }
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Save("add");
            ShowNotify("保存成功!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        protected void btnUpdata_Click(object sender, EventArgs e)
        {
            Save("updata");
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Save("submit");
        }
        #endregion
        #region 增加本月明细
        private void GetItems(string EnergyReportId)
        {
            List newItemLists = new List();
            foreach (JObject mergedRow in Grid1.GetMergedData())
            {
                JObject values = mergedRow.Value("values");
                string sortIndex = values.Value("SortIndex");
                var newItem = items.FirstOrDefault(x => x.SortIndex == sortIndex);
                if (newItem != null)
                {
                    newItem.EnergyReportItemId = SQLHelper.GetNewID();
                    newItem.EnergyReportId = EnergyReportId;
                    newItem.SortIndex = values.Value("SortIndex");
                    newItem.BusinessCategory = values.Value("BusinessCategory");
                    newItem.Throughput_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("Throughput_BasePeriod")).ToString();
                    newItem.Throughput_LastPeriod = Funs.GetNewDecimalOrZero(values.Value("Throughput_LastPeriod")).ToString();
                    newItem.Throughput_ThisPeriod = Funs.GetNewDecimalOrZero(values.Value("Throughput_ThisPeriod")).ToString();
                    newItem.Throughput_UnitOfMeasurement = values.Value("Throughput_UnitOfMeasurement");
                    newItem.Yield_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("Yield_BasePeriod")).ToString();
                    newItem.Yield_LastPeriod = Funs.GetNewDecimalOrZero(values.Value("Yield_LastPeriod")).ToString();
                    newItem.Yield_ThisPeriod = Funs.GetNewDecimalOrZero(values.Value("Yield_ThisPeriod")).ToString();
                    newItem.Yield_UnitOfMeasurement = values.Value("Yield_UnitOfMeasurement");
                    newItem.OutputValue_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("OutputValue_BasePeriod")).ToString();
                    newItem.OutputValue_LastYear = Funs.GetNewDecimalOrZero(values.Value("OutputValue_LastYear")).ToString();
                    newItem.OutputValue_ThisYear = Funs.GetNewDecimalOrZero(values.Value("OutputValue_ThisYear")).ToString();
                    newItem.OperationScale_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("OperationScale_BasePeriod")).ToString();
                    newItem.OperationScale_LastYear = Funs.GetNewDecimalOrZero(values.Value("OperationScale_LastYear")).ToString();
                    newItem.OperationScale_ThisYear = Funs.GetNewDecimalOrZero(values.Value("OperationScale_ThisYear")).ToString();
                    newItem.OperationScale_UnitOfMeasurement = values.Value("OperationScale_UnitOfMeasurement");
                    newItem.ServiceOperatingIncome_BasePeriod = Funs.GetNewDecimalOrZero(values.Value("ServiceOperatingIncome_BasePeriod")).ToString();
                    newItem.ServiceOperatingIncome_LastYear = Funs.GetNewDecimalOrZero(values.Value("ServiceOperatingIncome_LastYear")).ToString();
                    newItem.ServiceOperatingIncome_ThisYear = Funs.GetNewDecimalOrZero(values.Value("ServiceOperatingIncome_ThisYear")).ToString();
                    newItemLists.Add(newItem);
                }
            }
            items = newItemLists;
        }
        #endregion
        #region 获取明细
        private void GetNewItems(string year, string months)
        {
            var indexNames = ProjectEnergyreportItemService.GetItems("Template");
            foreach (var indexName in indexNames)
            {
                //增加明细集合
                Model.Environmental_ProjectEnergyReportItem item = new Environmental_ProjectEnergyReportItem
                {
                    EnergyReportItemId = SQLHelper.GetNewID(typeof(Model.Environmental_ProjectEnergyReportItem)),
                    BusinessCategory = indexName.BusinessCategory,
                    SortIndex = indexName.SortIndex,
                };
                items.Add(item);
            }
        }
        #endregion
        #region 单位下拉选择事件
        /// 
        /// 单位下拉选择事件
        /// 
        /// 
        /// 
        protected void drpUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            items.Clear();
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                //GetNewItems();
            }
            Grid1.DataSource = items;
            Grid1.DataBind();
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.ProjectEnergyReportMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnSave.Hidden = false;
                    //this.btnCopy.Hidden = false;
                }
                //if (buttonList.Contains(BLL.Const.BtnSaveUp))
                //{
                //    this.btnUpdata.Hidden = false;
                //}
            }
        }
        #endregion
        #region 复制上个月数据
        /// 
        /// 复制上个月的数据
        /// 
        /// 
        /// 
        protected void btnCopy_Click(object sender, EventArgs e)
        {
            //DateTime? nowDate = Funs.GetNewDateTime(this.drpYear.SelectedValue + "-" + this.drpMonth.SelectedValue);
            //if (nowDate.HasValue)
            //{
            //    DateTime showDate = new DateTime();
            //    showDate = nowDate.Value.AddMonths(-1);
            //    Model.Environmental_ProjectEnergyReport ChemicalReport = BLL.ProjectEnergyReportService.GetEnvironmental_ProjectEnergyReportByUnitIdAndYearAndMonth(this.drpUnit.SelectedValue, showDate.Year, showDate.Month);
            //    if (ChemicalReport != null)
            //    {
            //        Model.Environmental_ProjectEnergyReport newChemicalReport = new Environmental_ProjectEnergyReport();
            //        this.EnergyReportId = SQLHelper.GetNewID(typeof(Model.Environmental_ProjectEnergyReport));
            //        newChemicalReport.EnergyReportId = this.EnergyReportId;
            //        newChemicalReport.UnitId = this.drpUnit.SelectedValue;
            //        newChemicalReport.Year = Convert.ToInt32(this.drpYear.SelectedValue);
            //        newChemicalReport.Month = Convert.ToInt32(this.drpMonth.SelectedValue);
            //        newChemicalReport.FillingMan = this.CurrUser.UserName;
            //        newChemicalReport.FillingDate = DateTime.Now;
            //        newChemicalReport.DutyPerson = this.CurrUser.UserName;
            //        newChemicalReport.UpState = BLL.Const.UpState_2;
            //        BLL.ProjectEnergyReportService.ad(newChemicalReport);
            //        var oldItems = BLL.ProjectEnergyreportItemService.GetItems(ChemicalReport.EnergyReportId);
            //        if (oldItems.Count > 0)
            //        {
            //            foreach (var item in oldItems)
            //            {
            //                Model.Environmental_ProjectEnergyReportItem newItem = new Environmental_ProjectEnergyReportItem
            //                {
            //                    ChemicalReportItemId = SQLHelper.GetNewID(typeof(Model.Environmental_ProjectEnergyReportItem)),
            //                    EnergyReportId = this.EnergyReportId,
            //                    SortIndex = item.SortIndex,
            //                    LastYearValue = item.LastYearValue,
            //                    ThisYearValue = item.ThisYearValue,
            //                    Rate = item.Rate,
            //                };
            //                BLL.ProjectEnergyreportItemService.AddChemicalReportItem(newItem);
            //            }
            //        }
            //        GetValues(newChemicalReport.EnergyReportId);
            //    }
            //}
        }
        /// 
        /// 获取复制的值绑定到文本中
        /// 
        private void GetValues(string EnergyReportId)
        {
            var report = BLL.ProjectEnergyReportService.GetEnvironmental_ProjectEnergyReportById(EnergyReportId);
            if (report != null)
            {
                drpQuarters.SelectedValue = report.Quarters.ToString();
                drpYear.SelectedValue = report.Year.ToString();
                drpUnit.SelectedValue = report.UnitId;
                if (report.FillingDate != null)
                {
                    txtFillingDate.Text = string.Format("{0:yyyy-MM-dd}", report.FillingDate);
                }
                txtDutyPerson.Text = report.DutyPerson;
                items = BLL.ProjectEnergyreportItemService.GetShowItems(EnergyReportId);
                this.Grid1.DataSource = items;
                this.Grid1.DataBind();
            }
        }
        #endregion
    }
}