using BLL;
using Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using BLL.OfficeCheck.Inspect;
using NPOI.SS.Formula.Functions;
using System.Data.SqlClient;
namespace FineUIPro.Web.OfficeCheck.Inspect
{
    public partial class SafetyInspectionEdit : PageBase
    {
        #region 定义变量
        /// 
        /// 主键
        /// 
        public string InspectionId
        {
            get
            {
                return (string)ViewState["InspectionId"];
            }
            set
            {
                ViewState["InspectionId"] = value;
            }
        }
        /// 
        /// 项目主键
        /// 
        public string ProjectId
        {
            get
            {
                return (string)ViewState["ProjectId"];
            }
            set
            {
                ViewState["ProjectId"] = value;
            }
        }
        public string PhotoUrl
        {
            get
            {
                return (string)ViewState["PhotoUrl"];
            }
            set
            {
                ViewState["PhotoUrl"] = value;
            }
        }
        public string VideoUrl
        {
            get
            {
                return (string)ViewState["VideoUrl"];
            }
            set
            {
                ViewState["VideoUrl"] = value;
            }
        }
        
        #endregion
        
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
                this.btnMenuRectify.Hidden = false;
                this.btnMenuShow.Hidden = false;
                this.btnClose.OnClientClick = ActiveWindow.GetHideReference();
                this.ProjectId = Request.Params["ProjectId"];
                UserService.InitUserDropDownList(this.drpPersonResponsible, this.ProjectId, true);        
                this.dpkInspectTime.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                BindGrid();
            }
        }
        #endregion
        
        
        /// 
        /// 绑定数据
        /// 
        private void BindGrid()
        {
            this.InspectionId = Request.Params["InspectionId"];
            var Inspection = Inspect_InspectionService.GetInspectionByInspectionId(this.InspectionId);
            if (Inspection != null)
            {
                this.ProjectId = Inspection.ProjectId;
                if (this.ProjectId != this.CurrUser.LoginProjectId)
                {
                    this.InitDropDownList();
                }
                txtInspectionCode.Text = Inspection.InspectionCode;
                txtDescription.Text = Inspection.Description;
                this.drpPersonResponsible.SelectedValue = Inspection.PersonResponsible;
                if (Inspection.InspectTime != null)
                {
                    this.dpkInspectTime.Text = string.Format("{0:yyyy-MM-dd}", Inspection.InspectTime);
                }
                //获取明细
                string strSql =
                    @"select item.InspectionItemId,item.InspectionId,item.InspectionDescribe,item.PhotoUrl,item.VideoUrl,item.EvaluateResults,item.TimeLimited,item.RectificationDescription,"
                    + @" (CASE WHEN item.RectificationResults ='1' THEN '同意' 
                              WHEN item.RectificationResults ='2' THEN '不同意' 
                                ELSE '' END) AS RectificationResults, "
                    + @" (CASE WHEN item.States ='1' THEN '待评价' 
                              WHEN item.States ='2' THEN '待整改' 
                              WHEN item.States ='3' THEN '已整改待复查' 
                              WHEN item.States ='5' THEN '已闭环' 
                                ELSE '' END) AS States, "
                    + @" item.CompileMan ,item.CompileTime,item.RectificationPhotoUrl  from Inspect_InspectionItem item  where 1=1 ";
                List listStr = new List();
                if (!string.IsNullOrEmpty(this.InspectionId))
                {
                    strSql += " AND item.InspectionId = @InspectionId";
                    listStr.Add(new SqlParameter("@InspectionId", this.InspectionId));
                }
                SqlParameter[] parameter = listStr.ToArray();
                DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
               
                Grid1.RecordCount = tb.Rows.Count;
                var table = this.GetPagedDataTable(Grid1, tb);
                Grid1.DataSource = table;
                Grid1.DataBind();
                
            }
            else
            {
                ////自动生成编码
                this.dpkInspectTime.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
            }
                
            var val = Inspect_InspectionService.GetInspectionByInspectionId(this.InspectionId);
            if (val.States == "5")
            {
                this.btnSave.Hidden = true;
            }
        }
        
        /// 
        ///  初始化下拉框
        /// 
        private void InitDropDownList()
        {
            //检查组成员
            UserService.InitUserDropDownList(this.drpPersonResponsible, this.ProjectId, true);           
        }
        
        
       
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string itemId = string.Empty;
            if (e.CommandName == "PhotoUrl")
            {
                itemId = Grid1.DataKeys[e.RowIndex][0].ToString() + "_1";
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format(
                    "../../AttachFile/webuploader.aspx?toKeyId={0}&path=FileUpload/InspectionItem&menuId={1}", itemId,
                    BLL.Const.ProjectSafetyInspectionMenuId)));
                this.PhotoUrl = itemId;
            }
            else if (e.CommandName == "VideoUrl")
            {
                itemId = Grid1.DataKeys[e.RowIndex][0].ToString() + "_2";
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format(
                    "../../AttachFile/webuploader.aspx?toKeyId={0}&path=FileUpload/InspectionItem&menuId={1}",
                    itemId + "_2", BLL.Const.ProjectSafetyInspectionMenuId)));
                this.VideoUrl = itemId;
            }
        }
        
        /// 
        ///  点击客户端事件
        /// 
        /// 
        /// 
        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 设置LinkButtonField的点击客户端事件
            LinkButtonField deleteField = Grid1.FindColumn("Delete") as LinkButtonField;
        }
        
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            
            
        }
        
        /// 
        /// 保存按钮
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.SaveData(Const.BtnSave);
            
        }
        
        #region 保存方法
        /// 
        /// 保存数据
        /// 
        /// 
        private void SaveData(string type)
        {
            Model.Inspect_Inspection inspection = new Inspect_Inspection();
            
            //主表数据赋值
            if (!string.IsNullOrEmpty(this.txtInspectionCode.Text.Trim()))
            {
                inspection.InspectionCode = this.txtInspectionCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(this.txtDescription.Text.Trim()))
            {
                inspection.Description = this.txtDescription.Text.Trim();
            }
            if (this.drpPersonResponsible.SelectedValue != BLL.Const._Null)
            {
                inspection.PersonResponsible = this.drpPersonResponsible.SelectedValue;
            }
            if (!string.IsNullOrEmpty(this.dpkInspectTime.Text.Trim()))
            {
                inspection.InspectTime = DateTime.Parse(this.dpkInspectTime.Text.Trim());
            }
            
            //判断是否有主键
            if (string.IsNullOrEmpty(this.InspectionId))
            {
                //新增
                inspection.InspectionId = Guid.NewGuid().ToString();
                inspection.ProjectId = this.ProjectId;
                inspection.InspectType = "1";
                inspection.States = "1";
                inspection.CreateMan = this.CurrUser.UserId;
                inspection.CreateTime = DateTime.Now;
                Inspect_InspectionService.SaveInspection(inspection);
            }
            var val = Inspect_InspectionService.GetInspectionByInspectionId(this.InspectionId);
            //明细数据赋值
            JArray data = Grid1.GetMergedData();
            //判断是否有明细数据
            //if (data.Count > 0)
            //{
            //    foreach (var item in data)
            //    {
            //        JObject values = item.Value("values");
            //        string id = item.Value("id");
            //        var InspectItems = Inspect_InspectionService.GetInspectItemsById(id);
            //        if (InspectItems != null)
            //        {
            //            var evaluateResults = values.Value("EvaluateResults");
            //            if (!string.IsNullOrEmpty(evaluateResults))
            //            {
            //                InspectItems.EvaluateResults = evaluateResults.Trim();
            //                if (evaluateResults == "合格")
            //                {
            //                    InspectItems.States = "5"; //闭环
            //                }
            //                else if (evaluateResults == "不合格")
            //                {
            //                    InspectItems.States = "2"; //已评价
            //                }
                            
            //            }
            //            if (!string.IsNullOrEmpty(values.Value("TimeLimited")))
            //            {
            //                InspectItems.TimeLimited = values.Value("TimeLimited");
            //            }
            //            else
            //            {
            //                InspectItems.TimeLimited = null;
            //            }
            //            //if (!string.IsNullOrEmpty(values.Value("RectificationDescription")))
            //            //{
            //            //    //有整改描述  是不合格的复查提交
            //            //    InspectItems.RectificationDescription =
            //            //        values.Value("RectificationDescription").Trim();
            //            //}
            //            //else
            //            //{
            //            //    InspectItems.RectificationDescription = "";
            //            //}
            //            // if (!string.IsNullOrEmpty(values.Value("RectificationResults")))
            //            // {
            //            //     InspectItems.RectificationResults = values.Value("RectificationResults");
            //            // }
            //            //编辑
            //            Inspect_InspectionService.UpdateInspectionItem(InspectItems);
            //        }
                    
            //    }
                
            //    // 修改主表状态
            //    var InspectItemsList = Inspect_InspectionService.GetInspectItemsByInspectionId(this.InspectionId);
                
            //    HashSet list = new HashSet();
            //    foreach (var item in InspectItemsList)
            //    {
            //        list.Add(item.EvaluateResults);
            //    }
            //    if (val.States != "1")
            //    {
            //        var states = "3";
            //        if (list.Count() == 1)
            //        {
            //            if (list.Contains("合格"))
            //            {
            //                states = "5";
            //            }
            //            else if (list.Contains("不合格"))
            //            {
            //                states = "3";
            //            }
            //            else
            //            {
            //                states = "2";
            //            }
            //        }
            //        Inspect_InspectionService.UpdateInspectionStates(this.InspectionId,states);
            //    }
                
                
            //}
            //else
            //{
            //    // 修改主表状态
            //    if (!string.IsNullOrEmpty(this.InspectionId))
            //    {
                    
            //        //编辑
            //        inspection.InspectionId = this.InspectionId;
            //        inspection.States = val.States;
            //        Inspect_InspectionService.UpdateInspection(inspection);
            //    }
            //}
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion
        
        
       
        
        /// 
        /// 责任人下拉框选择改变事件,去除下拉框中的空值选项。
        /// 
        /// 
        /// 
        protected void drpPersonResponsible_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.drpPersonResponsible.SelectedValueArray = Funs.RemoveDropDownListNull(this.drpPersonResponsible.SelectedValueArray);
        }
        /// 
        /// 责任人下拉框选择改变事件,去除下拉框中的空值选项。
        /// 
        /// 
        /// 
        protected void drpddlEvaluateResults(object sender, EventArgs e)
        {
            if (this.ddlEvaluateResults.SelectedValue == "不合格")
            {
                //改限时时间
            }
            else
            {
                
            }
        }
        
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
            ShowNotify("操作成功!", MessageBoxIcon.Success);
        }
        
        protected void btnRectify_Click(object sender, EventArgs e)
        {
            //获取当前数据的明细
            var register = Inspect_InspectionService.GetInspectItemsById(this.Grid1.SelectedRowID);
            //if (register.EvaluateResults == "合格")
            //{
            //    Alert.ShowInTop("当前项已合格,无需整改!", MessageBoxIcon.Warning);
            //    return;
            //}
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("SafetyInspectionRectify.aspx?InspectionItemId={0}&type={1}", this.Grid1.SelectedRowID,'0', "编辑 - ")));
            
        }
        protected void btnShow_Click(object sender, EventArgs e)
        {
           
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("SafetyInspectionRectify.aspx?InspectionItemId={0}&type={1}", this.Grid1.SelectedRowID,'1', "查看 - ")));
            
        }
        
    }
}