using BO;
using BO.BO.Bill;
using BO.Utils.BillRpc;
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<NeedOrderEntity> needOrderList;
    List<OrderDetail> orderList;
    Thread orderSyncTask;
    Thread bt2SyncTask;

    void Tab2Init()
    {
      tab2DateSelect.Date = DateTime.Today;
      butcherDateInput.Date = DateTime.Today;
      orderGrid.AutoGenerateColumns = false;
      preOrderGrid.AutoGenerateColumns = false;
      orderGrid.DataSource = null;
      preOrderGrid.DataSource = null;

      AddKeyPadForTab2();
    }

    private void AddKeyPadForTab2()
    {
      for (var i = 1; i < 10; i++)
      {
        var btn = new Button() { Name = "_2" + 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) =>
        {
          InputPlanNumber(btn.Text);
        };
        tab2KeyPanel.Controls.Add(btn);
      }
      var zero = new Button() { Name = "_20", Text = "0", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      zero.Click += (sender, e) =>
      {
        InputPlanNumber(zero.Text);
      };
      tab2KeyPanel.Controls.Add(zero);
      var back = new Button() { Name = "_2back", Text = "←", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      back.Click += (sender, e) =>
      {
        InputPlanNumber(back.Text);
      };
      tab2KeyPanel.Controls.Add(back);

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

    }

    void InputPlanNumber(string input)
    {
      if (lastOrderDetail == null)
        throw new Exception("请选择一条排宰明细");
      lastOrderDetail.PlanNumber = GetAfterNumber(lastOrderDetail.PlanNumber, input) ?? 0;
      orderGrid.Refresh();
    }

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

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

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

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

    NeedOrderEntity lastPreOrder;
    void BindPreOrderGrid()
    {
      needOrderList = OrderDetailRpc.GetNeedOrderWeightBill(tab2DateSelect.Date.Value, GetSelectType());
      preOrderGrid.DataSource = needOrderList.OrderBy(x => x.WeighTime).ToList();

      foreach (DataGridViewRow row in preOrderGrid.Rows)
      {
        var show = (bool)row.Cells["P_Show"].Value;
        if (!show)
          row.DefaultCellStyle.BackColor = Color.YellowGreen;
        ((DataGridViewButtonCell)row.Cells["P_Hidden"]).Value = show ? "隐藏" : "显示";
        if (lastPreOrder != null && lastPreOrder.WeightBill_ID == (long)row.Cells["P_WeightBill_ID"].Value)
        {
          lastPreOrder = row.DataBoundItem as NeedOrderEntity;
          if (lastPreOrder.Show)
            row.DefaultCellStyle.BackColor = preOrderGrid.RowsDefaultCellStyle.SelectionBackColor;
          else
            row.DefaultCellStyle.BackColor = Color.Yellow;
        }
      }
      InitScrollBar3();
      preOrderGrid.ClearSelection();
      try
      {
        if (r2Roll != -1)
          preOrderGrid.FirstDisplayedScrollingRowIndex = r2Roll;
      }
      catch
      {
        r2Roll = -1;
      }
      preOrderGrid.Refresh();
    }

    OrderDetail lastOrderDetail;
    void BindOrderGrid()
    {
      orderList = OrderDetailRpc.GetOrderDetail(butcherDateInput.Date.Value);
      if (lastOrderDetail != null)
      {
        var t = orderList.FirstOrDefault(x => x.ID == lastOrderDetail.ID);
        if (t != null)
          t.PlanNumber = lastOrderDetail.PlanNumber;
      }
      orderGrid.DataSource = orderList.OrderByDescending(x => x.Order).ToList();
      if (lastOrderDetail == null && orderGrid.CurrentRow != null)
      {
        lastOrderDetail = orderGrid.CurrentRow.DataBoundItem as OrderDetail;
      }
      foreach (DataGridViewRow row in orderGrid.Rows)
      {
        if ((bool)row.Cells["O_IsHurryButcher"].Value)
          row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#CC9999");
        if ((bool)row.Cells["O_SecondarySplit"].Value)
          row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#6699CC");
        if (lastOrderDetail != null && lastOrderDetail.ID == (long)row.Cells["O_ID"].Value)
        {
          lastOrderDetail = row.DataBoundItem as OrderDetail;
          var c = orderGrid.RowsDefaultCellStyle.SelectionBackColor;
          if (lastOrderDetail.IsHurryButcher)
            row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#FF9900");
          if (lastOrderDetail.SecondarySplit)
            row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#006699");
          row.DefaultCellStyle.BackColor = c;
        }
      }
      InitScrollBar2();
      orderGrid.ClearSelection();
      try
      {
        if (r1Roll != -1)
          orderGrid.FirstDisplayedScrollingRowIndex = r1Roll;
      }
      catch
      {
        r1Roll = -1;
      }
      orderGrid.Refresh();
    }

    private void preOrderGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      if (e.ColumnIndex < preOrderGrid.ColumnCount - 2)
        return;
      if (e.ColumnIndex == preOrderGrid.ColumnCount - 2)
      {
        var currentOrder = 0;
        if (lastOrderDetail != null && lastOrderDetail.Date != butcherDateInput.Date)
          lastOrderDetail = null;
        if (lastOrderDetail != null)
          currentOrder = OrderDetailRpc.GetCurrentOrder(lastOrderDetail.ID);
        else
          currentOrder = OrderDetailRpc.GetMaxOrder(butcherDateInput.Date.Value);
        currentOrder++;
        var order = new OrderDetail();
        order.Order = currentOrder;
        order.LiveColonyHouse_Name = lastPreOrder.HouseNames;
        order.PlanNumber = lastPreOrder.LastNumber;
        order.WeightBill_ID = lastPreOrder.WeightBill_ID;
        order.B3WeighBill_ID = lastPreOrder.B3ID;
        order.Date = butcherDateInput.Date.Value;
        OrderDetailRpc.Insert(order);
        lastOrderDetail = order;
        BindOrderGrid();
      }
      else
        OrderDetailRpc.ChangeShowType((long)preOrderGrid.CurrentRow.Cells["P_WeightBill_ID"].Value, !(bool)preOrderGrid.CurrentRow.Cells["P_Show"].Value);
      BindPreOrderGrid();
    }

    private void preOrderGrid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      var entity = preOrderGrid.CurrentRow.DataBoundItem as NeedOrderEntity;
      if (e.ColumnIndex == preOrderGrid.ColumnCount - 2)//排宰
      {
        if (lastPreOrder != null)
        {
          foreach (DataGridViewRow row in preOrderGrid.Rows)
          {
            if (lastPreOrder.WeightBill_ID == (long)row.Cells["P_WeightBill_ID"].Value)
            {
              row.DefaultCellStyle.BackColor = lastPreOrder.Show ? preOrderGrid.RowsDefaultCellStyle.BackColor : Color.YellowGreen;
              break;
            }
          }
        }
        lastPreOrder = entity;
        preOrderGrid.CurrentRow.DefaultCellStyle.SelectionBackColor = lastPreOrder.Show ? preOrderGrid.RowsDefaultCellStyle.SelectionBackColor : Color.Yellow;
      }
      else
      {
        lastPreOrder = null;
      }
      preOrderGrid.Refresh();
    }

    private void orderGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      if (e.ColumnIndex != orderGrid.ColumnCount - 1)
        return;
      if (lastOrderDetail.PlanNumber < 0)
        throw new Exception("排宰头数不能小于0");
      var lastNumber = OrderDetailRpc.GetLastNumber(lastOrderDetail.WeightBill_ID, lastOrderDetail.ID);

      if (lastOrderDetail.PlanNumber > lastNumber)
        throw new Exception("排宰总头数多于过磅头数");
      var dbCurrentNumber = OrderDetailRpc.GetCurrentOrderPlanNumber(lastOrderDetail.ID);
      if (lastOrderDetail.PlanNumber == dbCurrentNumber)
        return;
      if (lastOrderDetail.PlanNumber == 0)
      {
        OrderDetailRpc.Delete(lastOrderDetail.ID);
        lastOrderDetail = null;
      }
      else
        OrderDetailRpc.UpdateNumber(lastOrderDetail.ID, lastOrderDetail.PlanNumber);
      BindPreOrderGrid();
      BindOrderGrid();
    }

    private void orderGrid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      var entity = orderGrid.CurrentRow.DataBoundItem as OrderDetail;
      if (lastOrderDetail != null)
      {
        foreach (DataGridViewRow row in orderGrid.Rows)
        {
          if (lastOrderDetail.ID == (long)row.Cells["O_ID"].Value)
          {
            Color c = orderGrid.RowsDefaultCellStyle.BackColor;
            if (lastOrderDetail.IsHurryButcher)
              c = ColorTranslator.FromHtml("#CC9999");
            if (lastOrderDetail.SecondarySplit)
              c = ColorTranslator.FromHtml("#6699CC");
            row.DefaultCellStyle.BackColor = c;
            break;
          }
        }
      }
      lastOrderDetail = entity;

      var bc = orderGrid.RowsDefaultCellStyle.SelectionBackColor;
      if (lastOrderDetail.IsHurryButcher)
        bc = ColorTranslator.FromHtml("#FF9900");
      if (lastOrderDetail.SecondarySplit)
        bc = ColorTranslator.FromHtml("#006699");
      orderGrid.CurrentRow.DefaultCellStyle.SelectionBackColor = bc;
      orderGrid.Refresh();
    }

    bool? GetSelectType()
    {
      bool? type = null;
      if (showAvailable.Checked)
        type = true;
      else if (showHidden.Checked)
        type = false;
      return type;
    }

    private void showRadio_CheckedChanged(object sender, EventArgs e)
    {
      BindPreOrderGrid();
    }

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

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