using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Dapper;
using Siger.Middlelayer.Dapper.Data;
using Siger.Middlelayer.ToolRepository.Repositories.Interface;
using Siger.Middlelayer.ToolRepository.Request;

namespace Siger.ApiTools.Controllers
{

    public class FailureCurveController : BaseController
    {
        private readonly IKMAlarmRecordDataRepository kMAlarmRecordDataRepository;

        public FailureCurveController(IKMAlarmRecordDataRepository kMAlarmRecordDataRepository)
        {
            this.kMAlarmRecordDataRepository = kMAlarmRecordDataRepository;
        }

        [HttpPost]
        public ActionResult GetToolAlarmLogPhoto([FromBody]RequestGetToolAlarmLogPhoto req)
        {
            //var analysisData = kMAlarmRecordDataRepository.GetList(f =>
            //                                        f.companyID == CompanyId &&
            //                                        f.projectID == ProjectId &&
            //                                        f.spindleID == req.spindle_name &&
            //                                        f.machineID == req.machine_id &&
            //                                        f.programNum == req.program_no &&
            //                                        f.toolNum == req.cutter_location_name &&
            //                                        f.timeS == req.alarm_time
            //                                    ).ToList();
            var dapperData = new ToolAlarmRepository(CompanyId, ProjectId);
            var analysisData = dapperData.AlarmLogFailurePhoto(req.machine_id, req.spindle_name, req.cutter_location_name, req.program_no, req.alarm_time);
            if (!analysisData.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var result = new FailureCurce();

            foreach (var item in analysisData)
            {
                //包络线报警只取一条
                if (result.realCharts == null &&
                    item.BLX_LL != "-" &&
                    item.BLX_UL != "-" &&
                    item.BLX_signal != "-"
                    )
                {
                    result.realCharts = new RealCharts();
                    result.realCharts.LL = kMAlarmRecordDataRepository.FillEchartsData(item.BLX_step_number, item.BLX_LL);
                    result.realCharts.UL = kMAlarmRecordDataRepository.FillEchartsData(item.BLX_step_number, item.BLX_UL);
                   // result.realCharts.UUUU = kMAlarmRecordDataRepository.FillEchartsData(item.BLX_step_number, item.BLX_ult_UL);
                   // result.realCharts.LLLL = kMAlarmRecordDataRepository.FillEchartsData(item.BLX_step_number, item.BLX_ult_LL);
                    result.realCharts.act = kMAlarmRecordDataRepository.FillEchartsData(item.BLX_step_number, item.BLX_signal);
                }
                //趋势线报警数据只取一条
                if (result.ProcessCount == null &&
                    item.Trend_time != "-" &&
                    item.Trend_feature_out != "-" &&
                    item.Trend_feature_in != "-" &&
                    item.Trend_UL != "-" &&
                    item.Trend_avg != "-" &&
                    item.Trend_huandao != "-"
                    )
                {
                    result.ProcessCount = getProcessCount(item);
                }
                if (result.ProcessCount != null && result.realCharts != null)
                {
                    break;
                }
            }
            //if (result.ProcessCount != null && result.realCharts != null)
            //{
            //    return new ObjectResult(result);
            //}
            //throw new BadRequestException(CommonEnum.RecordNotFound);
            if (result.ProcessCount == null && result.realCharts == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new ObjectResult(result);
        }

        //private ProcessCount getProcessCount(KMAlarmRecordDataEntity data)
        private ProcessCount getProcessCount(ToolAlarmRecordData data)
        {
            var time = JArray.Parse(data.Trend_time);
            var dataCount = time.Count;
            var feature = JArray.Parse(data.Trend_feature);
            var featureOut = JArray.Parse(data.Trend_feature_out);  //toine
            var featureIn = JArray.Parse(data.Trend_feature_in);    //toine
            var featureMax = JArray.Parse(data.Trend_feature_max);
            var featureMaxOut = JArray.Parse(data.Trend_feature_max_out);
            var featureMaxIn = JArray.Parse(data.Trend_feature_max_in);
            var UL = JArray.Parse(data.Trend_UL);
            var ULMax = JArray.Parse(data.Trend_max_UL);
            var avg = JArray.Parse(data.Trend_avg);
            var avgMax = JArray.Parse(data.Trend_max_avg);
            var huandao = JArray.Parse(data.Trend_huandao);
            double.TryParse(UL.Max().ToString(), out double ULmax);//上线最大值
            double.TryParse(ULMax.Max().ToString(), out double ULmaxmax);//上线最大值(max)

            double.TryParse(feature.Max().ToString(), out double featuremax);//完整线最大值
            int.TryParse(featureMax.Max().ToString(), out int featuremaxmax);//完整线最大值(max)


            var result = new ProcessCount();
            result.xtime = assembleOneDimensionArray(time);
            result.outpoint = assembleOneDimensionArrayBySpecial(featureOut);
            result.inpoint = assembleOneDimensionArrayBySpecial(featureIn);
            result.ULine = JArryHelper.ArryFormat(UL);
            result.average = JArryHelper.ArryFormat(avg);
            result.feature = JArryHelper.ArryFormat(feature);

            var feature_last = getObject(feature);
            result.feature_last = feature_last;

            var total_max = new Total_Max();
            total_max.xtimemax = assembleOneDimensionArray(time);//此处与上面的time一致，后续考虑是否使用同一个对象，减少调用
            total_max.outpointmax = assembleOneDimensionArrayBySpecial(featureMaxOut);
            total_max.inpointmax = assembleOneDimensionArrayBySpecial(featureMaxIn);
            total_max.ULinemax = JArryHelper.ArryFormat(ULMax);
            total_max.averagemax = JArryHelper.ArryFormat(avgMax);
            total_max.featuremax = JArryHelper.ArryFormat(featureMax);

            total_max.featuremax_last = getObject(total_max.featuremax);

            double max;
            if (featuremax > ULmax)
            {
                max = featuremax;
            }
            else
            {
                max = ULmax;
            }
            max = max * 1.17;//最大值

            double maxmax;
            if (featuremaxmax > ULmaxmax)
            {
                maxmax = featuremaxmax;
            }
            else
            {
                maxmax = ULmaxmax;
            }
            maxmax = maxmax * 1.17;//最大值(最大值)

            int huandaocount = 0;
            result.huandao = new List<List<List<object>>>();
            total_max.huandaomax = new List<object>();
            foreach (var item in huandao)
            {
                //竖线
                huandaocount++;

                int.TryParse(item.ToString(), out int value);
                var temp = new List<List<object>>();
                temp.Add(new List<object>()
                {
                    value-1,
                    0
                });
                temp.Add(new List<object>()
                {
                    value-1,
                    max
                });
                result.huandao.Add(temp);
                total_max.huandaomax.Add(temp);
            }
            return result;
        }
        private List<object> getObject(JArray list)
        {
            if (list == null || list.Count == 0)
                return new List<object>();
            var result = new List<object>();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    var temp = new List<object>();
                    temp.Add(i);
                    temp.Add(list[i]);
                    result.Add(temp);
                }
                else
                {
                    result.Add("-");
                }
            }
            return result;
        }
        private List<object> getObject(List<List<object>> list)
        {
            if (list == null || list.Count == 0)
                return new List<object>();
            var result = new List<object>();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    result.Add(list[i]);
                }
                else
                {
                    result.Add("-");
                }
            }
            return result;
        }
        private List<object> assembleOneDimensionArray(JArray list)
        {
            if (list == null || list.Count == 0)
                return new List<object>();
            var result = new List<object>();
            foreach (var item in list)
            {
                result.Add(item);
            }
            return result;
        }

        List<object> assembleOneDimensionArrayBySpecial(JArray list, string symbol = "-")
        {
            if (list == null || list.Count == 0)
                return new List<object>();
            var result = new List<object>();
            foreach (var item in list)
            {
                if (item.ToString() == symbol)
                {
                    result.Add(item);
                }
                else
                {
                    //值可能为double
                    if (double.TryParse(item.ToString(), out double value))
                    {
                        result.Add((int)value);
                    }

                }
            }
            return result;
        }

    }
}