using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using MySystem.Models;
using Library;
using LitJson;
using System.Drawing.Imaging;
using System.Drawing;

namespace MySystem
{
    public class MakeReferenceQrCodeService
    {
        public readonly static MakeReferenceQrCodeService Instance = new MakeReferenceQrCodeService();
        private MakeReferenceQrCodeService()
        { }

        public void StartListen()
        {
            Thread th = new Thread(Loop);
            th.IsBackground = true;
            th.Start();
        }

        private void Loop()
        { 
            bool op = true;
            while (op)
            {
                string content = RedisDbconn.Instance.RPop<string>("MakeReferenceQrCode");
                if (!string.IsNullOrEmpty(content))
                {
                    Start(content);
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }

        public void Start(string uid)
        {
            try
            {
                int UserId = int.Parse(function.CheckInt(uid));
                if (UserId > 0)
                {
                    WebCMSEntities db = new WebCMSEntities();
                    Users user = db.Users.FirstOrDefault(m => m.Id == UserId);
                    if (user != null)
                    {
                        string resultpath = MergeQrCode(user);
                        user.ReferenceQrCode = resultpath;
                        db.SaveChanges();
                        WebCMSEntities pxcdb = new WebCMSEntities();
                        Users tmpuser = pxcdb.Users.FirstOrDefault(m => m.Id == UserId);
                        if (tmpuser != null)
                        {
                            tmpuser.ReferenceQrCode = user.ReferenceQrCode;
                            pxcdb.SaveChanges();
                        }
                        pxcdb.Dispose();
                    }
                    db.Dispose();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public_service");
            }
        }
        public string MergeQrCode(Users user, int pid = 0)
        {
            string BgPic = "QrCodeBg.png";
            if (pid > 0)
            {
                BgPic = "QrCodeBg" + pid + ".png";
            }
            string path = function.CreateQRCode2(ConfigurationManager.AppSettings["SourceHost"].ToString() + "p/user-inviteregist-1?Id=" + user.Id, function.MD5_16(user.Id.ToString() + "9527"), "/bsserver_com/static/ReferenceQrCode/");
            path = path.Replace("//", "/");
            string resultpath = "/bsserver_com/static/ReferenceQrCode/" + function.MD5_16(user.Id.ToString() + "9527") + "Pic.png";
            MakeQRCode(function.getPath("/static/" + BgPic), function.getPath(path), function.getPath(resultpath), user, pid);
            return resultpath.Replace("bsserver_com/", "");
        }

        public void MakeQRCode(string sourcepath, string qrcode, string resultpath, Users us, int pid = 0)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(sourcepath);
            System.Drawing.Image qrcodepic = System.Drawing.Image.FromFile(qrcode);
            //获取图片宽高
            int Width = image.Width;
            int Height = image.Height;
            //创建一个位图文件
            Bitmap BitmapResult = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            //在位图文件上填充一个矩形框
            Graphics Grp = Graphics.FromImage(BitmapResult);
            System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(0, 0, Width, Height);
            //定义一个白色的画刷
            // SolidBrush mySolidBrush = new SolidBrush(System.Drawing.Color.White);
            //Grp.Clear(Color.White);
            //将矩形框填充为白色
            // Grp.FillRectangle(mySolidBrush, Rec);
            //向矩形框内填充Img

            Grp.DrawImage(image, 0, 0, Rec, GraphicsUnit.Pixel);
            Grp.DrawImage(qrcodepic, 340, 605, 326, 326);

            //写字
            Font f = new Font("PingFang SC", 34);
            Font f2 = new Font("PingFang SC", 30);
            Color color = Color.FromArgb(255, 255, 255, 255);
            if (pid > 0 && pid != 2)
            { 
                color = Color.FromArgb(255, 0, 0, 0);
            }
            Brush b = new SolidBrush(color);
            Brush b2 = new SolidBrush(color);
            StringFormat sf = new StringFormat();
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;
            Grp.DrawString(us.RealName, f, b, new RectangleF()
            {
                X = 0,
                Y = 980,
                Width = Width,
                Height = 50,
            }, sf);
            Grp.DrawString("推荐码：" + us.MakerCode, f2, b2, new RectangleF()
            {
                X = 0,
                Y = 1030,
                Width = Width,
                Height = 50,
            }, sf);
            //返回位图文件
            ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Png);
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);//这里的50L用来设置保存时的图片质量
            myEncoderParameters.Param[0] = myEncoderParameter;
            BitmapResult.Save(resultpath, jpgEncoder, myEncoderParameters);
            image.Dispose();
            qrcodepic.Dispose();
            Grp.Dispose();
            BitmapResult.Dispose();
        }

        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }
}