using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QMAPP.MESReport.Web.Models.LineQTY;
using QMAPP.Common.Web.Controllers;
using QMFrameWork.WebUI.Attribute;
using QMFrameWork.Data;
using QMAPP.Entity;
using QMAPP.ServicesAgent;
using QMFrameWork.WebUI.DataSource;
using QMFrameWork.Common.Serialization;
using QMAPP.MESReport.Entity.LineQTY;

using System.Collections;
using System.Reflection;
using QMFrameWork.ServiceInterface;
using System.Data.SqlClient;
using System.Data;
using QMAPP.Common.Web.Util;

using QMFrameWork.WebUI.QMEChart;
using QMFrameWork.WebUI.QMEChart.Data;
using QMAPP.MESReport.Web.Models;
using QMAPP.MESReport.BLL.LineQTY;
using System.Text;

namespace QMAPP.MESReport.Web.Controllers
{
    /// <summary>
    /// 生产统计
    /// 于子清
    /// 2017-10-18
    /// </summary>
    public class QTYInfoCountController : QController
    {
        public ActionResult QTYInfoCountView()
        {
            QTYInfoCountVModel model = new QTYInfoCountVModel();
            model.START_DATE = System.DateTime.Now.ToShortDateString();
            model.END_DATE = System.DateTime.Now.ToShortDateString();
           
            return View(model);
        }

        /// <summary>
        /// 异步刷新TABLE
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ActionResult GetTable(string MATERIAL_CODE, string TYPE_COUNT, string START_DATE, string END_DATE)
        {

            ServiceAgent wcfAgent = this.GetServiceAgent();

            QTYInfoCountVModel seachModel = null;
            seachModel = GetModel<QTYInfoCountVModel>();
            DataPage page = null;
            page = this.GetDataPage(seachModel);
            QTYInfoCountDModel condition = new QTYInfoCountDModel();
           
            List<QTYInfoCountDModel> nli = new List<QTYInfoCountDModel>();
            try
            {
                condition = CopyToModel<QTYInfoCountDModel, QTYInfoCountVModel>(seachModel);
                //初始没有查询条件的情况下返回空
                if (string.IsNullOrEmpty(condition.PROJECTCODE))
                {
                    return Json("");
                }


                #region wcf服务统一接口
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<List<QTYInfoCountDModel>>>("QTYInfoCountBLL_GetAllList", condition);

                nli = dataResult.Result;

                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
            string sss = GetHTMLStr(nli, TYPE_COUNT);
            return Json(sss);
        }

        /// <summary>
        /// 拼接字符串
        /// </summary>
        /// <returns></returns>
        public string GetHTMLStr(List<QTYInfoCountDModel> nli, string TYPE_COUNT)
        {
            StringBuilder html = new StringBuilder();

            if (nli == null)
            {
                return "没有数据";
            }

            string timetype = "号";
            if (TYPE_COUNT == "WEEK")
            {
                timetype = "周";
            }
            else if (TYPE_COUNT == "MONTH")
            {
                timetype = "月";
            }

            //拼接表头
            html.Append("<tr><td class='L1cos'>产品种类</td>");

            List<string> arr = new List<string>();

            foreach (QTYInfoCountDModel item in nli)
            {
                if (html.ToString().Contains(item.TDAY + timetype))
                {
                    continue;
                }

                html.Append("<td>");
                if (item.TDAY.Equals("累计"))
                {
                    html.Append(item.TDAY);
                }
                else
                {
                    html.Append(item.TDAY + timetype);
                    arr.Add(item.TDAY + timetype);
                }
                html.Append("</td>");
            }
            html.Append("</tr>");

            Dictionary<string, List<QTYInfoCountDModel>> dls = new Dictionary<string, List<QTYInfoCountDModel>>();

            //对结果集分类
            foreach (QTYInfoCountDModel item in nli)
            {
                if (dls.Keys.Contains(item.MATERIAL_NAME + item.MATERIAL_CODE))
                {
                    //则添加到KEY下
                    dls[item.MATERIAL_NAME + item.MATERIAL_CODE].Add(item);
                    continue;
                }
                else
                {
                    //新建key
                    List<QTYInfoCountDModel> li = new List<QTYInfoCountDModel>();
                    li.Add(item);
                    dls.Add(item.MATERIAL_NAME + item.MATERIAL_CODE, li);
                }
            }

            //拼接主体数据
            foreach (List<QTYInfoCountDModel> item in dls.Values)
            {
                if (item[0].MATERIAL_NAME.Equals("累计"))
                {
                    continue;
                }

                html.Append("<tr>");
                html.Append("<td>" + item[0].MATERIAL_NAME);
                html.Append("</td>");

                foreach (string itit in arr)
                {
                    bool sss = true;
                    string QTY = "";
                    foreach (QTYInfoCountDModel its in item)
                    {
                        if (its.TDAY + timetype == itit)
                        {
                            sss = false;
                            QTY = its.QTY;
                            break;
                        }
                    }
                    if (sss)
                    {
                        html.Append("<td>0</td>");
                    }
                    else
                    {
                        html.Append("<td>" + QTY + "</td>");
                    }
                }

                html.Append("</tr>");
            }

            return html.ToString();
        }


        /// <summary>
        /// 堆积柱状图
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult GetEchartDataBar2()
        {
            QTYInfoCountVModel seachModel = null;
            DataPage page = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            QTYInfoCountDModel condition = null;
            List<QTYInfoCountDModel> nli = new List<QTYInfoCountDModel>();
            try
            {
                //获取查询对象
                seachModel = GetModel<QTYInfoCountVModel>();
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                condition = CopyToModel<QTYInfoCountDModel, QTYInfoCountVModel>(seachModel);

                //初始没有查询条件的情况下返回空
                if (string.IsNullOrEmpty(condition.PROJECTCODE))
                {
                    return Content("");
                }

                #region wcf服务统一接口
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<List<QTYInfoCountDModel>>>("QTYInfoCountBLL_GetAllList", condition);

                nli = dataResult.Result;

                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }

            #region 源数据定义

            //生成数据
            List<TestEChartModel> dataList = new List<TestEChartModel>();

            if (nli!=null)
            {
                string timetype = "号";
                if (condition.TYPE_COUNT == "MONTH")
                {
                    timetype = "月";
                }
                else if (condition.TYPE_COUNT == "WEEK")
                {
                    timetype = "周";
                }

                foreach (QTYInfoCountDModel item in nli)
                {
                    dataList.Add(new TestEChartModel() { Week = item.TDAY + timetype, Value = item.QTY, TypeValue = item.MATERIAL_NAME, StackValue = item.MATERIAL_NAME });
                }
            }
            

            #endregion

            #region 默认设置

            QMEChartBar chartLBar = new QMEChartBar() { BarType = "bar2" };

            //设置源数据列表
            chartLBar.DataList = dataList;

            #region 设置标题
            //不为空时显示Title,为空时不显示
            chartLBar.Title = new QMECTitle();
            chartLBar.Title.Text = "";
            chartLBar.Title.Subtext = "";
            #endregion

            #region Tooltip提示窗口设置

            //是否显示ToolTip工具条
            chartLBar.HaveTooltip = true;

            #endregion

            #region Legend图例设置
            //是否有Legend
            chartLBar.HaveLegend = true;
            //Legend的自动统计字段,对应chartLine.DataList中用于统计的字段
            chartLBar.LegendField = "TypeValue";

            #endregion

            #region Toolbox工具栏设置
            //是否存在工具栏,为空时使用默认设置
            chartLBar.HaveToolBox = false;

            #endregion

            #region XAxis横坐标轴设置
            //为空时使用默认值并从数据源中统计类型,需要设置DataList数据源
            chartLBar.HaveXAxis = true;
            //设置X轴统计类型字段
            chartLBar.XAxisField = "Week";
            #endregion

            #region YAxis纵坐标轴设置
            //设置Y轴显示格式。
            chartLBar.HaveYAxis = true;
            //自定义设置
            chartLBar.YAxis = new QMECYAxis() { AxisLabel = new QMECAxisLabel() };
            chartLBar.YAxis.Type = "value";
            #endregion

            #region 堆积字段设置

            //堆积字段,是否是堆积图形
            chartLBar.StackField = "StackValue";
            #endregion

            #region 生成图表所需要数据格式
            //转换数据格式,值字段
            chartLBar.ValueField = "Value";
            chartLBar.Series = QMEChartHelper.CovertDataToSeries(chartLBar);
            foreach (QMECSerie serie in chartLBar.Series)
            {
                //显示数值
                serie.ItemStyle = new QMECItemStyle();
                serie.ItemStyle.Normal = new QMECNormal();
                serie.ItemStyle.Normal.Label = new QMECLabel();
                serie.ItemStyle.Normal.Label.Show = true;
            }
            #endregion

            #region 辅助线设置,有则设置,没有则无需设置
            //设置辅助线
            QMECMarkLine ml = new QMECMarkLine() { ItemStyle = new QMECItemStyle() { Normal = new QMECNormal() { LineStyle = new QMECLineStyle() } }, LineData = new List<QMECPoint>() };
            ml.ItemStyle.Normal.LineStyle = new QMECLineStyle() { Type = "dashed", Width = 1 };
            List<QMECMarkPoint> mp = new List<QMECMarkPoint>();
            QMECPoint mpstart = new QMECPoint();
            QMECPoint mpend = new QMECPoint();
            mpstart.Type = "min";
            mpend.Type = "max";
            ml.LineData.Add(mpstart);
            ml.LineData.Add(mpend);

            foreach (QMECSerie ser in chartLBar.Series)
            {
                if (ser.Name == "搜索引擎")
                {
                    ser.MarkLine = ml;
                }
            }
            #endregion

            return Content(QMEChartHelper.QMECHelper<QMEChartBar>(chartLBar));

            #endregion

        }

        #region 导出图片

        [HttpPost]
        [HandleException]
        public ActionResult ExportBanCi()
        {
            string imgSend = Request.Form["hiChartImg"];
            imgSend = imgSend.Replace(" ", "+");
            string[] contents = imgSend.Split(',');
            imgSend = contents[1];
            byte[] content = Convert.FromBase64String(imgSend);

            System.Web.Mvc.FileContentResult result = null;

            result = new System.Web.Mvc.FileContentResult(content, "application/png");

            result.FileDownloadName = System.Web.HttpUtility.UrlEncode("生产统计.png", System.Text.Encoding.UTF8);

            return result;
        }
        #endregion

    }
}