using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ComponentModel;

using FLY.Thick.Base.Common;
using FLY.Thick.Base.IService;
using AutoMapper;
using System.IO;
using Newtonsoft.Json;

namespace FLY.Thick.Base.Server
{
    public class CurveCollection : ICurveService
    {
        #region 数据文件需要保存的数据项

        /// <summary>
        /// AD曲线校正方式
        /// </summary>
        public CurveCorrectWay CorrectWay { get; set; } = CurveCorrectWay.OnePointIsScale;

        public CurveType Flag { get; set; } = CurveType.E;

        /// <summary>
        /// 输入的曲线, 排列顺序，Value 从 小到大
        /// </summary>
        [PropertyChanged.DoNotCheckEquality]
        public CurveCell[] Curves { get; set; }

        #endregion

        public event ActiveEventHandler ActiveEvent;

        public struct ExChange
        {
            public ExChange(int orgAd, int currAd) {
                OrgAD = orgAd;
                CurrAD = currAd;
            }
            public int OrgAD { get; set; }
            public int CurrAD { get; set; }
        }
        /// <summary>
        /// 真实样品校正点
        /// </summary>
        List<ExChange> RevisingCurves = new List<ExChange>();

        private string param_path = "curve.json";
        public CurveCollection() 
        {
            SetDefault();
            ReviseCurve();
        }

        public CurveCollection(string param_path)
        {
            if (!string.IsNullOrEmpty(param_path))
                this.param_path = param_path;

            SetDefault();
            if (!Load()) {
                Save();
            }
            Curves = Curves.OrderBy(c => c.Value).ToArray();
            RevisingCurves.Clear();
            ReviseCurve();

        }
        void SetDefault() 
        {
            CorrectWay = CurveCorrectWay.OnePointIsScale;
            Flag = CurveType.E;
            Curves = new CurveCell[] {
                new CurveCell() { AD = 57564, Value = 0 },
                new CurveCell() { AD = 30850, Value = 8800 },
                new CurveCell() { AD = 19000, Value = 17600 },
                new CurveCell() { AD = 12528, Value = 26400 },
                new CurveCell() { AD = 8409, Value = 35200 },
                new CurveCell() { AD = 5650, Value = 44000 },
                new CurveCell() { AD = 3779, Value = 52800 },
                new CurveCell() { AD = 2513, Value = 61600  },
                new CurveCell() { AD = 1660, Value = 70400 } 
            };
        }
        public void Apply(CurveCorrectWay correctWay, CurveType flag, CurveCell[] curves)
        {
            CorrectWay = correctWay;
            Flag = flag;
            Curves = curves;
            ClearExChange();
            ReviseCurve();

            ActiveEvent?.Invoke(this);
            Save();
        }


        #region ExChange

        public void ModifyExChange(List<ExChange> list)
        {
            RevisingCurves.Clear();
            for (int i = 0; i < list.Count(); i++)
            {
                //检测RevisingCurves 正确性，避免 /0 溢出
                if ((list[i].OrgAD <= 10) || (list[i].CurrAD <= 10))
                {
                    //异常
                    continue;
                }
                var v = from rc in RevisingCurves where rc.OrgAD == list[i].OrgAD select rc;
                if (v.Count() > 0)
                {
                    //异常,重复了
                    continue;
                }
                RevisingCurves.Add(list[i]);
            }
            RevisingCurves.OrderByDescending(c => c.OrgAD);
        }


        public void ClearExChange()
        {
            RevisingCurves.Clear();
        }
        #endregion


        public static bool CheckRevisingPointValid(int ad)
        {
            if (ad < 3)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 根据样品值，修正曲线,只支持2个样品
        /// </summary>
        /// <returns></returns>
        public bool ReviseCurve()
        {
            if (RevisingCurves.Count < 1)//没数据
            {
                foreach (CurveCell c in Curves)
                {
                    c.RevisedAD = c.AD;
                }
                return false;
            }

            if (RevisingCurves.Count == 1)//只有一个校正点
            {
                switch (CorrectWay)
                {
                    case CurveCorrectWay.OnePointIsScale:
                        {
                            double ux = ((double)RevisingCurves[0].CurrAD) / RevisingCurves[0].OrgAD;

                            foreach (CurveCell c in Curves)
                            {
                                c.RevisedAD = (int)(c.AD * ux);
                            }
                        } break;
                    default:
                        //case CurveCorrectWay.OnePointIsOffset:
                        {
                            int x = RevisingCurves[0].CurrAD - RevisingCurves[0].OrgAD;

                            foreach (CurveCell c in Curves)
                            {
                                c.RevisedAD = c.AD + x;
                            }
                        } break;
                }

                return true;
            }
            else
            {
                int adh = RevisingCurves[0].OrgAD;
                int adl = RevisingCurves[1].OrgAD;
                double uh = ((double)RevisingCurves[0].CurrAD) / adh;
                double ul = ((double)RevisingCurves[1].CurrAD) / adl;

                for (int i = 0, j = 1; i < Curves.Count(); i++)
                {
                    double ux = uh - (adh - Curves[i].AD) * (uh - ul) / (adh - adl);
                    Curves[i].RevisedAD = (int)(Curves[i].AD * ux);
                }
                return true;
            }
        }

        #region E

        int AD2Value_E(int ad, AD2ValueFlag flag)
        {
            int i;
            int thick;

            if (Curves.Count() < 1) return -1;
            if (ad < 0) return -1;
            if (ad == 0) ad = 1;
            if (flag == AD2ValueFlag.NoRevised)
            {
                for (i = 0; i < Curves.Count(); i++)
                {
                    if (ad < Curves[i].AD)
                        continue;
                    else
                        break;
                }
            }
            else
            {
                for (i = 0; i < Curves.Count(); i++)
                {
                    if (ad < Curves[i].RevisedAD)
                        continue;
                    else
                        break;
                }
            }
            if (i >= Curves.Count()) i = Curves.Count() - 1;

            if (i == 0) i = 1;
            if (flag == AD2ValueFlag.NoRevised)
            {
                double u;

                u = Math.Log((double)Curves[i - 1].AD / Curves[i].AD, Math.E) * 100 / (Curves[i].Value - Curves[i - 1].Value);
                thick = (int)(Math.Log((double)Curves[i - 1].AD / ad, Math.E) * 100 / u + Curves[i - 1].Value);
            }
            else
            {
                double u;

                u = Math.Log((double)Curves[i - 1].RevisedAD / Curves[i].RevisedAD, Math.E) * 100 / (Curves[i].Value - Curves[i - 1].Value);
                thick = (int)(Math.Log((double)Curves[i - 1].RevisedAD / ad, Math.E) * 100 / u + Curves[i - 1].Value);

            }
            //if (thick < 0)
            //    return 0;

            return thick;
        }
        #endregion
        #region 线性
        int AD2Value_Line(int ad, AD2ValueFlag flag)
        {
            int i;
            int thick;

            if (Curves.Count() < 2) return -1;
            if (ad < 0) return -1;
            if (ad == 0) ad = 1;
            bool isDescending = true;//降序排列
            if (Curves[0].AD < Curves[1].AD)
                isDescending = false;
            //找 ad0<ad<adi

            if (flag == AD2ValueFlag.NoRevised)
            {
                if (isDescending)//降序排列
                {
                    for (i = 0; i < Curves.Count(); i++)
                    {
                        if (ad < Curves[i].AD)
                            continue;
                        else
                            break;
                    }
                }
                else
                {
                    for (i = 0; i < Curves.Count(); i++)
                    {
                        if (ad > Curves[i].AD)
                            continue;
                        else
                            break;
                    }
                }
                if (i >= Curves.Count()) i = Curves.Count() - 1;
                if (i == 0) i = 1;

                double adi_ad0 = Curves[i].AD - Curves[i - 1].AD;
                double vi_v0 = Curves[i].Value - Curves[i - 1].Value;
                double a = vi_v0 / adi_ad0;
                double b = Curves[i - 1].Value - Curves[i - 1].AD * a;

                thick = (int)(ad * a + b);
                return thick;
            }
            else
            {
                if (isDescending)//降序排列
                {
                    for (i = 0; i < Curves.Count(); i++)
                    {
                        if (ad < Curves[i].RevisedAD)
                            continue;
                        else
                            break;
                    }
                }
                else
                {
                    for (i = 0; i < Curves.Count(); i++)
                    {
                        if (ad > Curves[i].RevisedAD)
                            continue;
                        else
                            break;
                    }
                }
                if (i >= Curves.Count()) i = Curves.Count() - 1;
                if (i == 0) i = 1;

                double adi_ad0 = Curves[i].RevisedAD - Curves[i - 1].RevisedAD;
                double vi_v0 = Curves[i].Value - Curves[i - 1].Value;
                double a = vi_v0 / adi_ad0;
                double b = Curves[i - 1].Value - Curves[i - 1].RevisedAD * a;

                thick = (int)(ad * a + b);
                return thick;
            }
        }
        #endregion

        public double AD2Value(int ad, AD2ValueFlag flag)
        {
            int value;
            switch (Flag)
            {
                case CurveType.Line:
                    value = AD2Value_Line(ad, flag);
                    break;
                default:
                    value = AD2Value_E(ad, flag);
                    break;
            }
            return value / 100.0;
        }


        public bool Load()
        {
            return CurveCollectionJsonDb.Load(this, param_path);
        }
        public bool Save()
        {
            return CurveCollectionJsonDb.Save(this, param_path);
        }

        #region INotifyPropertyChanged 成员

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        #endregion
    }


    public class CurveCollectionJsonDb
    {
        static Mapper Mapper { get; } = new AutoMapper.Mapper(new MapperConfiguration(c =>
        {
            c.CreateMap<CurveCollection, CurveCollectionJsonDb>().ReverseMap();
        }));
        public static bool Load(CurveCollection src, string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    string json = File.ReadAllText(filePath);
                    var p = JsonConvert.DeserializeObject<CurveCollectionJsonDb>(json);
                    Mapper.Map(p, src);
                    return true;
                }
            }
            catch
            {
                //异常，没有json 解码失败
            }

            return false;
        }
        public static bool Save(CurveCollection src, string filePath)
        {
            var p = Mapper.Map<CurveCollectionJsonDb>(src);
            try
            {
                File.WriteAllText(filePath, JsonConvert.SerializeObject(p, Formatting.Indented));
                return true;
            }
            catch
            {
                //异常，没有json 编码失败

            }
            return false;

        }

        /// <summary>
        /// AD曲线校正方式
        /// </summary>
        public CurveCorrectWay CorrectWay = CurveCorrectWay.OnePointIsScale;

        public CurveType Flag = CurveType.E;

        public CurveCell[] Curves = new CurveCell[] {
            new CurveCell() { AD = 57564, Value = 0 },
            new CurveCell() { AD = 30850, Value = 8800 },
            new CurveCell() { AD = 19000, Value = 17600 },
            new CurveCell() { AD = 12528, Value = 26400 },
            new CurveCell() { AD = 8409, Value = 35200 },
            new CurveCell() { AD = 5650, Value = 44000 },
            new CurveCell() { AD = 3779, Value = 52800 },
            new CurveCell() { AD = 2513, Value = 61600  },
            new CurveCell() { AD = 1660, Value = 70400 }
        };
    }
}
