using BO.BO.Bill;
using BO.Utils.BillRpc;
using BWP.WinFormControl;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QualityAndOrder
{
  partial class QualityOrderForm
  {
    List<SelectHurryList> hurryList;
    Thread bt3SyncTask;

    void Tab3Init()
    {
      orderGrid3.AutoGenerateColumns = false;
      orderGrid3.DataSource = null;

      AddKeyPadForTab3();
    }

    private void AddKeyPadForTab3()
    {
      for (var i = 1; i < 10; i++)
      {
        var btn = new Button() { Name = "_3" + i, Text = i.ToString(), Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
        btn.Click += (sender, e) =>
        {
          InputHurryNumber(btn.Text);
        };
        tab3KeyPanel.Controls.Add(btn);
      }
      var zero = new Button() { Name = "_30", Text = "0", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      zero.Click += (sender, e) =>
      {
        InputHurryNumber(zero.Text);
      };
      tab3KeyPanel.Controls.Add(zero);
      var back = new Button() { Name = "_3back", Text = "←", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      back.Click += (sender, e) =>
      {
        InputHurryNumber(back.Text);
      };
      tab3KeyPanel.Controls.Add(back);

      var clear = new Button() { Name = "_3clear", Text = "清空", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      clear.Click += (sender, e) =>
      {
        InputHurryNumber(clear.Text);
      };
      tab3KeyPanel.Controls.Add(clear);

    }

    void InputHurryNumber(string input)
    {
      if (lastHurry == null)
        throw new Exception("请选择一条排宰明细");
      lastHurry.HurryNumber = GetAfterNumber(lastHurry.HurryNumber, input) ?? 0;
      orderGrid3.Refresh();
    }

    private void tab3SearchBtn_Click(object sender, EventArgs e)
    {
      if (bt3SyncTask == null || !bt3SyncTask.IsAlive)
      {
        bt3SyncTask = new Thread(Tb3SyncTask);
        bt3SyncTask.Start();
        tab3SearchBtn.BackColor = Color.FromArgb(15, 215, 107);
        tab3SearchBtn.ForeColor = Color.White;
      }
      else
      {
        bt3SyncTask.Abort();
        tab3SearchBtn.BackColor = Color.FromKnownColor(KnownColor.Control);
        tab3SearchBtn.ForeColor = Color.FromKnownColor(KnownColor.ControlText);
      }
    }

    void Tb3SyncTask()
    {
      while (true)
      {
        this.Invoke(new InvokeHandler(delegate()
        {
          BindOrderGrid3();
        }));
        Thread.Sleep(5000);
      }
    }

    SelectHurryList lastHurry;
    private void BindOrderGrid3()
    {
      hurryList = OrderDetailRpc.GetSelectHurryList();
      if (lastHurry != null)
      {
        var t = hurryList.FirstOrDefault(x => x.WeightBill_ID == lastHurry.WeightBill_ID);
        if (t != null)
          t.HurryNumber = lastHurry.HurryNumber;
      }
      orderGrid3.DataSource = hurryList.OrderByDescending(x => x.B3WeighBill_ID).ToList();

      foreach (DataGridViewRow row in orderGrid3.Rows)
      {
        if (lastHurry != null && lastHurry.WeightBill_ID == (long)row.Cells["H_WeightBill_ID"].Value)
        {
          lastHurry = row.DataBoundItem as SelectHurryList;
          row.DefaultCellStyle.BackColor = orderGrid3.RowsDefaultCellStyle.SelectionBackColor;
        }
      }
      InitScrollBar4();
      orderGrid3.ClearSelection();
      try
      {
        if (r4Roll != -1)
          orderGrid3.FirstDisplayedScrollingRowIndex = r4Roll;
      }
      catch
      {
        r4Roll = -1;
      }
      orderGrid3.Refresh();
    }

    private void orderGrid3_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      if (e.ColumnIndex < orderGrid3.ColumnCount - 2)
        return;
      if (e.ColumnIndex == orderGrid3.ColumnCount - 2)//确定
      {
        if (lastHurry.HurryNumber == 0)
          return;
        if (lastHurry.HurryNumber > lastHurry.WeightNumber)
          throw new Exception("急宰头数多余排宰头数");
        bool hasError = false;
        var record =  OrderDetailRpc.InsertHurryRecord(lastHurry,out hasError);
        if (hasError)
          UMessageBox.Show("排宰顺序出现多条记录，请手动修改", "注意");
        lastHurry.HurryNumber = OrderDetailRpc.GetHurryRecordNumber(lastHurry.WeightBill_ID);
        orderGrid3.Refresh();
        HurryRecordPrint.Print(record);
      }
      else//查看
      {
        var view = new HurryRecordView(lastHurry.WeightBill_ID);
        if (view.ShowDialog() == DialogResult.OK)
        {
          lastHurry.HurryNumber -= view.Result;
          orderGrid3.Refresh();
        }
      }
    }

    private void orderGrid3_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      var entity = orderGrid3.CurrentRow.DataBoundItem as SelectHurryList;

      if (lastHurry != null)
      {
        foreach (DataGridViewRow row in orderGrid3.Rows)
        {
          if (lastHurry.WeightBill_ID == (long)row.Cells["H_WeightBill_ID"].Value)
          {
            row.DefaultCellStyle.BackColor = orderGrid3.RowsDefaultCellStyle.BackColor;
            break;
          }
        }
      }
      lastHurry = entity;
      if (e.ColumnIndex != orderGrid3.Columns.Count - 2)//非确定列
        orderGrid3.Refresh();
    }

    int r4Roll = -1;
    private void InitScrollBar4()
    {
      vScrollBar4.Maximum = (orderGrid3.RowCount - orderGrid3.DisplayedRowCount(false) + 30) * orderGrid3.RowTemplate.Height;
      vScrollBar4.Minimum = 0;
      vScrollBar4.SmallChange = orderGrid3.RowTemplate.Height;
      vScrollBar4.LargeChange = orderGrid3.RowTemplate.Height * 30;
      this.vScrollBar4.Scroll += (sender, e) =>
      {
        r4Roll = e.NewValue / orderGrid3.RowTemplate.Height;
        orderGrid3.FirstDisplayedScrollingRowIndex = r4Roll;
      };
    }
  }
}
