using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using Newtonsoft.Json.Linq;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Kingo.PluginServiceInterface.Model
{
    public class PhotoInfo : INotifyPropertyChanged
    {
        public PhotoInfo()
        {
            checkedVisibility = Visibility.Visible;
            isChecked = false;
        }
        public int IsChecked { get; set; } = 1;
        public string FID { get; set; }
        public int BSM { get; set; }
        public string HCJLBSM { get; set; }
        public string TBBH { get; set; }
        public string TCBM { get; set; }
        public string FJLX { get; set; }
        public int MODE { get; set; }
        public string FJMC { get; set; }
        public double ZBX { get; set; }
        public double ZBY { get; set; }
        public double XZB { get; set; }
        public double YZB { get; set; }
        public double MaxX { get; set; }
        public double MinX { get; set; }
        public double MinY { get; set; }
        public double MaxY { get; set; }
        public int WKID { get; set; }
        public string ARG { get; set; }
        private byte[] _arg4;
        public byte[] ARG4
        {
            get { return _arg4; }
            set
            {
                _arg4 = value;
                this.FJ = _arg4;
            }
        }
        public byte[] FJ { get; set; }
        public double PSJD { get; set; }
        public double PSGD { get; set; }
        public string PSSJ { get; set; }
        public string JZRY { get; set; }
        private string _cjsj;
        public string CJSJ
        {
            get
            {
                return _cjsj;
            }
            set
            {
                _cjsj = value;
                this.PSSJ = _cjsj;
            }
        }
        public double Longitude { get; set; }
        public double Latitude { get; set; }
        public string TBYBH { get; set; }
        private string jsonStr { get; set; }
        public string POINTS_JSON
        {
            get { return jsonStr; }
            set
            {
                try
                {
                    jsonStr = value;
                    if (string.IsNullOrWhiteSpace(jsonStr))
                    {
                        KGIS.Framework.Utils.LogAPI.Debug("照片ARG:" + this.ARG + "  Points_json为空!");
                        return;
                    }
                    var jObjectStr = JArray.Parse(jsonStr);
                    if (jObjectStr != null && jObjectStr.Count > 0)
                    {
                        var jObject = jObjectStr[0];
                        if (jObject["x"] != null && !string.IsNullOrWhiteSpace(jObject["x"].ToString()))//X坐标
                        {
                            this.XZB = double.Parse(jObject["x"].ToString());
                        }
                        if (jObject["y"] != null && !string.IsNullOrWhiteSpace(jObject["y"].ToString()))//Y坐标
                        {
                            this.YZB = double.Parse(jObject["y"].ToString());
                        }
                        double yaw = 0.0;
                        if (jObject["yaw"] != null && !string.IsNullOrWhiteSpace(jObject["yaw"].ToString()))//手机围绕Z轴翻转角度
                        {
                            yaw = double.Parse(jObject["yaw"].ToString());
                        }
                        double roll = 0.0;
                        if (jObject["roll"] != null && !string.IsNullOrWhiteSpace(jObject["roll"].ToString()))//围绕X轴左右翻转角度
                        {
                            roll = double.Parse(jObject["roll"].ToString());
                        }
                        this.PSJD = (yaw - roll + 360) % 360;
                        if(Platform.Instance.SystemType == SystemTypeEnum.DTBJK && SysConfigsOprator.GetAppsetingValueByKey("ArearName").Equals("11"))
                        {
                            PSJD = yaw;
                        }
                    }
                }
                catch (Exception ex)
                {
                    KGIS.Framework.Utils.LogAPI.Debug("举证照片POINTS_JSON解析异常:" + ex.Message);
                }
            }
        }
        public string GROUPCODE { get; set; }
        public string GROUP_NAME_USER { get; set; }
        /// 
        /// hcdb路径
        /// 
        public string hcdbpath { get; set; }
        /// 
        /// 是否是正射照片
        /// 
        public bool IsZS { get; set; }
        /// 
        /// 是否是无人机
        /// 
        public bool IsWRJ { get; set; }
        /// 
        /// 图片所属表(用于删除图片)
        /// 
        public string ImageType { get; set; }
        public object Tag { get; set; }
        private string imagePath = null;
        //{ return string.Format(@"{0}\举证成果\附件\{1}\{2}", Path.GetDirectoryName(Env.Instance.ProjectPath), TBYBH , FJMC); }
        public string ImagePath { get { return imagePath; } set { imagePath = value; } }
        public double Angle { get; set; }
        public string HCRY { get; set; }
        public int SFXZ { get; set; }
        private Visibility checkedVisibility;
        /// 
        /// 选择复选框显示属性
        /// 
        public Visibility CheckedVisibility
        {
            get { return checkedVisibility; }
            set
            {
                checkedVisibility = value;
                PropertyChangedByname("CheckedVisibility");
            }
        }
        private bool isChecked = true;
        /// 
        /// 是否选中
        /// 
        public bool isSelected
        {
            get { return isChecked; }
            set
            {
                isChecked = value;
                PropertyChangedByname("isSelected");
            }
        }
        private ImageSource imageSource;
        /// 
        /// 图片数据源
        /// 
        public ImageSource ImageSource
        {
            get
            {
                return imageSource;
            }
            set
            {
                imageSource = value;
                PropertyChangedByname("ImageSource");
            }
        }
        private string imglocalpath;
        /// 
        /// 图片相对地址(保存本地时需要)如果为空,则随机生成
        /// 
        public string ImgLocalPath
        {
            get
            {
                if (string.IsNullOrEmpty(imglocalpath))
                {
                    return Guid.NewGuid().ToString();
                }
                return imglocalpath;
            }
            set { imglocalpath = value; }
        }
        private string localpath;
        /// 
        /// 获取图片本地地址
        /// 
        public string LocalPath
        {
            get
            {
                //return string.Format(@"{0}\外业调查结果\图片\{1}\{2}", Path.GetDirectoryName(KGIS.Framework.Platform.Platform.Instance.GetProjectInfo().GetProjDBPath()), TBBH.Substring(0, 2), FJMC);
                return "";
            }
            set { localpath = value; }
        }
        /// 
        /// 根据网络路径更新图片
        /// 
        public void UpdateSource()
        {
            if (string.IsNullOrEmpty(sourceurl))
            {
                SetImageSource(null);
                return;
            }
            GetPhotoInfo(SourceURL);
        }
        /// 
        /// 异步获取图片
        /// 
        /// 
        private void GetPhotoInfo(string aPhotoUrl)
        {
            //如果是HTTP下载文件
            WebClient client = new WebClient();
            client.DownloadDataCompleted += client_DownloadDataCompleted;
            client.DownloadDataAsync(new Uri(aPhotoUrl));
        }
        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null || e.Result == null || e.Result.Count() == 0)
                {
                    SetImageSource(null);
                    return;
                }
                SetImageSource(e.Result);
            }
            catch (Exception)
            {
            }
        }
        private void SetImageSource(byte[] ImgResult)
        {
            if (ImgResult == null || ImgResult.Length == 0)
            {
                isNoimg = true;
                //ImageSource = new BitmapImage(new Uri("/Kingo.ImgDisplayControl;component/Images/zwtp.png", UriKind.RelativeOrAbsolute));
                return;
            }
            SaveFile(ImgResult);
        }
        public void SaveFile(byte[] filebyte = null)
        {
            try
            {
                string basepath = ImagePath;
                string dirpath = basepath.Substring(0, basepath.LastIndexOf('\\'));
                if (!Directory.Exists(dirpath))
                {
                    Directory.CreateDirectory(dirpath);
                }
                if (filebyte == null)
                    filebyte = ImageToByte(imageSource);
                File.WriteAllBytes(basepath, filebyte);
            }
            catch (Exception)
            {
                if (filebyte == null)
                    return;
                using (var ms = new MemoryStream(filebyte))
                {
                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.StreamSource = ms;
                    image.EndInit();
                    ImageSource = image;
                    ms.Dispose();
                }
            }
        }
        private bool isNoimg;
        /// 
        /// 是否无图片
        /// 
        public bool IsNoimg
        {
            get { return isNoimg; }
        }
        private string sourceurl;
        /// 
        /// 图片网络地址
        /// 
        public string SourceURL
        {
            get { return sourceurl + "?s=" + Guid.NewGuid(); }
            set { sourceurl = value; }
        }
        private void PropertyChangedByname(string pname)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(pname));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public void RotateImg(double angle)
        {
            try
            {
                TransformedBitmap tb = new TransformedBitmap();
                tb.BeginInit();
                //BitmapSource bs = (BitmapSource)ImageSource;//图片源
                tb.Source = (BitmapSource)ImageSource;
                RotateTransform transform = new RotateTransform(angle);
                tb.Transform = transform;
                tb.EndInit();
                ImageSource = tb;
                //TransformedBitmap tb = new TransformedBitmap();
                //tb.BeginInit();
                //BitmapSource bs = (BitmapSource)ImageSource;//图片源
                //tb.Source = bs;
                //RotateTransform transform = new RotateTransform(angle);
                //tb.Transform = transform;
                //tb.EndInit();
                //ImageSource = tb;
                //if (File.Exists(ImagePath))
                //{
                //    byte[] bb = ImageToByte(bs);
                //    File.WriteAllBytes(ImagePath, bb);//选择后保存本地路径
                //    ImageSource = tb;
                //}
            }
            catch
            {
            }
        }
        /// 
        /// 根据文件扩展名获取图片编码器
        /// 
        /// 文件路径
        /// 图片编码器
        private BitmapEncoder GetBitmapEncoder(string filePath)
        {
            var extName = Path.GetExtension(filePath).ToLower();
            if (extName.Equals(".png"))
            {
                return new PngBitmapEncoder();
            }
            else
            {
                return new JpegBitmapEncoder();
            }
        }
        #region 旋转图片处理方法
        private byte[] ImageToByte(ImageSource imgsource)
        {
            BitmapSource s = imgsource as BitmapSource;
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(s.PixelWidth, s.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            System.Drawing.Imaging.BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            s.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bmp.UnlockBits(data);
            byte[] bb = Bitmap2Byte(bmp);
            return bb;
        }
        private byte[] BitmapToBytes(Bitmap Bitmap)
        {
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                Bitmap.Save(ms, Bitmap.RawFormat);
                byte[] byteImage = new Byte[ms.Length];
                byteImage = ms.ToArray();
                return byteImage;
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }
        }
        private byte[] Bitmap2Byte(Bitmap bitmap)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }
        #endregion
    }
}