using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using AspNet = System.Web.UI.WebControls;
namespace FineUIPro.Web.ZHGL.Information
{
    public partial class ActionWorkLedger : PageBase
    {
        #region 定义变量
        /// 
        /// 主键
        /// 
        public string ActionWorkLedgerId
        {
            get
            {
                return (string)ViewState["ActionWorkLedgerId"];
            }
            set
            {
                ViewState["ActionWorkLedgerId"] = value;
            }
        }
        /// 
        /// 定义集合
        /// 
        private static List ActionWorkLedgerItems = new List();
        #endregion
        #region 加载页面
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BLL.ConstValue.InitConstValueDropDownList(this.drpQuarter, 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;
                DateTime showDate = System.DateTime.Now.AddMonths(-3);
                this.drpQuarter.SelectedValue = Funs.GetNowQuarterlyByTime(showDate).ToString();
                this.drpYear.SelectedValue = showDate.Year.ToString();
                GetValue();
            }
        }
        #endregion
        #region 清空文本框
        private void SetEmpty()
        {
            this.SimpleForm1.Title = string.Empty;
            txtUnitName.Text = string.Empty;
            txtQuarter.Text = string.Empty;
            txtCompileDate.Text = string.Empty;
            this.lbHandleMan.Text = string.Empty;
            Grid1.DataSource = null;
            Grid1.DataBind();
        }
        #endregion
        #region 获取记录值
        private void GetValue()
        {
            int year = Funs.GetNewIntOrZero(drpYear.SelectedValue);
            int quarter = Funs.GetNewIntOrZero(drpQuarter.SelectedValue);
            this.ActionWorkLedgerId = string.Empty;
            Model.View_Information_ActionWorkLedger report = Funs.DB.View_Information_ActionWorkLedger.FirstOrDefault(e => e.UnitId == drpUnit.SelectedValue && e.Quarter == quarter && e.YearId == year);
            if (report != null)
            {
                string state = string.Empty;
                if (report.UpState == BLL.Const.UpState_3)
                {
                    state = "(已上报)";
                }
                else
                {
                    if (report.HandleState == BLL.Const.HandleState_1)
                    {
                        state = "(待提交)";
                    }
                    else if (report.HandleState == BLL.Const.HandleState_2)
                    {
                        state = "(待审核)";
                    }
                    else if (report.HandleState == BLL.Const.HandleState_3)
                    {
                        state = "(待审批)";
                    }
                    else if (report.HandleState == BLL.Const.HandleState_4)
                    {
                        state = "(待上报)";
                    }
                }
                this.SimpleForm1.Title = "安全生产治本攻坚三年行动工作台账" + state;
                this.ActionWorkLedgerId = report.ActionWorkLedgerId;
                txtUnitName.Text = "单位:" + report.UnitName;
                txtQuarter.Text = "季度:" + report.Quarters;
                if (report.HandleState == BLL.Const.HandleState_1 || report.UpState == BLL.Const.UpState_3)
                {
                    this.lbHandleMan.Hidden = true;
                }
                else
                {
                    this.lbHandleMan.Hidden = false;
                    this.lbHandleMan.Text = "下一步办理人:" + report.UserName;
                }
                if (report.ReportDate != null)
                {
                    txtCompileDate.Text = "制表时间:" + string.Format("{0:yyyy-MM-dd}", report.ReportDate);
                }
                BindGrid1();
            }
            else
            {
                SetEmpty();
            }
            this.GetButtonPower();
        }
        #endregion
        #region 加载Grid
        private void BindGrid1()
        {
            string strSql = "select * from dbo.Information_ActionWorkLedgerItem where ActionWorkLedgerId = @ActionWorkLedgerId order by SortIndex";
            SqlParameter[] parameter = new SqlParameter[]
                    {
                        new SqlParameter("@ActionWorkLedgerId",this.ActionWorkLedgerId),
                    };
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            //tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion
        #region 增加、修改、删除、审核、审批、上报按钮事件
        /// 
        /// Tree增加按钮
        /// 
        /// 
        /// 
        protected void btnNew_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("ActionWorkLedgerAdd.aspx?UnitId={0}&&Year={1}&&Quarter={2}", this.CurrUser.UnitId, this.drpYear.SelectedValue, this.drpQuarter.SelectedValue, "编辑 - ")));
        }
        /// 
        /// 显示编辑页面
        /// 
        private void ShowEdit()
        {
            Model.Information_ActionWorkLedger report = BLL.ActionWorkLedgerService.GetActionWorkLedgerByUnitIdAndYearAndQuarters(drpUnit.SelectedValue, Funs.GetNewIntOrZero(drpYear.SelectedValue), Funs.GetNewIntOrZero(drpQuarter.SelectedValue));
            if (report == null)
            {
                Alert.ShowInTop("所选时间无报表记录!", MessageBoxIcon.Warning);
                return;
            }
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("ActionWorkLedgerAdd.aspx?ActionWorkLedgerId={0}", report.ActionWorkLedgerId, "编辑 - ")));
        }
        /// 
        /// Tree编辑按钮
        /// 
        /// 
        /// 
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            ShowEdit();
        }
        /// 
        /// 审核
        /// 
        /// 
        /// 
        protected void btnAudit1_Click(object sender, EventArgs e)
        {
            ShowEdit();
        }
        /// 
        /// 审批
        /// 
        /// 
        /// 
        protected void btnAudit2_Click(object sender, EventArgs e)
        {
            ShowEdit();
        }
        /// 
        /// 上报
        /// 
        /// 
        /// 
        protected void btnUpdata_Click(object sender, EventArgs e)
        {
            ShowEdit();
        }
        /// 
        /// Tree删除按钮
        /// 
        /// 
        /// 
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Model.Information_ActionWorkLedger report = BLL.ActionWorkLedgerService.GetActionWorkLedgerByUnitIdAndYearAndQuarters(drpUnit.SelectedValue, Funs.GetNewIntOrZero(drpYear.SelectedValue), Funs.GetNewIntOrZero(drpQuarter.SelectedValue));
            if (report != null)
            {
                BLL.LogService.AddSys_Log(this.CurrUser, report.YearId.ToString() + "-" + report.Quarter.ToString(),
                        report.ActionWorkLedgerId, BLL.Const.ActionWorkLedgerMenuId, BLL.Const.BtnDelete);
                BLL.ProjectDataFlowSetService.DeleteFlowSetByDataId(report.ActionWorkLedgerId);
                BLL.ActionWorkLedgerItemService.DeleteActionWorkLedgerItemList(report.ActionWorkLedgerId);
                BLL.ActionWorkLedgerService.DeleteActionWorkLedgerById(report.ActionWorkLedgerId);
                SetEmpty();
                //this.btnNew.Hidden = false;
                ShowNotify("删除数据成功!", MessageBoxIcon.Success);
            }
            else
            {
                ShowNotify("所选时间无报表记录!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 过滤、分页、排序、关闭窗口
        /// 
        /// 表头过滤
        /// 
        /// 
        /// 
        protected void Grid1_FilterChange(object sender, EventArgs e)
        {
            BindGrid1();
        }
        /// 
        /// 分页
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid1();
        }
        /// 
        /// Grid1排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid1();
        }
        /// 
        /// 分页列表显示条数下拉选择事件
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
        /// 
        /// 关闭Grid1弹出窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            GetValue();
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.ActionWorkLedgerMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    //this.btnNew.Hidden = false;
                    this.btnGet.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnEdit.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnDelete.Hidden = false;
                }
                //if (buttonList.Contains(BLL.Const.BtnPrint))
                //{
                //    this.btnPrint.Hidden = false;
                //}
                int year = Funs.GetNewIntOrZero(this.drpYear.SelectedValue);
                int quarter = Funs.GetNewIntOrZero(this.drpQuarter.SelectedValue);
                var report = BLL.ActionWorkLedgerService.GetActionWorkLedgerByUnitIdAndYearAndQuarters(this.drpUnit.SelectedValue, year, quarter);
                this.btnAudit1.Hidden = true;
                this.btnAudit2.Hidden = true;
                this.btnUpdata.Hidden = true;
                if (report != null)
                {
                    this.btnNew.Hidden = true;
                    if (report.HandleMan == this.CurrUser.UserId)   //当前人是下一步办理入
                    {
                        if (report.HandleState == BLL.Const.HandleState_2)
                        {
                            this.btnAudit1.Hidden = false;
                        }
                        else if (report.HandleState == BLL.Const.HandleState_3)
                        {
                            this.btnAudit2.Hidden = false;
                        }
                        else if (report.HandleState == BLL.Const.HandleState_4)
                        {
                            this.btnDelete.Hidden = true;
                            this.btnUpdata.Hidden = false;
                        }
                    }
                    if (report.UpState == BLL.Const.UpState_3)
                    {
                        this.btnUpdata.Hidden = true;
                        this.btnEdit.Hidden = true;
                        this.btnDelete.Hidden = true;
                    }
                    if (report.HandleMan == this.CurrUser.UserId || report.CompileMan == this.CurrUser.UserName)
                    {
                        this.btnEdit.Hidden = false;
                    }
                    else
                    {
                        this.btnEdit.Hidden = true;
                    }
                }
            }
            if (this.CurrUser.UserId == BLL.Const.sysglyId)
            {
                this.btnDelete.Hidden = false;
            }
        }
        #endregion
        #region 单位下拉框联动事件
        /// 
        /// 单位下拉框联动事件
        /// 
        /// 
        /// 
        protected void drpUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetValue();
        }
        #endregion
        #region 获取
        /// 
        /// 获取按钮
        /// 
        /// 
        /// 
        protected void btnGet_Click(object sender, EventArgs e)
        {
            Model.Information_ActionWorkLedger report = BLL.ActionWorkLedgerService.GetActionWorkLedgerByUnitIdAndYearAndQuarters(drpUnit.SelectedValue, Funs.GetNewIntOrZero(drpYear.SelectedValue), Funs.GetNewIntOrZero(drpQuarter.SelectedValue));
            if (report == null)
            {
                var returnValue = getActionWorkLedgerToSUB();
                if (returnValue.code == 1)
                {
                    ShowNotify(returnValue.message, MessageBoxIcon.Success);
                    GetValue();
                }
                else
                {
                    Alert.ShowInTop(returnValue.message, MessageBoxIcon.Warning);
                }
            }
            else
            {
                Alert.ShowInTop("该季度记录已存在,无需获取!", MessageBoxIcon.Warning);
            }
        }
        /// 
        ///  获取
        /// 
        /// 
        /// 
        public Model.ResponeData getActionWorkLedgerToSUB()
        {
            var responeData = new Model.ResponeData();
            try
            {
                string unitId = CommonService.GetThisUnitId();
                string baseurl = SysConstSetService.CNCECPath + "/api/HSSEData/getActionWorkLedger?year=" + this.drpYear.SelectedValue + "&quarter=" + this.drpQuarter.SelectedValue;
                string contenttype = "application/json;charset=unicode";
                Hashtable newToken = new Hashtable
                {
                    { "token", ServerService.GetToken().Token }
                };
                var strJosn = APIGetHttpService.Http(baseurl, "GET", contenttype, newToken, null);
                if (!string.IsNullOrEmpty(strJosn))
                {
                    JObject obj = JObject.Parse(strJosn);
                    responeData.code = Funs.GetNewIntOrZero(obj["code"].ToString());
                    responeData.message = obj["message"].ToString();
                    if (responeData.code == 1)
                    {
                        JArray getData = JArray.Parse(obj["data"].ToString());
                        if (getData.Count() > 0)
                        {
                            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
                            {
                                int i = 0;
                                string actionWorkLedgerId = SQLHelper.GetNewID();
                                foreach (var item in getData)
                                {
                                    if (i == 0)
                                    {
                                        Model.Information_ActionWorkLedger actionWorkLedger = new Model.Information_ActionWorkLedger();
                                        actionWorkLedger.ActionWorkLedgerId = actionWorkLedgerId;
                                        actionWorkLedger.UnitId = BLL.CommonService.GetThisUnitId();
                                        actionWorkLedger.ReportDate = DateTime.Now;
                                        actionWorkLedger.Quarter = Funs.GetNewInt(this.drpQuarter.SelectedValue);
                                        actionWorkLedger.YearId = Funs.GetNewInt(this.drpYear.SelectedValue);
                                        actionWorkLedger.CompileMan = this.CurrUser.UserName;
                                        actionWorkLedger.UpState = BLL.Const.UpState_2;
                                        actionWorkLedger.HandleState = BLL.Const.HandleState_1;
                                        actionWorkLedger.HandleMan = this.CurrUser.UserId;
                                        BLL.ActionWorkLedgerService.AddActionWorkLedger(actionWorkLedger);
                                    }
                                    Model.Information_ActionWorkLedgerItem newItem = new Model.Information_ActionWorkLedgerItem();
                                    newItem.ActionWorkLedgerItemId = SQLHelper.GetNewID();
                                    newItem.ActionWorkLedgerId = actionWorkLedgerId;
                                    newItem.SortIndex = Funs.GetNewInt(item["SortIndex"].ToString());
                                    newItem.Focus = item["Focus"].ToString();
                                    newItem.SpecialTask = item["SpecialTask"].ToString();
                                    newItem.WorkPoints = item["WorkPoints"].ToString();
                                    newItem.FillingRequirements = item["FillingRequirements"].ToString();
                                    newItem.CompletionDeadline = item["CompletionDeadline"].ToString();
                                    BLL.ActionWorkLedgerItemService.AddActionWorkLedgerItem(newItem);
                                    i++;
                                }
                            }
                            responeData.message = "获取成功!";
                        }
                        else
                        {
                            responeData.code = 0;
                            responeData.message = "集团记录尚未生成!";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                responeData.code = 0;
                responeData.message = "获取失败:" + ex.Message;
                ErrLogInfo.WriteLog("安全生产治本攻坚三年行动工作台账获取!", ex);
            }
            return responeData;
        }
        #endregion
        #region 关闭导入弹出窗口
        /// 
        /// 关闭导入弹出窗口
        /// 
        /// 
        /// 
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            GetValue();
        }
        /// 
        /// 关闭查看审批信息弹出窗口
        /// 
        /// 
        /// 
        protected void Window4_Close(object sender, WindowCloseEventArgs e)
        {
        }
        #endregion
        #region 打印
        /// 
        /// 打印
        /// 
        /// 
        /// 
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            //Model.Information_ActionWorkLedger report = BLL.ActionWorkLedgerService.GetActionWorkLedgerByUnitIdAndYearAndQuarters(drpUnit.SelectedValue, Funs.GetNewIntOrZero(drpYear.SelectedValue), Funs.GetNewIntOrZero(drpQuarter.SelectedValue));
            //if (report != null)
            //{
            //    PageContext.RegisterStartupScript(Window3.GetShowReference(String.Format("../../ReportPrint/ExReportPrint.aspx?reportId={0}&&replaceParameter={1}&&varValue={2}", Const.Information_ActionWorkLedgerId, report.ActionWorkLedgerId, "", "打印 - ")));
            //}
        }
        #endregion
        #region 季度向前/向后
        /// 
        /// 前一季度
        /// 
        /// 
        /// 
        protected void BtnBulletLeft_Click(object sender, EventArgs e)
        {
            SetMonthChange("-");
        }
        /// 
        /// 后一季度
        /// 
        /// 
        /// 
        protected void BulletRight_Click(object sender, EventArgs e)
        {
            SetMonthChange("+");
        }
        /// 
        /// 季度加减变化
        /// 
        /// 
        private void SetMonthChange(string type)
        {
            DateTime? nowDate = Funs.GetNewDateTime(this.drpYear.SelectedValue + "-" + (Funs.GetNewIntOrZero(this.drpQuarter.SelectedValue) * 3).ToString());
            if (nowDate.HasValue)
            {
                DateTime showDate = new DateTime();
                if (type == "+")
                {
                    showDate = nowDate.Value.AddMonths(3);
                }
                else
                {
                    showDate = nowDate.Value.AddMonths(-3);
                }
                this.drpYear.SelectedValue = showDate.Year.ToString();
                this.drpQuarter.SelectedValue = Funs.GetNowQuarterlyByTime(showDate).ToString();
                ///值变化
                GetValue();
            }
        }
        #endregion
        #region 查看审批信息
        /// 
        /// 查看审批信息
        /// 
        /// 
        /// 
        protected void btnSee_Click(object sender, EventArgs e)
        {
            Model.Information_ActionWorkLedger report = BLL.ActionWorkLedgerService.GetActionWorkLedgerByUnitIdAndYearAndQuarters(drpUnit.SelectedValue, Funs.GetNewIntOrZero(drpYear.SelectedValue), Funs.GetNewIntOrZero(drpQuarter.SelectedValue));
            if (report != null)
            {
                PageContext.RegisterStartupScript(Window4.GetShowReference(String.Format("ReportAuditSee.aspx?Id={0}", report.ActionWorkLedgerId, "查看 - ")));
            }
            else
            {
                ShowNotify("所选月份无记录!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 导出按钮
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            string filename = Funs.GetNewFileName();
            Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("安全生产治本攻坚三年行动工作台账" + filename, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentType = "application/excel";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Write(GetGridTableHtml(Grid1));
            Response.End();
        }
        #endregion
    }
}