using ButcherFactory.BO;
using ButcherFactory.BO.LocalBL;
using ButcherFactory.BO.Rpcs;
using ButcherFactory.BO.Utils;
using ButcherFactory.Dialogs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormControl;
using ButcherFactory.Utils;
using NotAuto = ButcherFactory.SegmentProduction_;
using ButcherFactory.Controls;
using System.Runtime.InteropServices;

namespace ButcherFactory.SegmentProductionAuto_
{
  public partial class SegmentProductionAutoForm : Form, IWithRoleForm
  {
    public List<short> RoleName
    {
      //get { return new List<short> { (short)设备类别.分割生产自动化 }; }
      get { return new List<short> { (short)设备类别.分割生产 }; }
    }

    public Form Generate()
    {
      return this;
    }

    Thread uploadData;
    Thread checkInStoreState;
    Thread initTask;
    BindingList<SegmentProduction> historyList;
    BindingList<long?> deleteList;
    BindingList<TotalCode> allCode;
    Dictionary<string, List<ClientGoodsSet_Detail>> goodsSetDic;
    long? batchID;
    DateTime? batchDate;
    DateTime butcherDate = DateTime.Today;
    NotAuto.SegmentProductionFormConfig config;
    List<GoodsIdentify> identityList;
    List<string> specialGoodsCodes;
    public SegmentProductionAutoForm()
    {
      InitializeComponent();
      butcherDateBox.Text = butcherDate.ToString("yyyy-MM-dd");
      netStateWatch1.GetConnectState = () => LoginUtil.TestConnection(500);
      this.FormClosing += SegmentProductionAutoForm_FormClosing;
      workUnitSelect.SelectedIndexChanged += delegate
      {
        if (workUnitSelect.SelectedValue == null)
          config.WorkUnitID = null;
        else
          config.WorkUnitID = (long)workUnitSelect.SelectedValue;
        XmlUtil.SerializerObjToFile(config);
      };
      productBatchSelect.SelectedIndexChanged += delegate
      {
        if (productBatchSelect.SelectedValue == null)
        {
          batchID = null;
          batchDate = null;
        }
        else
        {
          var entity = productBatchSelect.SelectedItem as ProductBatch;
          batchID = entity.ID;
          batchDate = entity.Date;
        }
      };
    }

    void SegmentProductionAutoForm_FormClosing(object sender, FormClosingEventArgs e)
    { 
      if (initTask != null && initTask.IsAlive)
        initTask.Abort();
      if (uploadData != null && uploadData.IsAlive)
        uploadData.Abort();
      if (checkInStoreState != null && checkInStoreState.IsAlive)
        checkInStoreState.Abort();
      if (Utils.mPortOpened)
        closePort();
    }

   public WeightDetails mCache;

    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
      initTask = new Thread(LoadBind);
      initTask.Start();

      checkInStoreState = new Thread(CheckInStored);
      checkInStoreState.Start();

      uploadData = new Thread(UpLoadLocalData);
      uploadData.Start();
      mCache = XmlUtil.DeserializeFromFile<WeightDetails>();
      var codes = XmlUtil.ReadAllText("MesGoodsCode.txt");
      if (string.IsNullOrEmpty(codes))
        specialGoodsCodes = new List<string>();
      else
        specialGoodsCodes = codes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
      var del = new List<long>();
      if (mCache.Cache == null)
      {
          mCache.Cache = new Dictionary<long, List<decimal>>();
      }
      foreach (var item in mCache.Cache)
      {
          if (item.Value == null || item.Value.Count == 0)
          {
              del.Add(item.Key);
          }
      }
      foreach (var v in del)
      {
          mCache.Cache.Remove(v);
      }
      wDic = mCache.Cache;
      _freshTotalCode = SegmentProductionBL.InitFreshTotalCode();
      _stayTotalCode = SegmentProductionBL.InitStayTotalCode();
      identityList = SegmentProductionBL.GetGoodsIdentify();

    }

    void LoadBind()
    {
      BLUtil.DeleteLocalDb<SegmentProduction>();
      SegmentProductionBL.DeleteBefore();
      GetBasicInfo();
    }

    bool ok = false;
    bool bind = false;
    void GetBasicInfo()
    {
      while (!ok)
      {
        try
        {
          var changed = BaseInfoSyncRpc.SyncGoodsByTag(ApplyClient.分割品);
          changed = BaseInfoSyncRpc.SyncBaseInfo<WorkUnit>() || changed;
          changed = BaseInfoSyncRpc.SyncProductBatch(1) || changed;
          changed = BaseInfoSyncRpc.SyncGoodsIdentify(out identityList) || changed;
          ok = true;
          if (changed || !bind)
            BindBasicInfo();
          this.Invoke(new Action(() =>
          {
            msglbl.Text = string.Empty;
          }));
        }
        catch
        {
          
          if (!bind)
          {
            BindBasicInfo();
            bind = true;
          }
        }
        Thread.Sleep(500);
      }
    }

    void BindBasicInfo()
    {
        this.BeginInvoke(new Action(() =>
      {
        productBatchSelect.EBindComboBox<ProductBatch>(null, 6, "Date");
        config = XmlUtil.DeserializeFromFile<NotAuto.SegmentProductionFormConfig>();
        var m = config.WorkUnitID;
        workUnitSelect.EBindComboBox<WorkUnit>(x => x.ID == m, top: 100);

        BindGoods();
        BindGrid();
      }));
    }

    void BindGoods()
    {
      goodsSetDic = FormClientGoodsSetBL.GetSelectedDetail();
      flowLayoutPanel1.Controls.Clear();
      flowLayoutPanel2.Controls.Clear();
      foreach (var item in goodsSetDic)
      {
        var btn = new ColorButton() { Width = 100, Height = 62, Text = item.Key, Font = new Font("宋体", 15), Margin = new Padding(15, 3, 15, 0), EnableGroup = true };
        btn.Click += GroupGoodsSetClick;
        flowLayoutPanel1.Controls.Add(btn);
      }
    }

    Color goodsColor = Color.FromArgb(250, 120, 24);
    string groupKey = string.Empty;
    public Dictionary<long, List<decimal>> wDic = new Dictionary<long, List<decimal>>();
    void GroupGoodsSetClick(object sender, EventArgs e)
    {
        flowLayoutPanel2.Controls.Clear();
        var groupBtn = sender as ColorButton;
        groupKey = groupBtn.Text;
        var arr = goodsSetDic[groupKey];
        foreach (var item in arr)
        {
            var bTag = new ButtonTag();
            if ((item.EachNumber ?? 0) > 0)
            {
                bTag.Label.MaxCount = item.EachNumber.Value;
                if (wDic.ContainsKey(item.Goods_ID))
                {
                   var l = wDic[item.Goods_ID];
                   bTag.Label.Text = string.Format("{0}-{1}", item.EachNumber.Value, l.Count);
                }
                else
                {
                    bTag.Label.Text = string.Format("{0}-0", item.EachNumber.Value);
                }
                ClientGoodsSet_Detail g = item;
                bTag.Button.Click += delegate
                {
                    if (batchID == null) {
                      MessageBox.Show("请先选择批次！");
                      return;
                    }
                    if (g.GoodsType == 1 && !g.NoTotalCode)
                    {
                      if (_totalCode == null || _codePanel == null)
                      {
                        MessageBox.Show("请先选择总码！");
                        return;
                      }
                    }
                  if (!status.StableStatus)
                  {
                    MessageBox.Show("称重稳定后再操作！");
                    return;
                  }
                  decimal weight = 0;
                  if (!decimal.TryParse(lblChengZhong.Text, out weight)) {
                    MessageBox.Show("重量错误，是否未归零！");
                    return;
                  }
//#if DEBUG
//                    if (weight == 0)
//                        weight = (g.StandardWeightLow ?? 4.0m) + 0.1m;
//#endif
                    if (weight <= 0)
                    {
                    //weight = 10;
                      MessageBox.Show("重量必须大于0");
                      return;
                    }    
                    if (g.StandardWeight.HasValue)
                    {
                        if (weight < (g.StandardWeightLow ?? 0) || weight > (g.StandardWeightUp ?? 0))
                        {
                           MessageBox.Show(string.Format("重量必须在{0:#0.######}-{1:#0.######}之间", g.StandardWeightLow, g.StandardWeightUp));
                           return;
                        }  
                        weight = g.StandardWeight.Value;
                    }
                    List<decimal> l = null;
                    if (wDic.ContainsKey(g.Goods_ID))
                    {
                        l = wDic[g.Goods_ID];
                        if (l.Count >= g.EachNumber.Value)
                        { 
                            l.Clear();
                        }
                        l.Add(weight);
                    }
                    else
                    {
                        wDic.Add(g.Goods_ID, l = new List<decimal>() { weight });
                    }
                    bTag.Label.MinCount = l.Count();
                    if (l.Count >= g.EachNumber.Value)
                    {
                        weight = l.Sum(x => x);
                        InsertSegmentProduction(g, weight); 
                    }
                    mCache.Cache = wDic;
                    XmlUtil.SerializerObjToFile(mCache);
                };

                bTag.Label.Click += delegate
                {
                    List<decimal> l = new List<decimal>(0);
                    if (wDic.ContainsKey(g.Goods_ID))
                    {
                        l = wDic[g.Goods_ID];
                    }
                    new WeightView(this, bTag).ShowDialog();
                };
            }
            else
            {
                bTag.Label.Visible = false;
                bTag.Button.Click += GoodsBtnClick;
            }
           
            bTag.Button.Tag = item;
            if (item.SelectedIdentify != null) {
              bTag.identityButton.Text = item.SelectedIdentify.Identify;
            }
            item.Identify = identityList.Where(x => x.Goods_ID == item.Goods_ID);
            if (item.Identify.Any())
            {
              bTag.identityButton.Click += delegate
              {
                new IdentifySelectionDialog(item).ShowDialog();
                if (item.SelectedIdentify != null)
                {
                  bTag.identityButton.Text = item.SelectedIdentify.Identify;
                }
                else {
                  bTag.identityButton.Text = "选择标识";
                }
              };
            }
            else {
              bTag.identityButton.Enabled = false;
            }
            bTag.Button.Text = item.Goods_Name;
            bTag.Button.Font = new Font("黑体", 12, FontStyle.Bold);
            bTag.Button.BackColor = Color.Black;
            bTag.Button.Margin = new Padding(10, 10, 10, 35);
            bTag.Button.PlaySound = true;
            bTag.Button.ForeColor = Color.White;
            bTag.Button.Width = 140;
            bTag.Button.Height = 90;
            flowLayoutPanel2.Controls.Add(bTag);
        }
    }

    void GoodsBtnClick(object sender, EventArgs e)
    {
      if (batchID == null)
        throw new Exception("请先选择批次");
      var btn = sender as ColorButton;
      var detail = btn.Tag as ClientGoodsSet_Detail;
      if (!status.StableStatus)
      {
        MessageBox.Show("称重稳定后再操作！");
        return;
      }
      decimal weight = 0;
      if (!decimal.TryParse(lblChengZhong.Text, out weight))
      {
        MessageBox.Show("重量错误，是否未归零！");
        return;
      }
      //#if DEBUG
      // if (weight == 0)
      //  weight = (detail.StandardWeightLow ?? 4.0m) + 0.1m;
      //#endif
      if (weight <= 0)
          throw new Exception("重量必须大于0");

      if (detail.StandardWeight.HasValue)
      {
          if (weight < (detail.StandardWeightLow ?? 0) || weight > (detail.StandardWeightUp ?? 0))
              throw new Exception(string.Format("重量必须在{0:#0.######}-{1:#0.######}之间", detail.StandardWeightLow, detail.StandardWeightUp));
          weight = detail.StandardWeight.Value;
      }
      if (specialGoodsCodes.Contains(detail.Goods_Code))
      {
        var dialog = new GoodsNumberInputDialog(detail);
        if (dialog.ShowDialog() != DialogResult.OK)
          return;
      }
      InsertSegmentProduction(detail, weight);
    }

    private void InsertSegmentProduction(ClientGoodsSet_Detail detail, decimal weight)
    {
      if (detail.GoodsType.HasValue && detail.GoodsType != 0 && string.IsNullOrEmpty(detail.Goods_CustomerDefine))
        throw new Exception("未配置自定义执行标准，请联系管理员处理！");
      var pics = int.Parse(numberInput.Text);
      if (pics <= 0)
        pics = 1;
      else if (pics > 50)
        pics = 50;
      SegmentProduction entity = null;
      for (var i = 0; i < pics; i++)
      {
        entity = new SegmentProduction();
        entity.Goods_ID = detail.Goods_ID;
        entity.Weight = weight;
        entity.WorkUnit_ID = config.WorkUnitID;
        entity.ProductBatch_ID = batchID.Value;
        entity.StandardPic = detail.StandardPic;
        entity.GoodsType = detail.GoodsType;
        entity.NoTotalCode = detail.NoTotalCode;
        entity.ButcherDate = butcherDate;
        if (detail.SelectedIdentify != null)
        {
          entity.Identify = detail.SelectedIdentify.Identify;
          entity.IdentifyRemark = detail.SelectedIdentify.Remark;
        }
        if (!string.IsNullOrEmpty(statisticNumberBox.Text))
          entity.StatisticNumber = decimal.Parse(statisticNumberBox.Text);

        TotalCode thisTotal = null;
        ColorButton thisPanel;
        bool rebuild = false;
        if (entity.GoodsType == 0)
        {
          entity.TotalCode_ID = _freshTotalCode.ID;
          thisTotal = _freshTotalCode;
          thisPanel = _freshPanel;
          if (_totalCode == null || _totalCode.GoodsType != 0)
          {
            foreach (var bt in codeButtons)
            {
              if (bt.Selected)
              {
                bt.Selected = false;
                bt.Invalidate();
              }
            }
            _codePanel = _freshPanel;
            _codePanel.Selected = true;
            _codePanel.Invalidate();
            _totalCode = _freshTotalCode;
            rebuild = true;
          }
        }
        else if (entity.GoodsType == 1 && entity.NoTotalCode)
        {
          entity.TotalCode_ID = _stayTotalCode.ID;
          thisTotal = _stayTotalCode;
          thisPanel = _stayPanel;
          if (_totalCode == null || _totalCode.GoodsType != 1 || !_totalCode.NoTotalCode)
          {
            foreach (var bt in codeButtons)
            {
              if (bt.Selected)
              {
                bt.Selected = false;
                bt.Invalidate();
              }
            }
            _codePanel = _stayPanel;
            _codePanel.Selected = true;
            _codePanel.Invalidate();
            _totalCode = _stayTotalCode;
            rebuild = true;
          }
        }
        else
        {
          if (_totalCode == null || _codePanel == null)
          {
            throw new Exception(string.Format("请先选择总码！"));
          }
          if (_totalCode.GoodsType == 0)
          {
            throw new Exception(string.Format("只有鲜品才可以选择鲜品总码！"));
          }
          else if (_totalCode.GoodsType == 1 && _totalCode.NoTotalCode)
          {
            throw new Exception(string.Format("冻品只有暂存区产品才能选择暂存区！"));
          }
          entity.TotalCode_ID = _totalCode.ID;
          thisTotal = _totalCode;
          thisPanel = _codePanel;
        }

        SegmentProductionBL.InsertAndSetGroupID(entity, batchDate.Value);
        entity.Goods_Code = detail.Goods_Code;
        entity.Goods_Name = detail.Goods_Name;
        entity.Goods_Spec = detail.Goods_Spec;
        entity.MainUnit = detail.MainUnit;
        entity.ShotPrintName = detail.ShotPrintName;
        entity.Goods_CustomerDefine = detail.Goods_CustomerDefine;
        if (rebuild)
        {
          BindflowLayoutPanel(thisPanel, thisTotal);
        }

        var c = initSegmentBt(entity, thisPanel, thisTotal);

        flowLayoutPanel4.Controls.Add(c);
        flowLayoutPanel4.Controls.SetChildIndex(c, 0);

        historyList.Insert(0, entity);

        //if (historyList.Count > 30)
        //    historyList.RemoveAt(30);
        if (barPrintCheck.Checked)
        {
          var template = config.Template;
          if (detail.GoodsType.HasValue)
          {
            if (detail.GoodsType == 0)
              template = "SegmentProductionPrint.html";
            else
              template = "SegmentProductionPrint1.html";
          }
          NotAuto.SegmentProductionPrint.Print(entity, batchDate, template);
          var log = new SegmentLog(entity.BarCode, "打印");
          log.Message = string.Format("存货名称：{0} 重量：{1:#0.###}", entity.Goods_Name, entity.Weight);
          SegmentProductionBL.InsertLog(log);
        }
        else
        {
          var log = new SegmentLog(entity.BarCode, "生产未打印");
          log.Message = string.Format("存货名称：{0} 重量：{1:#0.###}", entity.Goods_Name, entity.Weight);
          SegmentProductionBL.InsertLog(log);
        }
      }
      GoodsLabel.Text = detail.Goods_Name;

      var thd = new Thread(new ParameterizedThreadStart(RefreshTask));
      thd.Start(entity);
    }

    SegmentProduction current;
    ColorButton _labelBt;
    private ColorButton initSegmentBt(SegmentProduction entity, ColorButton parent, TotalCode tCode)
    {
        var bt = new ColorButton() { Text = entity.ShortCode };
        bt.Tag = entity;
        bt.Width = 98;
        bt.Height = 35;
        bt.Font = new Font("黑体", 15, FontStyle.Bold);
        bt.ForeColor = Color.Black;
        bt.BackColor = System.Drawing.SystemColors.ButtonFace;
        
        bt.SelectedColor = Color.Cyan;
        bt.Click += delegate
        { 
            bt.Selected = !bt.Selected;
            if (bt.Selected)
            {
                current = entity;
                _labelBt = bt;
                GoodsLabel.Text = entity.Goods_Name;
                if (_codePanel != null)
                {
                    _codePanel. Selected = false;
                    _codePanel. Invalidate();
                }
                parent .Selected = true;
                parent. Invalidate();
                _totalCode = tCode;
                _codePanel = parent;
            }
            else
            {  
                _labelBt = null;
                current = null; 
                GoodsLabel.Text = "";
            }
            foreach (var bt2 in segmentButtons)
            {
                if (bt2.Text != entity.ShortCode && bt2.Selected)
                {
                    bt2.Selected = false;
                    bt2.Invalidate();
                }
            }

        };
        segmentButtons.Add(bt);
        return bt;
    }

    void RefreshTask(object obj)
    {
        var entity = obj as SegmentProduction;
        var list = SegmentProductionBL.GetProductTask(batchDate ?? DateTime.Today, entity);
        this.Invoke(new Action(() =>
        {
            taskDataGrid.DataSource = list;
            taskDataGrid.Refresh();
        }));
    }

    List<ColorButton> codeButtons = new List<ColorButton>(0);
    List<ColorButton> segmentButtons = new List<ColorButton>(0);

    void BindGrid()
    {
      historyList = SegmentProductionBL.GetListByState(true);
      deleteList = SegmentProductionBL.GetInStoreList();
      allCode = SegmentProductionBL.GetTotalCode(DateTime.Now);

      RefreshCodePanel();
 
      var first = historyList.FirstOrDefault();
      if (first != null)
        GoodsLabel.Text = first.Goods_Name;
    }

    private void RefreshCodePanel()
    {
        flowLayoutPanel3.Controls.Clear();
        codeButtons.Clear();
        flowLayoutPanel4.Controls.Clear();
        foreach (var item in allCode)
        {
            if (item.GoodsType == 0 || (item.GoodsType == 1 && item.NoTotalCode))
            {

            }
            else
            {
              if (deleteList.Contains(item.ID))
              {
                continue;
              }
            }
            
            var n = new ColorButton();
            AddCodeButton(n, item);
          
            flowLayoutPanel3.Controls.Add(n);
        }
    }

    void UpLoadLocalData()
    {
      while (true)
      {
        try
        {
          if (netStateWatch1.NetState)
          {
            var msg = SegmentProductionBL.UploadSegmentInfo(true);
            if (!string.IsNullOrEmpty(msg) && msg.EndsWith("重复上传"))
            {
              this.Invoke(new Action(() =>
              {
                MessageBox.Show(msg + "请检查原因！");
              }));
            }
          }
        }
        catch
        {

        }
        Thread.Sleep(2000);
      }
    }

    private void CheckInStored()
    {
      while (true)
      {
        try
        {
          if (netStateWatch1.NetState)
          {
            if (historyList!=null &&  historyList.Any())
            {
                int c = 50;
                if (historyList.Count() < 50)
                {
                    c = historyList.Count;
                }
              var arr = historyList.Reverse().Take(c);
              var inStored = SegmentProductionBL.GetInStoreState(arr.Select(x => x.BarCode).ToList());
              var tag = arr.Where(x => inStored.Contains(x.BarCode));
              if (tag.Any())
              {
                SegmentProductionBL.SetInStored(tag.Select(x => x.ID).ToList());
                this.Invoke(new Action(() =>
                {
                  var groupByTotal = tag.GroupBy(x => x.TotalCode_ID);
                  foreach (var item2 in groupByTotal)
                  {
                      var d = item2.FirstOrDefault();

                    //鲜品不删除总码
                      if (d.GoodsType == 0)
                      {
                        if (_freshPanel != null)
                        {
                          var list = new List<ColorButton>();
                          foreach (var t in item2)
                          {
                            foreach (ColorButton item in flowLayoutPanel4.Controls)
                            {
                              var tagItem = (SegmentProduction)item.Tag;
                              if (tagItem.BarCode == t.BarCode)
                              {
                                list.Add(item);
                                break;
                              }
                            }
                          }
                          foreach (var item in list)
                          {
                            flowLayoutPanel4.Controls.Remove(item);
                          }
                        }
                        continue;
                      }
                      else if (d.GoodsType == 1 && d.NoTotalCode)//暂存区不删除总码
                      {
                        if (_stayPanel != null)
                        {
                          var list = new List<ColorButton>();
                          foreach (var t in item2)
                          {
                            foreach (ColorButton item in flowLayoutPanel4.Controls)
                            {
                              var tagItem = (SegmentProduction)item.Tag;
                              if (tagItem.BarCode == t.BarCode)
                              {
                                list.Add(item);
                                break;
                              }
                            }
                          }
                          foreach (var item in list)
                          {
                            flowLayoutPanel4.Controls.Remove(item);
                          }
                        }
                        continue;
                      }
                      var f = codeButtons.FirstOrDefault(x => ((TotalCode)x.Tag).ID == item2.Key);
                      if (f != null)
                      {
                          flowLayoutPanel3.Controls.Remove(f); 
                          codeButtons.Remove(f);
                      } 
                      if (_codePanel != null && _totalCode.ID == item2.Key)
                      {
                          flowLayoutPanel4.Controls.Clear();
                          _codePanel = null;
                          _totalCode = null;
                      }
                  }

                  foreach (var item in tag)
                    historyList.Remove(item);
                     
                }));
              }
            }
          }
        }
        catch (Exception ex)
        {
          this.Invoke(new Action(() =>
             {
               var msg = ex.Message ?? string.Empty;
               msglbl.Text = "ERROR:" + msg;
               LogUtil.WriteErrorFile(msg, "分割品车间称重计数");
             }));
        }
        Thread.Sleep(5000);
      }
    }

    private void closeBtn_Click(object sender, EventArgs e)
    {
        var unSyncCount = SegmentProductionBL.GetUnSyncCount();
        bool close = true;
        if (unSyncCount > 0)
        {
            if (MessageBox.Show(string.Format("{0}条数据等待上传，确认关闭？", unSyncCount), "关闭确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                close = false;
            }
        }
        Thread.Sleep(500);
        if (close)
            Close();
    }

    private void goodsSetBtn_Click(object sender, EventArgs e)
    {
      new ClientGoodsSetDialog().ShowDialog();
      BindGoods();
    }

    private void rePrintBtn_Click(object sender, EventArgs e)
    {
      if (barPrintCheck.Checked)
      {
        if (historyList.Count == 0)
          throw new Exception("请先选择要补打的记录");
        SegmentProduction item;

        if (current != null)
          item = current;
        else
          item = historyList.First();
        var template = config.Template;
        var goodsInfo = SegmentProductionBL.GetGoodsInfo(item.Goods_ID);
        if (goodsInfo != null && goodsInfo.Item1.HasValue)
        {
          if (goodsInfo.Item1 == 0)
            template = "SegmentProductionPrint.html";
          else
            template = "SegmentProductionPrint1.html";
        }
        NotAuto.SegmentProductionPrint.Print(item, batchDate, template);
        var log = new SegmentLog(item.BarCode, "补打");
        log.Message = string.Format("存货名称：{0} 重量：{1:#0.###}", item.Goods_Name, item.Weight);
        SegmentProductionBL.InsertLog(log);
      }
    }

    private void templateBtn_Click(object sender, EventArgs e)
    {
      new TemplateSelector(config).ShowDialog();
    }

    private void deleteBtn_Click(object sender, EventArgs e)
    {
        //if (_totalCode == null || _codePanel == null)
        if (current != null)
        { 
            if (MessageBox.Show("确定删除选中记录？", "删除确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
                return;
             
            if (current.CreateTime.AddMinutes(1) < DateTime.Now)
            {
                MessageBox.Show("已超出可删除时间范围");
                return;
            }
            SegmentProduction d = current;
            SegmentProductionBL.Delete(d);
            historyList.Remove(d);
            if (_labelBt != null)
            {
                var parent=_labelBt.Parent;
                parent.Controls.Remove(_labelBt);
            }
        
            var thd = new Thread(new ParameterizedThreadStart(RefreshTask));
            thd.Start(d);
            current = null;
        }
        else if (_totalCode != null && _codePanel != null)
        {
            var deleteList = historyList.Where(x => x.TotalCode_ID == _totalCode.ID).ToList();
            if (deleteList.Count > 0)
            {
                MessageBox.Show("总码下已有条码，不允许直接删除总码");
                return;
            }
            if (_totalCode.GoodsType == 0)
            {
              MessageBox.Show("鲜品总码不允许删除");
              return;
            }
            else if (_totalCode.GoodsType == 1 && _totalCode.NoTotalCode)
            {
              MessageBox.Show("暂存区总码不允许删除");
              return;
            }
            SegmentProductionBL.DeleteTotalCode(_totalCode);
            allCode.Remove(_totalCode);
            codeButtons.Remove(_codePanel );
            foreach (var item in deleteList)
            {
                historyList.Remove(item);
                var thd = new Thread(new ParameterizedThreadStart(RefreshTask));
                thd.Start(item);
            }
            flowLayoutPanel3.Controls.Remove(_codePanel);
           // RefreshCodePanel();
            current = null;
            if (allCode.Count > 0)
            {
                _totalCode = allCode[0];
                _codePanel = (ColorButton)flowLayoutPanel3.Controls[0];
                _codePanel.Selected = true;
                _codePanel.Invalidate();
                BindflowLayoutPanel(_codePanel, _totalCode);
            }
            else
            {
                _totalCode = null;
                _codePanel = null;
            }

        }

    }

    private void logBtn_Click(object sender, EventArgs e)
    {
      new LogForm().ShowDialog();
    }

    private void StatisticNumberBox_MouseClick(object sender, MouseEventArgs e)
    {
      var keyBoard = new NumberPad();
      if (keyBoard.ShowDialog() == true)
      {
        var box = (sender as TextBox);
        if (string.IsNullOrEmpty(keyBoard.Result))
          box.Text = string.Empty;
        else
        {
          decimal num = 0;

          if (!decimal.TryParse(keyBoard.Result, out num))
            throw new Exception("数量输入有误");
          box.Text = keyBoard.Result;
        }
      }
    }

    private void ViewTaskBtn_Click(object sender, EventArgs e)
    {
      if (string.IsNullOrEmpty(groupKey))
        throw new Exception("请选择存货分组");
      if (batchID == null)
        throw new Exception("请先选择批次");
      if (goodsSetDic == null)
        throw new Exception("请选择存货分组");
      var arr = goodsSetDic[groupKey];
      if(arr.Count==0)
        throw new Exception("分组中没有任何存货");
      var goods = arr.Select(x => new Goods { Code = x.Goods_Code, Name = x.Goods_Name, ID = x.Goods_ID });
      new ViewTaskForm(batchDate ?? DateTime.Today, batchID.Value, goods).ShowDialog();
    }

    private void numberInput_MouseClick(object sender, MouseEventArgs e)
    {
      var keyBoard = new NumberPad();
      if (keyBoard.ShowDialog() == true)
      {
        var box = (sender as TextBox);
        if (string.IsNullOrEmpty(keyBoard.Result))
          box.Text = "1";
        else
        {
          int num = 0;
          if (!int.TryParse(keyBoard.Result, out num))
            throw new Exception("数量输入有误");
          if (num <= 0)
            num = 1;
          if (num > 50)
            num = 50;
          box.Text = num.ToString();
        }
      }
    }

    ColorButton _codePanel;
    ColorButton _freshPanel;
    ColorButton _stayPanel;
    TotalCode _totalCode;
    TotalCode _freshTotalCode;
    TotalCode _stayTotalCode;

    private void colorButton1_Click(object sender, EventArgs e)
    {
        var n = new ColorButton();
        
        var tCode = SegmentProductionBL.InsertTotalCode(new TotalCode());
        allCode.Insert(0, tCode);
        AddCodeButton(n, tCode,true);
        flowLayoutPanel4.Controls.Clear();
        flowLayoutPanel3.Controls.Add(n);
        flowLayoutPanel3.Controls.SetChildIndex(n, 2);
    }

    private void AddCodeButton(ColorButton n, TotalCode tCode, bool add = false)
    {
        n .Tag = tCode;
        if (tCode.GoodsType == 0)
        {
          n.Text = "鲜品";
          _freshPanel = n;
        }
        else if (tCode.GoodsType == 1 && tCode.NoTotalCode)
        {
          n.Text = "暂存区";
          _stayPanel = n;
        }
        else
           n.Text = tCode.ShortCode;
        n .Click += delegate
        {
           
            n .Selected = !n.Selected;  
            if (n .Selected)
            { 
                current = null;
                _codePanel = n;
                _totalCode = tCode;
                if (_labelBt != null)
                {
                    _labelBt.Selected = false;
                    _labelBt.Invalidate();
                }
                _labelBt = null;

                BindflowLayoutPanel(n, tCode);
            }
            else
            {
                flowLayoutPanel4.Controls.Clear();
                _codePanel = null;
                _totalCode = null;
            }
            foreach (var bt in codeButtons)
            {
                if (bt.Text != n.Text && bt.Selected)
                {
                    bt.Selected = false;
                    bt.Invalidate();
                }
            }

        };
        if (add)
        {
            _codePanel = n;
            n .Selected = true;
            _totalCode = tCode;
            foreach (var bt in codeButtons)
            {
                if (bt.Selected)
                {
                    bt.Selected = false;
                    bt.Invalidate();
                }
            }
        }
        n.BackColor =  Color.LightGray;
        n.Font = new  Font("黑体", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
        n.ForeColor = Color.Black;
       // n.Location = new  Point(3, 3);
        //n.Name = "Button";
        n.SelectedColor = Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
        n.Size = new  Size(99, 40);
        //n.TabIndex = 1;
        n.UseVisualStyleBackColor = false;

        codeButtons.Add(n );
    }

    private void BindflowLayoutPanel(ColorButton tButton, TotalCode tCode)
    {
        var details = historyList.Where(x => x.TotalCode_ID == tCode.ID);
        flowLayoutPanel4.Controls.Clear();
        foreach (var d in details)
        {
            flowLayoutPanel4.Controls.Add(initSegmentBt(d, tButton, tCode));
        }
    }

    private void colorButton2_Click(object sender, EventArgs e)
    {
        if (_totalCode == null || _codePanel == null)
        {
            throw new Exception(string.Format("请先选择总码！"));
        }
       var dmos= historyList.Where(x => x.TotalCode_ID == _totalCode.ID).ToArray();
       if (dmos.Length == 0)
       {
           throw new Exception(string.Format("此码不包含任何产品！"));
       }
       foreach (var item in dmos)
       {
           item.TotalCode_Code = _totalCode.BarCode;
       }
        NotAuto.SegmentSumCodePrint.Print(dmos, "SegmentSumCode.html");
        var log = new SegmentLog(dmos[0].TotalCode_Code, "总码");
        log.Message = string.Format("总码：{0}  ", dmos[0].TotalCode_Code);
        SegmentProductionBL.InsertLog(log);
    }

    private const int CP_NOCLOSE_BUTTON = 0x200;

    protected override CreateParams CreateParams
    {

        get
        {

            CreateParams myCp = base.CreateParams;

            myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;

            return myCp;

        }

    }

    private void butcherDateBox_MouseClick(object sender, MouseEventArgs e)
    {
      var simpleLbl = sender as Label;
      var cs = new CalendarSelecter();
      if (cs.ShowDialog() == true)
      {
        butcherDate = cs.Result;
        butcherDateBox.Text = butcherDate.ToString("yyyy-MM-dd");
      }
    }

    WeightStatus status = new WeightStatus();
    #region 称相关
    private void init()
    {
      zeroBtn.Enabled = false;
     // weightSwitch.Enabled = false;
      System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//忽略程序跨越线程运行导致的错误.没有此句将会产生错误
    }

    private void weightSwitch_Click(object sender, EventArgs e)
    {
      this.lblChengZhong.Text = "0.00";
      if (Utils.mPortOpened)//关闭动作
      {
        if (CallLibrary.unbindScale() == 1)
        {
          Utils.mPortOpened = false; //串口打开标记
          closePort();
        }
      }
      else
      {
        if (!Utils.mPortOpened)
        {
          openPort();
        }
      }
      weightSwitch.Text = Utils.mPortOpened ? "停止称重" : "启用称重";
    }

    #region 打开 关闭 串口
    private void openPort()
    {
      try
      {
        int port = 3;
        int baudrate = 9600;
        if (CallLibrary.sendPort(port, baudrate) == 1)
        {
          Utils.mPortOpened = true; //串口打开标记
          timer1.Enabled = true;
          zeroBtn.Enabled = true;
          //this.labelStatus.Text = Utils.rm.GetString("comOpen");

          //Console.WriteLine("Open port Complete.");
        }
        else
        {
          Utils.mPortOpened = false; //串口打开标记
          timer1.Enabled = false;
          MessageBox.Show("串口打开失败");
         // this.labelStatus.Text = Utils.rm.GetString("comFail");
        //  Console.WriteLine("Open port fail .");
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show("" + ex);
      }
    }

    private void closePort()
    {
      timer1.Enabled = false;
      Utils.mPortOpened = false;
     // this.labelStatus.Text = Utils.rm.GetString("comClose");
      this.zeroBtn.Enabled = false;

      this.labelZero.BackColor = Color.White;
      this.labelZero.ForeColor = Color.Black;
      this.labelStable.BackColor = Color.White;
      this.labelStable.ForeColor = Color.Black;
      status.TareStatus = false;
    }
    #endregion

    private void zeroBtn_Click(object sender, EventArgs e)
    {
      if (CallLibrary.SendZero() == 1)
      {
        //MessageBox.Show("Zero is successful");
       // MessageBox.Show(Utils.rm.GetString("zeroIsOk"));
      }
      else
      {
        MessageBox.Show(Utils.rm.GetString("zeroisFail"));
      }
    }
    #endregion

    private void SegmentProductionAutoForm_Load(object sender, EventArgs e)
    {
      init();
    }

    #region 重量处理
    string netWeight = string.Empty;
    private void timer1_Tick(object sender, EventArgs e)
    {
      try
      {
        timer1.Interval = 100;
        if (Utils.mPortOpened)
        {
          IntPtr stringNet = CallLibrary.getStringNet();

          netWeight = Marshal.PtrToStringAnsi(stringNet); //重量

          Console.WriteLine("weight data:" + netWeight);

          weightNet(netWeight);
          if (CallLibrary.isZero() != 1)
          {
            this.labelZero.BackColor = Color.White;
            this.labelZero.ForeColor = Color.Black;
            status.ZeroStatus = false;
          }
          else
          {
            this.labelZero.BackColor = Color.Green;
            this.labelZero.ForeColor = Color.White;
            status.ZeroStatus = true;
          }
          //稳定
          if (CallLibrary.isStable() != 1)
          {
            this.labelStable.BackColor = Color.White;
            this.labelStable.ForeColor = Color.Black;
            status.StableStatus = false;
          }
          else
          {
            this.labelStable.BackColor = Color.Green;
            this.labelStable.ForeColor = Color.White;
            status.StableStatus = true;
          }
          if (CallLibrary.isTare() != 1)
          {
            status.TareStatus = false;
          }
          else
          {
            status.TareStatus = true;
          }
        }
        else
        {
          this.lblChengZhong.Text = "0.00";
          this.labelZero.BackColor = Color.White;
          //this.labelStatus.BackColor = Color.White;
          //this.labelStatus.ForeColor = Color.Black;
        }
      }
      catch //(Exception ex)
      {
        //Console.WriteLine(ex);
      }
    }

    private void weightNet(string netWeight)
    {
      if (netWeight != null)
      {
        if (!netWeight.Contains("--UL--") && !netWeight.Contains("--OL--"))
        {
          this.lblChengZhong.Text = double.Parse(netWeight).ToString("0.00");
        }
        else
        {
          if (netWeight.Contains("--UL--"))
          {
            this.lblChengZhong.Text = "--UL--";
          }
          else if (netWeight.Contains("--OL--"))
          {
            this.lblChengZhong.Text = "--OL--";
          }
        }
      }
    }

    #endregion
  }
}
