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 SegmentProductionPrint
  {
    static int id = 1;
    const string PRINTFILE = @"PrintTemplate\";
    const string ENDFILE = @"PrintTemplate\SegmentProductionPrintEnd.html";
    const string IMGFILE = @"TempImg\_img{0}.png";
    static string CustomerDefine = "GB/T9959.2-2008";
    public static void Print(SegmentProduction entity, DateTime? dt, string template)
    {
      if (BO.Utils.AppContext.ConnectInfo.TraceBackUrl == "default")
        throw new Exception("请先配置追溯服务器地址");
      if (dt == null)
        dt = DateTime.Today;
      var dic = new Dictionary<string, string>();
      dic.Add("$ShotPrintName", entity.ShotPrintName);
      dic.Add("$Goods_Name", entity.Goods_Name);
      var info = string.Empty;
      if (entity.StandardPic)
        info = string.Format("规格：{0}", entity.Goods_Spec);
      else
        info = string.Format("重量：{0:#0.##}{1}", entity.Weight, entity.MainUnit);
      dic.Add("$Info", info);
      dic.Add("$Date", dt.Value.ToString("yyyy/MM/dd"));
      var customerDefine = entity.Goods_CustomerDefine;
      if (string.IsNullOrEmpty(customerDefine))
        customerDefine = CustomerDefine;
      dic.Add("$CustomerDefine", customerDefine);
      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);
      dic.Add("$Identity", entity.Identify);

      var barImgUrl = string.Format(IMGFILE, id + "_bar");
      try
      {
        BwpClientPrint.BwpClientWebPrint.CreateBarCode("69212203" + entity.Goods_Code, barImgUrl, new Size(120, 40));
      }
      catch (Exception ex)
      {
        if (ex.Message == "Contents do not pass checksum")
        {
          BwpClientPrint.BwpClientWebPrint.CreateBarCode("69738841" + entity.Goods_Code, barImgUrl, new Size(120, 40));
        }
      }
      dic.Add("$BarImg", barImgUrl);
      string unit = entity.MainUnit;
      int rate = 1;
      if (unit.ToUpper() == "KG")
      {
        rate = 1000;
        unit = "g";
      }
      dic.Add("$Weight", string.Format("{0:#0.##}{1}", entity.Weight * rate, unit));

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

    public static void PrintEnd(List<SegmentProduction> list)
    {
      string firstRow = "<tr><td><span>{0}:</span></td><td>{1}</td><td>{2:#0.######}</td><td rowspan='{3}' style='width:120px'><img src='$ImageUrl' style='width:120px;height:120px;margin-top:-5px;'/></td></tr>";
      string template = "<tr><td><span>{0}:</span></td><td>{1}</td><td>{2:#0.######}</td></tr>";
      var builder = new StringBuilder();
      bool first = true;
      var count = list.GroupBy(x => x.Goods_Name).Count();
      foreach (var item in list.GroupBy(x => x.Goods_Name))
      {
        var weight = item.Sum(x => x.Weight);
        var num = item.Count();
        if (first)
        {
          builder.Append(string.Format(firstRow, item.Key, num, weight, count));
          first = false;
        }
        else
          builder.Append(string.Format(template, item.Key, num, weight));
      }
      var dic = new Dictionary<string, string>();
      dic.Add("$tableContent", builder.ToString());
      var groupID = list.First().GroupID.ToString();
      var imgUrl = string.Format(IMGFILE, id);
      BwpClientPrint.BwpClientWebPrint.Create2DPic(groupID, imgUrl, 120);
      dic.Add("$ImageUrl", imgUrl);
      dic.Add("$DateTime", DateTime.Now.ToString("yyyy/MM/dd HH:ss"));
      BwpClientPrint.BwpClientWebPrint.Print(ENDFILE, 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();
      }
    }
  }
}
