/// <summary>
 /// 取得用户的所有配置
 /// </summary>
 /// <returns>设备表ID</returns>
 public IList<CustomChart> Getlist(int userId, int groupid)
 {
     CustomChart CustomChart = new CustomChart();
     CustomChart.userId = userId;
     CustomChart.groupId = groupid;
     return _CustomReportDao.Getlist(CustomChart);
 }
        /// <summary>
        /// 生成自定义图表
        /// </summary>
        /// <returns>自定义报表页面</returns>
        public ActionResult ChartView(int id, string startTime, string endTime)
        {
            string report = "";

            DateTime dt = DateTime.Now;
            switch (id)
            {
                default:///自定义
                    CustomChart crt = new CustomChart();
                    crt.id = id;
                    crt = CustomChartService.GetInstance().Get(crt);
                    crt.startTime = startTime;
                    crt.endTime = endTime;
                    report = GetCustomReport(crt);
                    break;
            }
            return Content(report);
        }
        public ActionResult Save(CustomChart customReport, string cid)
        {
            int temp = 0;
            int.TryParse(cid, out temp);
            customReport.id = temp;
            customReport.groupId = 0;
            string ret = Resources.SunResource.CUSTOM_SAVE_SUCCESSFULLY;

            if (customReport != null)
            {
                if (!customReport.customType.Equals("2") && string.IsNullOrEmpty(customReport.product))
                {
                    customReport.product = customReport.ProIdType;
                }
            }
            User user = UserUtil.getCurUser();
            if (null != user && UserUtil.demousername.Equals(user.username))
            {
                ret = "Sorry,exampleuser prohibit to save";
                return Content(ret);
            }
            else if (string.IsNullOrEmpty(customReport.reportName))
            {
                ret = Resources.SunResource.CUSTOMREPORT_SAVE_FAILED_NAME;
                return Content(ret);
            }
            else if (customReport.customType.Trim().Equals("2") && string.IsNullOrEmpty(customReport.product))
            {
                ret = Resources.SunResource.CUSTOMREPORT_SAVE_FAILED_EQUIPMENT;
                return Content(ret);
            }
            else if (customReport.customType.Trim().Equals("3") && string.IsNullOrEmpty(customReport.times))
            {
                ret = Resources.SunResource.CUSTOMREPORT_SAVE_FAILED_TIME;
                return Content(ret);
            }

            int flag = 0;

            try
            {
                if (customReport.id <= 0)
                {
                    flag = CustomChartService.GetInstance().Insert(customReport);
                }
                else if (CustomChartService.GetInstance().Get(customReport) != null)
                {
                    flag = CustomChartService.GetInstance().Update(customReport);
                }
                else
                {
                    flag = CustomChartService.GetInstance().Insert(customReport);
                }
            }
            catch (Exception ee)
            {
                ret = "Save failed!" + ee.Message;
                return Content(ret);
            }
            return Content(ret);
        }
        public ActionResult Preview(CustomChart customReport)
        {
            string ret = "";
            CustomChart crt = new CustomChart();
            if (customReport != null)
            {
                crt = customReport;
            }
            ret = GetCustomReport(crt);

            return Content(ret);
        }
        public ActionResult modifyDefined(string id)
        {
            CustomChart cus = null;

            if (!string.IsNullOrEmpty(id))
            {
                cus = new CustomChart();
                cus.id = int.Parse(id);
                cus = CustomChartService.GetInstance().Get(cus);
            }
            Plant plant = PlantService.GetInstance().GetPlantInfoById(cus.plantId);
            SetDeviceList(plant);

            Analysis(ref cus);

            ViewData["charts"] = CustomChartService.GetInstance().GetListByPlant(cus.plantId);
            return View("CustomChart", cus);
        }
        public string GetReportTr(CustomChart cr)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(" <tr visible=\"false\">");
            sb.Append("   <td>");
            sb.Append("     <table width=\"100%\" border=\"0\" cellspacing=\"0\">");
            sb.Append("       <tr>");
            sb.Append("        <td width=\"54%\" height=\"28\" class=\"bp01 pl40\">");
            sb.Append("        " + cr.reportName + "");
            sb.Append("          <input id=\"hRepor" + cr.id + "\" type=\"hidden\" value=\"" + cr.id + "\" />");
            sb.Append("         </td>");
            sb.Append("          <td width=\"23%\" align=\"center\" class=\"bp01\">");
            sb.Append("           <a href=\"/CustomReport/Defined/" + cr.id + "\" id=\"aReporEdit" + cr.id + "\"  >");
            sb.Append("            <img src=\"/images/sub/edit.gif\" width=\"14\" height=\"14\" class=\"imga\" /></a>");
            sb.Append("          </td>");
            sb.Append("         <td align=\"center\" class=\"bp01\">");
            sb.Append("            <a href=\"#\" id=\"aReporDel" + cr.id + "\">");
            sb.Append("             <img src=\"/images/sub/del.gif\" width=\"14\" height=\"14\" class=\"imga\" /></a>");
            sb.Append("          </td>");
            sb.Append("          </tr>");
            sb.Append("          </table>");
            sb.Append("         </td>");
            sb.Append("       </tr>");

            return sb.ToString();
        }
        public string GetReporAjax(CustomChart cr)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("   $('#aReporDel" + cr.id + "').click(function() {");
            sb.Append("       if (confirm(\"确定删除自定义报表'" + cr.reportName + "'?\") == \"0\") {");
            sb.Append("           return;");
            sb.Append("         } else {");
            sb.Append("         $.ajax({");
            sb.Append("            type: \"POST\",");
            sb.Append("             url: \"/CustomReport/DeleteReport\",");
            //sb.Append("             data: { id: $('#hRepor" + cr.id + "').val() },");
            sb.Append("             data: { id: \"" + cr.id + "\"},");
            sb.Append("             success: function(result) {");
            sb.Append("             $('#divGroup').empty();");
            sb.Append("             $('#divGroup').append(result);");
            sb.Append("               }");
            sb.Append("            });");
            sb.Append("        }");
            sb.Append("    });");
            //sb.Append("   $('#aReporEdit" + cr.id + "').click(function() {");
            //sb.Append("      $.ajax({");
            //sb.Append("      type: \"POST\",");
            //sb.Append("        url: \"/CustomReport/EditReport\",");
            ////sb.Append("         data: { id: $('#hRepor" + cr.id + "').val() },");
            //sb.Append("         data: { id:\"" + cr.id + "\"},");
            //sb.Append("       success: function(result) {");
            ////sb.Append("           $('#divGroup').empty();");
            ////sb.Append("           $('#divGroup').append(result);");
            //sb.Append("       }");
            //sb.Append("         });");
            //sb.Append("    });");
            return sb.ToString();
        }
 /// <summary>
 /// 插入自定义报表
 /// </summary>
 /// <returns>设备表ID</returns>
 public int Remove(CustomChart customReport)
 {
     return _CustomReportDao.Remove(customReport);
 }
        /// <summary>
        /// 取得自定义图表的数据
        /// </summary>
        /// <param name="crt"></param>
        /// <returns></returns>
        private string GetCustomReport(CustomChart crt)
        {
            User user = UserUtil.getCurUser();
            DateTime dt = CalenderUtil.curDateWithTimeZone(user.timezone);

            string ret = "sorry:" + Resources.SunResource.NODATA;
            if (crt != null)
            {
                Analysis(ref crt);
                ///多设备多测点单时间报表
                List<DeviceStuct> list = new List<DeviceStuct>();
                list = GetDeviceStucts(crt);
                string reportName = crt.reportName;
                switch (crt.timeInterval.Trim().ToUpper())
                {
                    case "YEAR":

                        //if (crt.timeSlot.Trim().ToUpper().Equals("YEAR"))
                        //{
                        ChartData chartData = CompareChartService.GetInstance().compareYearsMultiDeviceMultiMonitor(crt.reportName, list, getWorkYears(list));
                        ret = JsonUtil.convertToJson(chartData, typeof(ChartData));
                        //}
                        break;
                    case "MONTH":
                        //if (crt.timeSlot.Trim().ToUpper().Equals("YEAR"))
                        //{
                        //dtstart = dt.AddYears(-crt.tcounter.Value);
                        //}
                        //else if (crt.timeSlot.Trim().ToUpper().Equals("MONTH"))
                        // {
                        //dtstart = dt.AddMonths(-crt.tcounter.Value);
                        //}

                        chartData = CompareChartService.GetInstance().compareYearMMMultiDeviceMultiMonitor(crt.reportName, GetDeviceStucts(crt), crt.startTime, crt.endTime);
                        ret = JsonUtil.convertToJson(chartData, typeof(ChartData));
                        break;
                    case "DAY":
                        //if (crt.timeSlot.Trim().ToUpper().Equals("DAY"))
                        //{
                        //dtstart = dt.AddDays(-crt.tcounter.Value);
                        // }
                        //else if (crt.timeSlot.Trim().ToUpper().Equals("MONTH"))
                        //{
                        //dtstart = dt.AddMonths(-crt.tcounter.Value);
                        // }
                        chartData = CompareChartService.GetInstance().compareMMDDMultiDeviceMultiMonitor(crt.reportName, GetDeviceStucts(crt), crt.startTime, crt.endTime);
                        ret = JsonUtil.convertToJson(chartData, typeof(ChartData));
                        break;
                    case "HOUR":
                        //if (crt.timeSlot.Trim().ToUpper().Equals("DAY"))
                        //{
                        //    dtstart = dt.AddDays(-crt.tcounter.Value);
                        //}
                        //else if (crt.timeSlot.Trim().ToUpper().Equals("HOUR"))
                        //{
                        //    dtstart = dt.AddHours(-crt.tcounter.Value);
                        //}
                        int intervalMins = 5;
                        chartData = CompareChartService.GetInstance().compareDayHHMultiDeviceMultiMonitor(crt.reportName, GetDeviceStucts(crt), crt.startTime, crt.endTime, intervalMins);
                        ret = JsonUtil.convertToJson(chartData, typeof(ChartData));
                        break;
                    default:
                        break;
                }
            }
            return ret;
        }
 public ActionResult DeleteChart(int id)
 {
     CustomChart mode = new CustomChart();
     mode.id = id;
     CustomChartService.GetInstance().Remove(mode);
     return Content("success");
 }
        public ActionResult Delete(int id, string returnUrl)
        {
            CustomChart mode = new CustomChart();
            UpdateModel(mode, Request.Form.AllKeys);

            int flag = CustomChartService.GetInstance().Remove(mode);

            return new RedirectResult(returnUrl);
        }
 public ActionResult DefinedUserChart()
 {
     User user = UserUtil.getCurUser();
     SetDeviceList(user.plants);
     SetMI(null);
     CustomChart cus = new CustomChart();
     cus.groupId = 0;
     cus.userId = user.id;
     ViewData["charts"] = CustomChartService.GetInstance().GetListByGroup(user.id, 0);
     return View("CustomChart", cus);
 }
 public ActionResult DefinedPlantChartList(int id, string cid)
 {
     int temp = 0;
     int.TryParse(cid, out temp);
     Plant plant = PlantService.GetInstance().GetPlantInfoById(id);
     SetDeviceList(plant);
     SetMI(null);
     CustomChart cus = null;
     if (string.IsNullOrEmpty(cid))
     {
         cus = new CustomChart();
         cus.groupId = 0;
         cus.plantId = plant.id;
     }
     else
     {
         cus = CustomChartService.GetInstance().Get(new CustomChart() { id = temp });
         Analysis(ref cus);
     }
     ViewData["charts"] = CustomChartService.GetInstance().GetListByPlant(cus.plantId);
     return View("CustomChartList", cus);
 }
 /// <summary>
 /// 修改自定义报表
 /// </summary>
 /// <returns>设备表ID</returns>
 public CustomChart Get(CustomChart customReport)
 {
     return _CustomReportDao.Get(customReport);
 }
 /// <summary>
 /// 修改自定义报表
 /// </summary>
 /// <returns>设备表ID</returns>
 public int Update(CustomChart customReport)
 {
     return _CustomReportDao.Update(customReport);
 }
        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="cr"></param>
        public void TextTo(ref CustomChart customReport)
        {
            if (!string.IsNullOrEmpty(customReport.product))
            {
                string[] strText = customReport.product.Split(';');
                foreach (string str in strText)
                {
                    string[] sss = str.Split(',');

                }
            }
        }
        /// <summary>
        /// 15&Plant,Power&valueType,KW&Unit,Max&cVal;
        /// 解析定义图表规则
        /// </summary>
        /// <param name="cc"></param>
        private void Analysis(ref  CustomChart cc)
        {
            if (cc != null && !string.IsNullOrEmpty(cc.product))
            {
                if (cc.customType.Trim().Equals("1"))
                {
                    string ss = cc.product.Replace(";", string.Empty);
                    string[] ssa = ss.Split(',');

                    foreach (string s in ssa)
                    {
                        string[] ss0 = s.Split('&');

                        if (ss0.Length == 2)
                        {
                            switch (ss0[1])
                            {
                                case "cVal":
                                    cc.cVal = ss0[0];
                                    break;
                                case "Unit":
                                    cc.units = ss0[0];
                                    break;
                                case "valueType":
                                    cc.valueType = ss0[0];
                                    break;
                                case "subType":
                                    cc.subType = ss0[0];
                                    break;
                                default:
                                    cc.productList = s;
                                    cc.ProIdType = s;
                                    break;
                            }

                        }
                    }
                    SetMI(cc.ProIdType);
                }

                else if (cc.customType.Trim().Equals("3"))
                {
                    if (!string.IsNullOrEmpty(cc.times))
                    {
                        List<string> slist = new List<string>();
                        string[] splis = cc.times.Split(';');
                        foreach (string ss in splis)
                        {
                            if (!string.IsNullOrEmpty(ss))
                            {
                                slist.Add(ss);
                            }
                        }
                        ViewData["TimesList"] = slist;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(cc.product))
                    {
                        List<SelectListItem> slist = new List<SelectListItem>();
                        string[] splis = cc.product.Split(';');
                        string[] sproductName = cc.productName.Split(';');

                        for (int i = 0; i < splis.Length; i++)
                        {
                            SelectListItem sel = new SelectListItem();
                            if (!string.IsNullOrEmpty(splis[i]))
                            {
                                sel.Value = splis[i];
                                sel.Text = sproductName[i];
                                slist.Add(sel);
                            }
                        }
                        ViewData["ProductList"] = slist;
                    }
                }

            }
            SetMI(cc.ProIdType);
        }
        public ActionResult DeleteReport(int id)
        {
            CustomChart mode = new CustomChart();
            mode.id = id;
            int flag = CustomChartService.GetInstance().Remove(mode);
            User user = UserUtil.getCurUser();

            string ret = GetHtml(user.id);
            return RedirectToAction("ReportGroup", ret);
        }
        /// <summary>
        /// 根据自定义图表,构造设备比较结构
        /// </summary>
        /// <param name="crt"></param>
        /// <returns></returns>
        private List<DeviceStuct> GetDeviceStucts(CustomChart crt)
        {
            List<DeviceStuct> list = new List<DeviceStuct>();

            string[] ss = crt.product.Split(';');

            foreach (string ssssss in ss)
            {
                if (string.IsNullOrEmpty(ssssss))
                    continue;
                string[] ssa = ssssss.Split(',');
                DeviceStuct dev = new DeviceStuct();
                dev.chartType = crt.subType;
                dev.intervalMins = 5;
                dev.rate = 1F;

                foreach (string s in ssa)
                {
                    string[] ss0 = s.Split('&');
                    if (ss0.Length == 2)
                    {
                        switch (ss0[1])
                        {
                            case "subType":
                                dev.chartType = ss0[0];
                                break;
                            case "cVal":
                                dev.cVal = int.Parse(ss0[0]);
                                break;
                            case "Unit":
                                dev.unit = ss0[0];
                                break;
                            case "valueType":
                                dev.monitorType = MonitorType.getMonitorTypeByCode(int.Parse(ss0[0]));
                                break;
                            case "0":///DeviceData.PLANT_CODE.ToString()
                                dev.deviceType = ChartDeviceType.PLANT;
                                dev.deviceId = ss0[0];
                                Plant plant = PlantService.GetInstance().GetPlantInfoById(int.Parse(dev.deviceId));
                                dev.comareObj = plant.name;
                                break;
                            default:
                                dev.deviceType = ChartDeviceType.DEVICE;
                                dev.deviceId = ss0[0];
                                Device device = DeviceService.GetInstance().get(int.Parse(dev.deviceId));
                                dev.comareObj = device.fullName;
                                break;
                        }

                    }
                }
                if (!(dev.monitorType.code != MonitorType.PLANT_MONITORITEM_ENERGY_CODE && !crt.timeInterval.Equals("Hour")))
                {
                    list.Add(dev);
                }
            }
            return list;
        }
 /// <summary>
 /// 插入自定义报表
 /// </summary>
 /// <returns>设备表ID</returns>
 public int Insert(CustomChart customReport)
 {
     return _CustomReportDao.Insert(customReport);
 }