using ButcherFactory.BO;
using ButcherFactory.BO.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ButcherFactory.SegmentProduction_
{
    public static class SegmentSumCodePrint
    {
        static int id = 1;
        const string PRINTFILE = @"PrintTemplate\";
        const string ENDFILE = @"PrintTemplate\SegmentProductionPrintEnd.html";
        const string IMGFILE = @"TempImg\_sum_img{0}.png";
        public static void Print(SegmentProduction[] entitys, string template)
        {
            if (BO.Utils.AppContext.ConnectInfo.TraceBackUrl == "default")
                throw new Exception("请先配置追溯服务器地址");

            var dic = new Dictionary<string, string>();
            var entity = entitys.FirstOrDefault();
            var groupByGoods = entitys.GroupBy(x =>new { x.Goods_ID, x.Identify });
            var info = string.Empty;
            foreach (var item in groupByGoods)
            {
                var f = item.FirstOrDefault();
                info += string.Format("<p class='g_name'>{0}</p>", f.Goods_Name);
                info += string.Format("<p class='g_number'>件数：{0} &nbsp;&nbsp; {1}</p>", item.Count(), f.Identify);
                info += string.Format("<p class='g_weight'>总重量：{0:#0.######}KG </p>", item.Sum(x=>x.Weight));
            }


            dic.Add("$Goods_Name", info);
            dic.Add("$Date", DateTime.Now.ToString("yyyy/MM/dd HH:mm"));
            var code = entity.TotalCode_Code;
            if (!string.IsNullOrEmpty(code))
            {
                if (code.Length > 6)
                    code = code.Substring(code.Length - 6);
            } 
            dic.Add("$Code", code);
            var imgUrl = string.Format(IMGFILE, id);
            var url = string.Format("{0}",entity.TotalCode_Code);
            BwpClientPrint.BwpClientWebPrint.Create2DPic(url, imgUrl, 120);
            dic.Add("$ImageUrl", imgUrl);

            BwpClientPrint.BwpClientWebPrint.Print(PRINTFILE + template, dic);
            AfterPrint();
        }

        static DirectoryInfo TempImage = null;
        private static void AfterPrint()
        {
            if (id == 100)
                id = 0;
            id++;
            if (TempImage == null)
                TempImage = new DirectoryInfo("TempImg");
            var files = TempImage.GetFiles();
            while (files.Length > 100)
            {
                var last = files.OrderBy(x => x.CreationTime).First().FullName;
                File.Delete(last);
                files = TempImage.GetFiles();
            }
        }
    }
}
