using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.Mvc;
using QMAPP.Common.Web.Controllers;
using QMAPP.Entity;
using QMAPP.FJC.Entity.ProductIn;
using QMAPP.MESReport.Entity.LineQTY;
using QMAPP.MESReport.Web.Models.LineQTY;
using QMAPP.ServicesAgent;
using QMFrameWork.Common.ExcelOperation;
using QMFrameWork.Data;
using QMFrameWork.Log;
using QMFrameWork.WebUI.Attribute;
using ExcelOperationHelper = QMAPP.MESReport.Web.Common.ExcelOperationHelper;

namespace QMAPP.MESReport.Web.Controllers
{
    /// <summary>
    /// 生产完成率分析
    /// 于子清
    /// 2017-10-20
    /// </summary>
    public class QTYCompletionRateCountController : QController
    {

        public ActionResult QTYCompletionRateCountView()
        {
            QTYCompletionRateVModel seachModel = new QTYCompletionRateVModel();
            seachModel.START_DATE = DateTime.Now.Date.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss");
            seachModel.END_DATE = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            return View(seachModel);
        }

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

            ServiceAgent wcfAgent = this.GetServiceAgent();
            QTYCompletionRateDModel condition = new QTYCompletionRateDModel();

            condition.WORKCENTER_CODE = WORKCENTER_CODE;

            condition.START_DATE = START_DATE;
            condition.END_DATE = END_DATE;


            List<QTYCompletionRateDModel> nli = new List<QTYCompletionRateDModel>();
            try
            {
                #region wcf服务统一接口
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<List<QTYCompletionRateDModel>>>("QTYCompletionRateBLL_GetAllList", condition);

                nli = dataResult.Result;

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

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

            if (nli == null || nli.Count == 0)
            {
                return "没有数据";
            }
            var workcenter = "";
            if (!string.IsNullOrEmpty(WORKCENTER_CODE))
            {
                if (WORKCENTER_CODE == "0")
                {
                    workcenter = "注塑";
                }
                if (WORKCENTER_CODE == "1")
                {
                    workcenter = "门板";
                }
                if (WORKCENTER_CODE == "2")
                {
                    workcenter = "仪表板";
                }
            }
            //拼接表头
            html.Append("<tr><td >" + workcenter + "</td>");

            foreach (QTYCompletionRateDModel item in nli)
            {
                html.Append("<td>");
                html.Append(item.MATERIAL_SHORT);
                html.Append("</td>");
            }
            html.Append("</tr>");

            //拼接第一行
            html.Append("<tr><td >计划</td>");

            foreach (QTYCompletionRateDModel item in nli)
            {
                html.Append("<td>");
                html.Append(item.QTY);
                html.Append("</td>");
            }
            html.Append("</tr>");

            //拼接第二行
            html.Append("<tr><td >完成</td>");

            foreach (QTYCompletionRateDModel item in nli)
            {
                html.Append("<td>");
                html.Append(item.COMPLETE_QTY);
                html.Append("</td>");
            }
            html.Append("</tr>");

            return html.ToString();
        }

     

        #region 多图叠加

        /// <summary>
        /// 多图叠加
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult GetEchartDataGroup1(string name)
        {
            QTYCompletionRateVModel seachModel = null;
            DataPage page = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            QTYCompletionRateDModel condition = null;
            List<QTYCompletionRateDModel> nli = new List<QTYCompletionRateDModel>();
            try
            {
                //获取查询对象
                seachModel = GetModel<QTYCompletionRateVModel>();
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                condition = CopyToModel<QTYCompletionRateDModel, QTYCompletionRateVModel>(seachModel);
                #region wcf服务统一接口
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<List<QTYCompletionRateDModel>>>("QTYCompletionRateBLL_GetAllList", condition);

                nli = dataResult.Result;

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

            #region 源数据定义

            string jihua = "", wancheng = "", wclv = "",riqi="", dou = "";
            bool first = true;
            foreach (QTYCompletionRateDModel item in nli)
            {

                jihua += dou + "'" + item.QTY + "'";
                wancheng += dou + "'" + item.COMPLETE_QTY + "'";
                wclv += dou + "'" + (Convert.ToDouble(item.COMPLETE_QTY)/Convert.ToDouble(item.QTY)*100).ToString("0") + "'";
                riqi += dou + "'" + item.TDAY + "'";
                if (first)
                {
                    first = false;
                    dou = ",";
                }
            }


            string strOption = @"{
            tooltip: {
                trigger: 'axis'
            },
            toolbox: {
                show: false,
                feature: {
                    mark: { show: true },
                    dataView: { show: true, readOnly: false },
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            calculable: true,
            legend: {
                data: ['计划数量', '完成数量']
            },
            xAxis: [
        {
            type: 'category',
            data: [" + riqi + @"]
        }
    ],
            yAxis: [
        {
            type: 'value',
            name: '件',
            axisLabel: {
                formatter: '{value}'
            }
        },
        {
            type: 'value',
            name: '百分比',
            axisLabel: {
                formatter: '{value} %'
            }
        }
    ],
            series: [

        {
            name: '计划数量',
            type: 'bar',
            data: [" + jihua + @"]

        },
        {
            name: '完成数量',
            type: 'bar',
            data: [" + wancheng + @"]
        }, 
        {
            name: '完成率',
            type: 'line',
            yAxisIndex: 1,
            data: [" + wclv + @"]
            , itemStyle: { normal: { label: { show: true}} }
        }
    ]
        }";
            #endregion

            return Content(strOption);

        }

        /// <summary>
        /// 统计图页面配置
        /// </summary>
        /// <returns></returns>
        public static string QMEChartPageConfig()
        {
            StringBuilder configBuilder = new StringBuilder();
            configBuilder.AppendLine("");
            configBuilder.AppendLine("<!--图表控件-->");
            configBuilder.AppendLine("<script src=\"../../Scripts/echarts-2.2.2/build/dist/echarts.js\" type=\"text/javascript\" language=\"javascript\"></script>");
            configBuilder.AppendLine("<script type=\"text/javascript\">");
            configBuilder.AppendLine("<!-- 路径配置-->");
            configBuilder.AppendLine("    require.config({");
            configBuilder.AppendLine("        paths: {");
            configBuilder.AppendLine("            echarts: '../../Scripts/echarts-2.2.2/build/dist',");
            configBuilder.AppendLine("            themes: '../../Scripts/echarts-2.2.2/src'");
            configBuilder.AppendLine("        }");
            configBuilder.AppendLine("    });");
            configBuilder.AppendLine("    if (!window.console || !console.firebug) {");
            configBuilder.AppendLine("        var names = ['log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'];");

            configBuilder.AppendLine("        window.console = {};");
            configBuilder.AppendLine("        for (var i = 0; i < names.length; ++i)");
            configBuilder.AppendLine("            window.console[names[i]] = function () { }");
            configBuilder.AppendLine("    }        ");
            configBuilder.AppendLine("</script>");

            return configBuilder.ToString();

        }

        #endregion

        //完成率图表
        [HandleException]
        public ActionResult GetEchartDataBar2()
        {
            QTYCompletionRateVModel seachModel = null;
            DataPage page = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            QTYCompletionRateDModel condition = null;
            List<QTYCompletionRateDModel> nli = new List<QTYCompletionRateDModel>();
            try
            {
                //获取查询对象
                seachModel = GetModel<QTYCompletionRateVModel>();
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                condition = CopyToModel<QTYCompletionRateDModel, QTYCompletionRateVModel>(seachModel);
                #region wcf服务统一接口
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<List<QTYCompletionRateDModel>>>("QTYCompletionRateBLL_GetAllList", condition);

                nli = dataResult.Result;

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

            var workcenter = "";
            if (!string.IsNullOrEmpty(condition.WORKCENTER_CODE))
            {
                if (condition.WORKCENTER_CODE == "0")
                {
                    workcenter = "注塑";
                }
                if (condition.WORKCENTER_CODE == "1")
                {
                    workcenter = "门板";
                }
                if (condition.WORKCENTER_CODE == "2")
                {
                    workcenter = "仪表板";
                }
            }
            return Content(setOptionRepair(nli, workcenter + "计划数量", workcenter + "完成数量"));
        }

        public string setOptionRepair(List<QTYCompletionRateDModel> nli, string name1, string name2)
        {
            #region 源数据定义

            string jihua = "", wancheng = "", wclv = "", riqi = "", dou = "";
            bool first = true;
            if (nli == null || nli.Count == 0)
            {
                jihua += "''";
                wancheng += "''";
                wclv += "''";
                riqi += "''";
            }
            else
            {
                //jihua += "'',";
                //wancheng += "'',";
                //wclv += "'',";
                //riqi += "'',";

                foreach (QTYCompletionRateDModel item in nli)
                {
                    //jihua=生成数量QTY,wancheng=返修数量COMPLETE_QTY。 借用
                    jihua += dou + "'" + item.QTY + "'";
                    wancheng += dou + "'" + item.COMPLETE_QTY + "'";
                    double fenmu = 1;
                    if (!string.IsNullOrEmpty(item.QTY) && item.QTY != "0")
                    {
                        fenmu = Convert.ToDouble(item.QTY);
                    }
                    double fenzi = 0;
                    if (!string.IsNullOrEmpty(item.COMPLETE_QTY))
                    {
                        fenzi = Convert.ToDouble(item.COMPLETE_QTY);
                    }
                    wclv += dou + "'" + (fenzi / fenmu * 100).ToString("0") + "'";
                    riqi += dou + "'" + item.MATERIAL_SHORT + "'";
                    if (first)
                    {
                        first = false;
                        dou = ",";
                    }
                }
                //jihua += ",''";
                //wancheng += ",''";
                //wclv += ",''";
                //riqi += ",''";
            }

            string strOption = @"{
            noDataLoadingOption: {
                text: '无数据',
                effect: 'bubble',
                effectOption: {
                    effect: {
                        n: 0
                    }
                }
            },
            dataZoom : {
                show : true,
                realtime : true,
                start : 0,
                end : 100
            },
            grid: {
                y2: 80
            },
            tooltip: {
                trigger: 'axis'
            },
            toolbox: {
                show: false,
                feature: {
                    mark: { show: true },
                    dataView: { show: true, readOnly: false },
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            calculable: true,
            legend: {
                data: ['" + name1 + @"', '" + name2 + @"']
            },
            xAxis: [
                {
                    type: 'category',
                    axisLabel : {      //坐标轴刻度标签的相关设置。
                        interval:'auto',  
                        rotate:10
                    },
                    data: [" + riqi + @"]
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '件',
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                {
                    type: 'value',
//                    name: '百分比',
//                    axisLabel: {
//                        formatter: '{value} %'
//                    }
                    scale: true,
                    name: '百分比',
                    max: 100,
                    min: 0,
                    boundaryGap: [" + wclv + @"]
                }
            ],
            series: [
                {
                    name: '" + name1 + @"',
                    type: 'bar',
                    data: [" + jihua + @"]

                },
                {
                    name: '" + name2 + @"',
                    type: 'bar',
                    data: [" + wancheng + @"]
                }, 
                {
                    name: '完成率',
                    type: 'line',
                    yAxisIndex: 1,
                    data: [" + wclv + @"], 
                    itemStyle: { normal: { label: { show: true}} }
                }
            ]
        }";
            #endregion

            return strOption;
        }



        #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


        #region 导出excel
        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult ExportExcel()
        {
            QTYCompletionRateVModel seachModel = null;
            QTYCompletionRateDModel condition = null;
            DataTable exportDt = new DataTable();
            string selectKey = Request["selectKey"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            try
            {
                //获取查询对象
                seachModel = GetModel<QTYCompletionRateVModel>();
                condition = CopyToModel<QTYCompletionRateDModel, QTYCompletionRateVModel>(seachModel);

                //获取数据
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<DataTable>>("QTYCompletionRateBLL_GetExportData", condition);
                //var dataResult = wcfAgent.InvokeServiceFunction<DataResult<List<QTYCompletionRateDModel>>>("QTYCompletionRateBLL_GetAllList", condition);

                //通过返回dataResult判断
                if (dataResult.Ex != null)
                {
                    throw dataResult.Ex;
                }
                else if (dataResult.IsSuccess)
                {
                    exportDt = dataResult.Result;
                }
                else
                {
                    SetMessage(dataResult.Msg);
                    return View(true);
                }

                //根据所选信息进行导出
                if (!String.IsNullOrEmpty(selectKey))
                {
                    DataView dv = new DataView(exportDt);
                    string strWhere = "";
                    string[] list = selectKey.Split(":".ToCharArray());
                    foreach (string ID in list)
                    {
                        strWhere += " PID='" + ID + "' or";
                    }
                    if (strWhere != "")
                    {
                        strWhere = strWhere.Remove((strWhere.Length - 2), 2);
                    }
                    dv.RowFilter = strWhere;
                    exportDt = dv.ToTable();
                }

                //导出
                IEExcelHelper ieExcelHelper = new IEExcelHelper();
                var sheetInfo = ieExcelHelper.GetMainInfo("QTYCompletionRateCountExp");
                var fileName = System.Guid.NewGuid().ToString() + ".xlsx";
                ieExcelHelper.ExportExcel(sheetInfo, exportDt, ExcelOperationHelper.GetTempPath() + fileName, true);
                return Content(fileName);
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo { ErrorInfo = ex, Info = "导出excel", Tag = "完成率" });
                SetMessage("导出excel失败");
                return View(true);
            }
        }

        /// <summary>
        /// 导出文件
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportFile()
        {
            String filePath = ExcelOperationHelper.GetTempPath();
            String fileName = Request["FileName"];
            ExcelOperationHelper.FileDownload(Response, filePath + fileName, "完成率.xlsx");
            return Content("");
        }
        #endregion

    }
}