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 tb2SyncB3IDThread;
    Thread bt2SyncTask;

    void Tab2Init()
    {
      tab2DateSelect.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 (orderGrid.CurrentCell == null)
        throw new Exception("请选择一条排宰明细");
      var tag = orderGrid.CurrentRow.DataBoundItem as OrderDetail;
      tag.PlanNumber = GetAfterNumber(tag.PlanNumber, input) ?? 0;
      orderGrid.Refresh();
    }

    private void tab2SyncBtn_Click(object sender, EventArgs e)
    {
      BindOrderGrid();
      if (tb2SyncB3IDThread == null)
      {
        tb2SyncB3IDThread = new Thread(Tab2SyncB3ID);
        tb2SyncB3IDThread.Start();
      }

      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);
      }
    }

    private void Tab2SyncB3ID()
    {
      while (true)
      {
        if (orderList == null || needOrderList == null)
        {
          Thread.Sleep(5000);
          continue;
        }
        bool orderChange = false;
        bool needListChange = false;
        var ids = orderList.Where(x => x.B3WeighBill_ID == null).Select(x => (long?)x.WeightBill_ID).Distinct().ToList();
        var needOrderIds = needOrderList.Where(x => x.B3ID == null).Select(x => (long?)x.WeightBill_ID);
        ids.AddRange(needOrderIds.Except(ids));
        if (ids.Any())
        {
          var result = WeightBillRpc.SyncBillB3Ids(ids);
          foreach (var item in result)
          {
            var left = orderList.Where(x => x.WeightBill_ID == item.Item1);
            foreach (var lEntity in left)
            {
              lEntity.B3WeighBill_ID = item.Item2;
              if (!orderChange)
                orderChange = true;
            }

            var rFirst = needOrderList.FirstOrDefault(x => x.WeightBill_ID == item.Item1);
            if (rFirst != null)
            {
              rFirst.B3ID = item.Item2;
              if (!needListChange)
                needListChange = true;
            }
          }
        }
        if (orderChange)
        {
          this.Invoke(new InvokeHandler(delegate()
          {
            orderGrid.Refresh();
          }));
        }
        if (needListChange)
        {
          this.Invoke(new InvokeHandler(delegate()
          {
            preOrderGrid.Refresh();
          }));
        }
        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();
      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 = Color.YellowGreen;
        if (lastOrderDetail != null && lastOrderDetail.ID == (long)row.Cells["O_ID"].Value)
        {
          var cRow = row;
          if (orderGrid.Rows.IndexOf(row) == 1)
            cRow = orderGrid.Rows[0];
          lastOrderDetail = cRow.DataBoundItem as OrderDetail;
          if (lastOrderDetail.IsHurryButcher)
            cRow.DefaultCellStyle.BackColor = Color.Yellow;
          else
            cRow.DefaultCellStyle.BackColor = orderGrid.RowsDefaultCellStyle.SelectionBackColor;
        }
      }
      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;
      var entity = preOrderGrid.CurrentRow.DataBoundItem as NeedOrderEntity;
      if (e.ColumnIndex == preOrderGrid.ColumnCount - 2)
      {
        var currentOrder = 0;
        if (lastOrderDetail != null)
          currentOrder = OrderDetailRpc.GetCurrentOrder(lastOrderDetail.ID);
        else
          currentOrder = OrderDetailRpc.GetMaxOrder();
        currentOrder++;
        var order = new OrderDetail();
        order.Order = currentOrder;
        order.LiveColonyHouse_Name = entity.HouseNames;
        order.PlanNumber = entity.LastNumber;
        order.WeightBill_ID = entity.WeightBill_ID;
        order.B3WeighBill_ID = entity.B3ID;
        OrderDetailRpc.Insert(order);
        BindOrderGrid();
      }
      else
      {
        entity.Show = !entity.Show;
        OrderDetailRpc.ChangeShowType(entity.WeightBill_ID, entity.Show);
      }
      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 - 2)
        return;
      var entity = orderGrid.CurrentRow.DataBoundItem as OrderDetail;
      if (e.ColumnIndex == orderGrid.ColumnCount - 2)//确定
      {
        if (entity.PlanNumber < 0)
          throw new Exception("排宰头数不能小于0");
        var lastNumber = OrderDetailRpc.GetLastNumber(entity.WeightBill_ID, entity.ID);

        if (entity.PlanNumber > lastNumber)
          throw new Exception("排宰总头数多余过磅头数");
        if (entity.PlanNumber == lastNumber)
          return;
        if (entity.PlanNumber == 0)
          OrderDetailRpc.Delete(entity.ID);
        else
          OrderDetailRpc.UpdateNumber(entity.ID, entity.PlanNumber);
        BindPreOrderGrid();
      }
      else if ((e.ColumnIndex == orderGrid.ColumnCount - 1))//急宰
      {
        entity.IsHurryButcher = !entity.IsHurryButcher;
        OrderDetailRpc.UpdateHurryFlag(entity.ID, entity.IsHurryButcher);
      }
      BindOrderGrid();
    }

    private void orderGrid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      var entity = orderGrid.CurrentRow.DataBoundItem as OrderDetail;
      if (e.ColumnIndex == orderGrid.ColumnCount - 2 && entity.PlanNumber == 0)//确定
      {
        lastOrderDetail = null;
      }
      else
      {
        if (lastOrderDetail != null)
        {
          foreach (DataGridViewRow row in orderGrid.Rows)
          {
            if (lastOrderDetail.ID == (long)row.Cells["O_ID"].Value)
            {
              row.DefaultCellStyle.BackColor = lastOrderDetail.IsHurryButcher ? Color.YellowGreen : orderGrid.RowsDefaultCellStyle.BackColor;
              break;
            }
          }
        }
        lastOrderDetail = entity;
        orderGrid.CurrentRow.DefaultCellStyle.SelectionBackColor = lastOrderDetail.IsHurryButcher ? Color.Yellow : orderGrid.RowsDefaultCellStyle.SelectionBackColor;
      }
      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;
      };
    }
  }
}
