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 (AppContext.ConnectInfo.TraceBackUrl == "default")
                throw new Exception("请先配置追溯服务器地址");

            var dic = new Dictionary<string, string>();
            var entity = entitys.FirstOrDefault();
            var groupByGoods = entitys.GroupBy(x => x.Goods_ID);
            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}</p>", item.Count());  
            }


            dic.Add("$Goods_Name", info);
            dic.Add("$Date", DateTime.Now.ToString("yyyy/MM/dd HH:mm"));
            var code = entity.BarCode;
            if (code.Length > 17)
                code = code.Substring(17);
            dic.Add("$Code", code);
            var imgUrl = string.Format(IMGFILE, id);
            var url = string.Format(AppContext.ConnectInfo.TraceBackUrl + "?code={0}", entity.BarCode);
            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();
            }
        }
    }
}
