using Newtonsoft.Json;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.QmsRepository.Request;
using Siger.Middlelayer.QmsRepository.Response;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Siger.Middlelayer.Common;
namespace Siger.ApiQMS.Utility
{
    public class PythonBIHelper
    {
        public string htmlUrl = string.Empty;

        public string Run(string pythonPath, string pythonScriptPath, string methodName, RequestSpcControlChart param)
        {
            var p = new Process();
            var sArguments = $"{pythonScriptPath}";
            sArguments += $" {methodName}";
            sArguments += $" {param.setSection}";
            sArguments += $" {param.setMachineID}";
            sArguments += $" {param.setProductID}";
            sArguments += $" {param.setStarttime}";
            sArguments += $" {param.setEndtime}";
            sArguments += $" {param.setTargetfeature}";
            sArguments += $" {param.setChunkSize}";
            sArguments += $" {param.setGroupSize}";
            sArguments += $" {param.setGroupNum}";

            p.StartInfo.FileName = pythonPath; //python的安装路径
            p.StartInfo.Arguments = sArguments;//python命令的参数
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            htmlUrl = "";
            p.Start();//启动进程            
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.OutputDataReceived += p_OutputDataReceived;
            p.ErrorDataReceived += P_ErrorDataReceived;
            p.WaitForExit();

            return htmlUrl;

        }
        public string RunRelationAnalysis(string pythonPath, string pythonScriptPath, string methodName, RequestRelationAnalys analys)
        {
            var p = new Process();
            var sArguments = $" {pythonScriptPath}";
            sArguments += $" {methodName}";
            sArguments += $" {analys.setYProductCode}";
            sArguments += $" {analys.setYItem}";
            sArguments += $" {UnixTimeHelper.ConvertDataTimeLongMilliSecond(analys.setStarttime)}";
            sArguments += $" {UnixTimeHelper.ConvertDataTimeLongMilliSecond(analys.setEndtime)}";
            sArguments += $" {string.Join(",", analys.setXItems)}";

            p.StartInfo.FileName = pythonPath; //python的安装路径
            p.StartInfo.Arguments = sArguments;//python命令的参数
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            htmlUrl = "";
            p.Start();//启动进程            
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.OutputDataReceived += p_OutputRelationDataReceived;
            p.ErrorDataReceived += P_ErrorDataReceived;
            p.WaitForExit();

            return htmlUrl;
        }
        private void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                Logger.WriteLineError(e.Data);
                htmlUrl = "";
            }
        }

        private void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                var res = JsonConvert.DeserializeObject<BIChartResult>(e.Data);
                var result = res.data;
                htmlUrl = ReadFile(result, Guid.NewGuid().ToString());
            }
        }
        private void p_OutputRelationDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                //var res = JsonConvert.DeserializeObject<ResponseBIRelationResult>(e.Data);
                var result = e.Data.ToString();
                htmlUrl = result;
            }
        }

        private string ReadFile(string fileContent, string fileName)
        {
            var htmlFolder = "ChartHtml";
            var fileSetting = Config<FileSettings>.Get();
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, htmlFolder);
           
            var filename = Path.Combine(rootDir, $"{fileName}.html");

            try
            {
                FileHelper.WriteFile(fileContent, filename);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
            
            return FileSystemHelper.CommonFileSetting.RequestPath + $"/{htmlFolder}/{fileName}.html";
        }
    }
}
