using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.ZHGL.Environmental
{
    public partial class OperationReportEdit : PageBase
    {
        #region 定义项
        /// 
        /// 主键
        /// 
        private string BusinessReportId
        {
            get
            {
                return (string)ViewState["BusinessReportId"];
            }
            set
            {
                ViewState["BusinessReportId"] = value;
            }
        }
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BLL.ConstValue.InitConstValueDropDownList(this.drpYear, BLL.ConstValue.Group_0008, true);
                BLL.ConstValue.InitConstValueDropDownList(this.ddlQuarter, BLL.ConstValue.Group_0011, true);
                this.ddlUnitId.DataTextField = "UnitName";
                this.ddlUnitId.DataValueField = "UnitId";
                this.ddlUnitId.DataSource = BLL.UnitService.GetThisUnitDropDownList();
                this.ddlUnitId.DataBind();
                this.ddlUnitId.Readonly = true;
                var year = Request.Params["Year"];
                var quarter = Request.Params["Quarter"];
                string unitId = Request.Params["UnitId"];
                this.drpYear.SelectedValue = year;
                this.ddlQuarter.SelectedValue = quarter;
                if (!string.IsNullOrEmpty(Request.QueryString["type"]))
                {
                    this.btnSave.Hidden = true;
                    this.btnUpdata.Hidden = false;
                }
                else
                {
                    this.btnSave.Hidden = false;
                    this.btnUpdata.Hidden = true;
                }
                ddlUnitId.SelectedValue = CommonService.GetThisUnitId();
                BindGrid(year, quarter, unitId);
                
            }
        }
        private void BindGrid(string year, string quarter, string unitId)
        {
            this.BusinessReportId = Request.Params["BusinessReportId"];
            if (!string.IsNullOrEmpty(this.BusinessReportId))
            {
                var operationReport = Funs.DB.Environmental_OperationReport.FirstOrDefault(s => s.BusinessReportId == this.BusinessReportId);
                if (operationReport != null)
                {
                    #region 赋值
                    if (operationReport.Year != null)
                    {
                        this.drpYear.SelectedValue = operationReport.Year.ToString();
                    }
                    if (operationReport.Quarters != null)
                    {
                        this.ddlQuarter.SelectedValue = operationReport.Quarters.ToString();
                    }
                    if (!string.IsNullOrWhiteSpace(operationReport.FillingMan))
                    {
                        this.txtCompileMan.Text = operationReport.FillingMan.ToString();
                    }
                    //if (!string.IsNullOrWhiteSpace(operationReport.UnitLevel))
                    //{
                    //    this.txtUnitLevel.Text = operationReport.UnitLevel;
                    //}
                    //if (!string.IsNullOrWhiteSpace(operationReport.Place))
                    //{
                    //    this.txtPlace.Text = operationReport.Place;
                    //}
                    if (operationReport.FillingDate != null)
                    {
                        this.txtFillingDate.Text = operationReport.FillingDate.Value.ToString("yyyy-MM-dd");
                    }
                    //if (operationReport.CreateDate != null)
                    //{
                    //    this.txtCreateDate.Text = operationReport.CreateDate.Value.ToString("yyyy-MM-dd");
                    //}
                    //if (!string.IsNullOrWhiteSpace(operationReport.Code))
                    //{
                    //    this.txtCode.Text = operationReport.Code;
                    //}
                    //if (operationReport.PersonNum != null)
                    //{
                    //    this.txtPersonNum.Text = operationReport.PersonNum.ToString();
                    //}
                    //if (operationReport.TotalAssets != null)
                    //{
                    //    this.txtTotalAssets.Text = operationReport.TotalAssets.ToString();
                    //}
                    //if (operationReport.TotalValue != null)
                    //{
                    //    this.txtTotalValue.Text = operationReport.TotalValue.ToString();
                    //}
                    //if (operationReport.NewInvestment != null)
                    //{
                    //    this.txtNewInvestment.Text = operationReport.NewInvestment.ToString();
                    //}
                    this.txtStatisticsDutyPerson.Text = operationReport.StatisticsDutyPerson;
                    this.txtUnitDutyPerson.Text = operationReport.UnitDutyPerson;
                    this.txtRemark.Text = operationReport.Remark;
                    //根据主表id加载子表
                    var reportItem = Funs.DB.Environmental_OperationReportItem.Where(x => x.BusinessReportId == operationReport.BusinessReportId)
                        .OrderBy(x => x.SortIndex).ToList();
                    Grid1.DataSource = reportItem;
                    Grid1.DataBind();
                    #endregion
                }
            }
            else
            {
                #region 不存在则根据项目统计生成
                //this.ddlUnitId.SelectedValue = unitId;
                this.drpYear.SelectedValue = year;
                this.ddlQuarter.SelectedValue = quarter;
                this.txtFillingDate.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                var projects = Funs.DB.Base_Project.Where(s => s.UnitId == unitId).Select(s => s.ProjectId).ToList();
                var items = Funs.DB.Environmental_ProjectOperationReport
                    .Where(s => s.Year.ToString() == year && s.Quarters.ToString() == quarter && projects.Contains(s.ProjectId))
                    .ToList();
                if (items.Any())
                {
                    //this.txtPersonNum.Text = items.Sum(s => s.PersonNum ?? 0).ToString();
                    //this.txtTotalAssets.Text = items.Sum(s => s.TotalAssets ?? 0).ToString();
                    //this.txtTotalValue.Text = items.Sum(s => s.TotalValue ?? 0).ToString();
                    //this.txtNewInvestment.Text = items.Sum(s => s.NewInvestment ?? 0).ToString();
                }
                this.txtCompileMan.Text = this.CurrUser.UserName;
                this.txtStatisticsDutyPerson.Text = this.CurrUser.UserName;
                this.txtUnitDutyPerson.Text = this.CurrUser.UserName;
                //加载子表
                var reportItemlist = new List();
                //第一个本单位
                var isthisUnit = CommonService.GetIsThisUnit();
                var reportItemModel = new Model.Environmental_OperationReportItem() {
                    BusinessReportItemId = Guid.NewGuid().ToString(),
                    SortIndex = 1,
                    UnitName = isthisUnit.UnitName,
                    SortUnitName= isthisUnit.UnitName,
                    Code = isthisUnit.UnitCode,
                    UnitLevel = "",
                    CreateDate=null,
                    Place= isthisUnit.Address,
                    PersonNum=0,
                    TotalAssets=0,
                    TotalValue=0,
                    NewInvestment=0,
                };
                reportItemlist.Add(reportItemModel);
                //加载分单位
                var unitList = Funs.DB.Base_Unit.Where(x => x.IsBranch == true).ToList();
                foreach (var item in unitList)
                {
                    var reportItemModelb = new Model.Environmental_OperationReportItem()
                    {
                        BusinessReportItemId = Guid.NewGuid().ToString(),
                        SortIndex = 1,
                        UnitName = item.UnitName,
                        SortUnitName = isthisUnit.UnitName,
                        Code = item.UnitCode,
                        UnitLevel = "",
                        CreateDate = null,
                        Place = item.Address,
                        PersonNum = 0,
                        TotalAssets = 0,
                        TotalValue = 0,
                        NewInvestment = 0,
                    };
                    reportItemlist.Add(reportItemModelb);
                }
                Grid1.DataSource = reportItemlist;
                Grid1.DataBind();
                #endregion
            }
        }
        #endregion
        #region 保存、提交、关闭
        /// 
        /// 保存按钮
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.drpYear.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("请选择年度", MessageBoxIcon.Warning);
                return;
            }
            if (this.ddlQuarter.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("请选择季度", MessageBoxIcon.Warning);
                return;
            }
            this.SaveData(BLL.Const.BtnSave);
            PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
        }
        /// 
        /// 上报
        /// 
        /// 
        /// 
        protected void btnUpdata_Click(object sender, EventArgs e)
        {
            SaveData("updata");
        }
        /// 
        /// 保存数据
        /// 
        /// 
        private void SaveData(string type)
        {
            Model.Environmental_OperationReport operationReport = new Model.Environmental_OperationReport
            {
                UnitId = this.ddlUnitId.SelectedValue
            };
            if (this.drpYear.SelectedValue != BLL.Const._Null)
            {
                operationReport.Year = Funs.GetNewInt(this.drpYear.SelectedValue);
            }
            if (this.ddlQuarter.SelectedValue != BLL.Const._Null)
            {
                operationReport.Quarters = Funs.GetNewInt(this.ddlQuarter.SelectedValue);
            }
            operationReport.FillingMan = this.txtCompileMan.Text.Trim();
            operationReport.StatisticsDutyPerson = this.txtStatisticsDutyPerson.Text.Trim();
            operationReport.UnitDutyPerson = this.txtUnitDutyPerson.Text.Trim();
            operationReport.FillingDate = Funs.GetNewDateTime(this.txtFillingDate.Text);
            //operationReport.Code = this.txtCode.Text.Trim();
            //operationReport.PersonNum = Funs.GetNewInt(this.txtPersonNum.Text.Trim());
            //operationReport.TotalAssets = Funs.GetNewDecimalOrZero(this.txtTotalAssets.Text.Trim());
            //operationReport.TotalValue = Funs.GetNewDecimalOrZero(this.txtTotalValue.Text.Trim());
            //operationReport.NewInvestment = Funs.GetNewDecimalOrZero(this.txtNewInvestment.Text.Trim());
            //operationReport.UnitLevel = this.txtUnitLevel.Text.Trim();
            //operationReport.CreateDate = Funs.GetNewDateTime(this.txtCreateDate.Text);
            //operationReport.Place = this.txtPlace.Text.Trim();
            operationReport.Remark = this.txtRemark.Text.Trim();
            if (!string.IsNullOrEmpty(this.BusinessReportId))
            {
                var model = Funs.DB.Environmental_OperationReport.FirstOrDefault(s => s.BusinessReportId == this.BusinessReportId);
                if (model != null)
                {
                    //model.Code = operationReport.Code;
                    //model.PersonNum = operationReport.PersonNum;
                    //model.TotalAssets = operationReport.TotalAssets;
                    //model.TotalValue = operationReport.TotalValue;
                    //model.NewInvestment = operationReport.NewInvestment;
                    model.Quarters = operationReport.Quarters;
                    model.Year = operationReport.Year;
                    model.FillingMan = operationReport.FillingMan;
                    model.FillingDate = operationReport.FillingDate;
                    //model.CreateDate = operationReport.CreateDate;
                    //model.Place = operationReport.Place;
                    model.Remark = operationReport.Remark;
                    model.StatisticsDutyPerson = operationReport.StatisticsDutyPerson;
                    model.UnitDutyPerson = operationReport.UnitDutyPerson;
                    operationReport.UpState = model.UpState;
                    operationReport.BusinessReportId = model.BusinessReportId;
                    BLL.LogService.AddSys_Log(this.CurrUser, operationReport.Year.ToString() + "-" + operationReport.Quarters.ToString(), operationReport.BusinessReportId, BLL.Const.OperationReportMenuId, BLL.Const.BtnModify);
                    Funs.DB.SubmitChanges();
                    saveReportItem(operationReport.BusinessReportId);
                }
            }
            else
            {
                var model = (from x in Funs.DB.Environmental_OperationReport
                             where x.UnitId == operationReport.UnitId && x.Year == operationReport.Year && x.Quarters == operationReport.Quarters
                             select x).FirstOrDefault();
                if (model == null)
                {
                    this.BusinessReportId = SQLHelper.GetNewID(typeof(Model.Environmental_ProjectOperationReport));
                    operationReport.BusinessReportId = this.BusinessReportId;
                    operationReport.UpState = Const.UpState_2;
                    Funs.DB.Environmental_OperationReport.InsertOnSubmit(operationReport);
                    BLL.LogService.AddSys_Log(this.CurrUser, operationReport.Year.ToString() + "-" + operationReport.Quarters.ToString(), operationReport.BusinessReportId,
                        BLL.Const.OperationReportMenuId, BLL.Const.BtnAdd);
                    Funs.DB.SubmitChanges();
                    saveReportItem(operationReport.BusinessReportId);
                }
                else
                {
                    Alert.ShowInTop("该季度记录已存在", MessageBoxIcon.Warning);
                    return;
                }
            }
            if (type == "updata")     //数据同步
            {
                if (operationReport.UpState == BLL.Const.UpState_2)
                {
                    string code = CNCECHSSEWebService.UpOperationReport(operationReport.BusinessReportId, this.CurrUser);
                    if (code == "1")
                    {
                        ShowNotify("同步成功!", MessageBoxIcon.Success);
                        PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                        return;
                    }
                    else if (code == "3")
                    {
                        Alert.ShowInParent("集团当前季度数据已锁定,无法上传!", MessageBoxIcon.Error);
                    }
                    else
                    {
                        Alert.ShowInParent("同步异常,请退出后重试!", MessageBoxIcon.Error);
                    }
                }
                else
                {
                    ShowNotify("当前单据状态不能同步!", MessageBoxIcon.Warning);
                    return;
                }
            }
        }
        #endregion
        #region 保存子表
        private void saveReportItem(string BusinessReportId) {
            var list = Funs.DB.Environmental_OperationReportItem.Where(x => x.BusinessReportId == BusinessReportId).ToList();
            //先删除
            if (list.Count>0)
            {
                Funs.DB.Environmental_OperationReportItem.DeleteAllOnSubmit(list);
                Funs.DB.SubmitChanges();
            }
            //再保存
            JArray mergedData = Grid1.GetMergedData();
            var reportItemlist = new List();
            var isthisUnit = CommonService.GetIsThisUnit();
            foreach (var item in mergedData)
            {
                JObject values = item.Value("values");
                int i = item.Value("index");
                var model = new Model.Environmental_OperationReportItem() { 
                    BusinessReportItemId= Grid1.Rows[i].DataKeys[0].ToString(),
                    BusinessReportId= BusinessReportId,
                    SortIndex= i+1,
                    UnitName = values.Value("UnitName").ToString(),
                    SortUnitName= isthisUnit.UnitName,
                    Code= values.Value("Code").ToString(),
                    UnitLevel= values.Value("UnitLevel").ToString(),
                    Place= values.Value("Place").ToString(),
                    PersonNum= values.Value("PersonNum"),
                    TotalAssets= values.Value("TotalAssets"),
                    TotalValue = values.Value("TotalValue"),
                    NewInvestment = values.Value("NewInvestment"),
                };
                if (!string.IsNullOrEmpty(values.Value("CreateDate").ToString()))
                {
                    model.CreateDate = Convert.ToDateTime(values.Value("CreateDate").ToString());
                }
                reportItemlist.Add(model);
            }
            Funs.DB.Environmental_OperationReportItem.InsertAllOnSubmit(reportItemlist);
            Funs.DB.SubmitChanges();
        }
        #endregion
        #region 年季度变化事件
        /// 
        /// 年季度变化事件
        /// 
        /// 
        /// 
        protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.drpYear.SelectedValue != BLL.Const._Null && this.ddlQuarter.SelectedValue != BLL.Const._Null)
            {
                BindGrid(this.drpYear.SelectedValue, this.ddlQuarter.SelectedValue, Request.Params["unitId"]);
            }
        }
        #endregion
    }
}