using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using BLL;
namespace FineUIPro.Web.CQMS.Check
{
    public partial class JointCheckChartStatistics : PageBase
    {
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.txtStartRectificationTime.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                this.txtEndRectificationTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
                this.AnalyseData();
        }
        #endregion
        #region 统计
        /// 
        /// 统计分析
        /// 
        /// 
        /// 。
        protected void BtnAnalyse_Click(object sender, EventArgs e)
        {
            this.AnalyseData();
            PageContext.RegisterStartupScript(@" setTimeout(function () { rendChart(" + legend+","+xAxis+","+series+ ");},1000);  ");
          
        }
        public string legend = "[]";
        public string xAxis="[]";
        public string series="[]";
        /// 
        /// 统计方法
        /// 
        private void AnalyseData()
        {
            if (this.rblState.SelectedValue == "0")
            {
                string strSql = @" select UnitId,unitName,
                             Sum(case when OK='0' then 1 else 0 end) as todo,
                             Sum(case when OK='1' then 1 else 0 end) as finish
                             from View_Check_JointCheckDetail 
                             where ProjectId=@ProjectId  
                            ";
                if (!string.IsNullOrEmpty(this.txtStartRectificationTime.Text.Trim()))
                {
                    strSql += " and CheckDate >='" + this.txtStartRectificationTime.Text.Trim() + "' ";
                }
                if (!string.IsNullOrEmpty(this.txtEndRectificationTime.Text.Trim()))
                {
                    strSql += " and CheckDate <'" + DateTime.Parse(  this.txtEndRectificationTime.Text.Trim()).AddDays(1).ToString("yyyy-MM-dd") + "' ";
                }
                strSql += " group by UnitId,unitName ";
                List listStr = new List();
                listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
                SqlParameter[] parameter = listStr.ToArray();
                DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
                legend = "[ \"未闭合\", \"已闭合\"]";
                xAxis = "[";
                
                string series2 = "[";
                string series3 = "[";
                foreach (DataRow dr in tb.Rows)
                {
                    xAxis += "\"" + dr["unitName"].ToString() + "\",";
                    series2 += "" + dr["todo"].ToString() + ",";
                    series3 += "" + dr["finish"].ToString() + ",";
                }
                xAxis = xAxis.TrimEnd(',');
                xAxis += "]";
               
                series2 = series2.TrimEnd(',');
                series2 += "]";
                series3 = series3.TrimEnd(',');
                series3 += "]";
                series = @"[
                            {
                                name: '未闭合',
                                type: 'bar', 
                                barWidth: 20,
                                label: {
                                        show: true,
                                        position: 'top'
                                        },
                                emphasis: {
                                    focus: 'series'
                                },
                                data: " + series2 + @"
                            },
                            {
                                name: '已闭合',
                                type: 'bar', 
                                label: {
                                        show: true,
                                        position: 'top'
                                        },
                                barWidth: 20,
                                emphasis: {
                                    focus: 'series'
                                },
                                data: " + series3 + @"
                            }]";
            }
            else
            {
                string strSql = @" select QuestionDef,QuestionTypeStr,
                             count(*) as count
                             from View_Check_JointCheckDetail 
                             where ProjectId=@ProjectId
                              ";
                if (!string.IsNullOrEmpty(this.txtStartRectificationTime.Text.Trim()))
                {
                    strSql += " and CheckDate >='" + this.txtStartRectificationTime.Text.Trim() + "' ";
                }
                if (!string.IsNullOrEmpty(this.txtEndRectificationTime.Text.Trim()))
                {
                    strSql += " and CheckDate <'" + DateTime.Parse(this.txtEndRectificationTime.Text.Trim()).AddDays(1).ToString("yyyy-MM-dd") + "' ";
                }
                strSql += " group by QuestionDef,QuestionTypeStr ";
                List listStr = new List();
                listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
                SqlParameter[] parameter = listStr.ToArray();
                DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
                Dictionary> data = new Dictionary>();
                legend = "[";
                xAxis = "[";
                HashSet xdic = new HashSet();
                HashSet unitdic = new HashSet();
                foreach (DataRow dr in tb.Rows)
                {
                    //if (dr["QuestionDef"].ToString().Length > 20)
                    //{
                    //    dr["QuestionDef"] = dr["QuestionDef"].ToString().Substring(0, 20);
                    //}
                    xdic.Add(dr["QuestionTypeStr"].ToString());
                    unitdic.Add(dr["QuestionDef"].ToString());
                    Dictionary temp = null;
                    if (!data.ContainsKey(dr["QuestionDef"].ToString()))
                    {
                        data.Add(dr["QuestionDef"].ToString(), new Dictionary());
                    }
                    temp = data[dr["QuestionDef"].ToString()];
                    if (!temp.ContainsKey(dr["QuestionTypeStr"].ToString()))
                    {
                        temp.Add(dr["QuestionTypeStr"].ToString(), "0");
                    }
                    temp[dr["QuestionTypeStr"].ToString()] = dr["count"].ToString();
                }
                foreach (string types in xdic)
                {
                    xAxis += "\"" + types + "\",";
                }
                //xAxis = xAxis.TrimEnd(',');
                xAxis += "]";
                //foreach (string types in unitdic)
                //{
                   
                    
                //    legend += "\"" + types + "\",";
                //}
                //legend = legend.TrimEnd(',');
                legend += "]";
                series = "[";
                foreach (string unit in data.Keys)
                {
                    string tempseries = "";
                    foreach (string types in xdic)
                    {
                        if (data[unit].ContainsKey(types))
                        {
                            tempseries += "" + data[unit][types] + ",";
                        }
                        else
                        {
                            tempseries += ",";
                        }
                    }
                    //stack: '未闭合',
                    series += @"{
                                name: '"+ unit.Replace("\n","").Replace("\r", "") + @"',
                                type: 'bar',
                                
                                barWidth: 10,
                                
                                label: {
                                            show: true,
                                            position: 'top'
                                        },
                                emphasis: {
                                    focus: 'series'
                                },
                                data: [" + tempseries+ @"] 
                                },";
                }
                
                
                series = series.TrimEnd(',');
                series += "]";
               
               
                
            }
            //   this.ChartAccidentTime.CreateChart(BLL.ChartControlService.GetDataSourceChart(dtTime, "单位巡检分析", this.drpChartType.SelectedValue, 1130, 450, this.ckbShow.Checked));
            //#endregion
            //}
            //else
            //{
            //    #region 按检查项
            //    ///按检查项
            //    DataTable dtTime = new DataTable();
            //    dtTime.Columns.Add("检查项", typeof(string));
            //    dtTime.Columns.Add("总数量", typeof(string));
            //    dtTime.Columns.Add("待整改", typeof(string));
            //    dtTime.Columns.Add("已整改", typeof(string));
            //    var types = from x in Funs.DB.HSSE_Hazard_HazardRegisterTypes where x.HazardRegisterType == "1" orderby x.TypeCode select x;
            //    foreach (var item in types)
            //    {
            //        DataRow rowTime = dtTime.NewRow();
            //        Model.SpTDesktopItem newspItem = new Model.SpTDesktopItem();
            //        rowTime["检查项"] = item.RegisterTypesName;
            //        var typeHazad = hazardRegisters.Where(x => x.RegisterTypesId == item.RegisterTypesId);
            //        rowTime["总数量"] = typeHazad.Count();
            //        rowTime["待整改"] = typeHazad.Where(x => x.States == "1" || x.States == null).Count();
            //        rowTime["已整改"] = typeHazad.Where(x => x.States == "3" || x.States == "2").Count();
            //        dtTime.Rows.Add(rowTime);
            //    }
            //    //  this.ChartAccidentTime.CreateChart(BLL.ChartControlService.GetDataSourceChart(dtTime, "巡检问题分析", this.drpChartType.SelectedValue, 1100, 330, this.ckbShow.Checked));
            //    #endregion
            //}
        }
        #endregion
        #region 图形
        /// 
        /// 图形变换 
        /// 
        /// 
        /// 
        protected void drpChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.AnalyseData();
            PageContext.RegisterStartupScript(@"setTimeout(function () {  rendChart(" + legend + "," + xAxis + "," + series + ");}, 1000); ");
        }
        protected void ckbShow_CheckedChanged(object sender, CheckedEventArgs e)
        {
            this.AnalyseData();
            PageContext.RegisterStartupScript(@"setTimeout(function () { rendChart(" + legend + "," + xAxis + "," + series + ");}, 1000);");
        }
        #endregion
    }
}