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

namespace ButcherFactory.WeightCount_
{
  public static class WeightCountPrint
  {
    static int id = 1;
    const string TEMPLATE = @"PrintTemplate\WeightCountPrint.html";
    const string IMGFILE = @"TempImg\_img{0}.png";
    public static void Print(WeightCountEntity entity)
    {
      var dic = new Dictionary<string, string>();
      dic.Add("$Goods_Name", entity.Goods_Name);
      dic.Add("$Weight", string.Format("0:#0.##",entity.Weight));
      dic.Add("$Date", DateTime.Today.ToString("yyyy/MM/dd"));
      dic.Add("$BarCode", string.Format("0:#0.##", entity.Weight));
      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(BO.Utils.AppContext.ConnectInfo.TraceBackUrl + "?code={0}", entity.BarCode);
      BwpClientPrint.BwpClientWebPrint.Create2DPic(url, imgUrl, 120);

      dic.Add("$ImageUrl", imgUrl);
      BwpClientPrint.BwpClientWebPrint.Print(TEMPLATE, dic);
      AfterPrint();
    } 
    
    static DirectoryInfo TempImage = null;
    private static void AfterPrint()
    {
      if (id == 20)
        id = 0;
      id++;
      if (TempImage == null)
        TempImage = new DirectoryInfo("TempImg");
      var files = TempImage.GetFiles();
      if (files.Length > 10)
      {
        var last = files.OrderBy(x => x.CreationTime).First().FullName;
        File.Delete(last);
      }
    }
  }
}
