using BO.BO.Bill;
using BO.Utils;
using BO.Utils.BillRpc;
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;

namespace OrderConfirm
{
  public partial class OrderConfirmForm : Form, IAfterLogin
  {
    #region IAfterLogin
    public string RoleName
    {
      get { return "窒晕员"; }
    }

    public Form Generate()
    {
      return this;
    }

    #endregion

    private delegate void InvokeHandler();
    List<OrderDetail> orderList;
    Thread syncThread;
    public OrderConfirmForm()
    {
      InitializeComponent();
      uDatePicker1.Date = DateTime.Today;
      orderGrid.AutoGenerateColumns = false;
      orderGrid.DataSource = null;
      this.FormClosing += delegate
      {
        if (syncThread != null && syncThread.IsAlive)
          syncThread.Abort();
      };
    }

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

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

    void BindFinishNumber()
    {
      var number = OrderDetailRpc.GetFinishNumbers(uDatePicker1.Date.Value);
      finishNumberLabel.Text = number.ToString();
      finishNumberLabel.Refresh();
    }

    OrderDetail lastOrderDetail;
    private void BindOrderGrid()
    {
      orderList = OrderDetailRpc.GetOrderDetail(uDatePicker1.Date.Value);
      orderGrid.DataSource = orderList.OrderBy(x => x.Order).OrderBy(x => x.Doing).ToList();
      if (lastOrderDetail == null && orderGrid.CurrentRow != null)
      {
        lastOrderDetail = orderGrid.CurrentRow.DataBoundItem as OrderDetail;
      }
      foreach (DataGridViewRow row in orderGrid.Rows)
      {
        var state = (int)row.Cells["C_OrderState"].Value;
        if ((bool)row.Cells["C_IsHurryButcher"].Value)
          row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#CC9999");
        if ((bool)row.Cells["C_SecondarySplit"].Value)
          row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#6699CC");
        ((DataGridViewButtonCell)row.Cells["C_OK"]).Value = state == 0 ? "开始" : "取消";
        if (lastOrderDetail != null && lastOrderDetail.ID == (long)row.Cells["C_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;
        }
      }
      InitScrollBar1();
      orderGrid.ClearSelection();
      try
      {
        if (roll != -1)
          orderGrid.FirstDisplayedScrollingRowIndex = roll;
      }
      catch
      {
        roll = -1;
      }
      orderGrid.Refresh();
    }

    private void existBtn_Click(object sender, EventArgs e)
    {
      this.Close();
    }

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

    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["C_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();
    }

    private void orderGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      if (e.ColumnIndex < orderGrid.ColumnCount - 2)
        return;
      if (lastOrderDetail.OrderState == 20)
        return;
      if (e.ColumnIndex == orderGrid.ColumnCount - 2)//开始 取消
        OrderDetailRpc.SetOrderState(lastOrderDetail.ID, lastOrderDetail.OrderState == 0 ? 10 : 0);
      else//完成
      {
        OrderDetailRpc.SetOrderState(lastOrderDetail.ID, 20);
        BindFinishNumber();
      }
      BindOrderGrid();
    }

    string code = string.Empty;
    bool start = false;
    private void OrderConfirmForm_KeyUp(object sender, KeyEventArgs e)
    {
      switch (e.KeyData)
      {
        case Keys.S:
          start = true;
          code = string.Empty;
          break;
        case Keys.E:
          if (!start)
            break;
          InsertDetail();
          start = false;
          code = string.Empty;
          break;
        default:
          if (start)
            code += (char)e.KeyValue;
          break;
      }
    }

    void InsertDetail()
    {
      if (orderList == null)
        throw new Exception("请先同步数据");
      long id = 0;
      if (!long.TryParse(code, out id))
        throw new Exception(string.Format("接收扫码输入错误 {0}", code));
      var entity = OrderDetailRpc.GetHurryRecord(id);
      if (entity.ToOrderDetail_ID.HasValue)
        throw new Exception("该条码已插入过，不能重复插入");
      var currentOrder = 0;
      if (!setTop.Checked)
      {
        if (lastOrderDetail != null && lastOrderDetail.Date != uDatePicker1.Date)
          lastOrderDetail = null;
        if (lastOrderDetail != null)
          currentOrder = OrderDetailRpc.GetCurrentOrder(lastOrderDetail.ID);
        else
          currentOrder = OrderDetailRpc.GetMaxOrder(uDatePicker1.Date.Value);
        currentOrder++;
      }
      else
      {
        setTop.Checked = false;
        var l = orderList.OrderBy(x => x.Order).OrderBy(x => x.Doing).FirstOrDefault();
        if (l != null)
          currentOrder = l.Order;
        else
          currentOrder = 1;
      }
      var order = new OrderDetail();
      order.Order = currentOrder;
      order.LiveColonyHouse_Name = entity.LiveColonyHouse_Name;
      order.PlanNumber = entity.HurryNumber;
      order.WeightBill_ID = entity.WeightBill_ID;
      order.B3WeighBill_ID = entity.B3WeighBill_ID;
      order.Date = uDatePicker1.Date.Value;
      order.IsHurryButcher = true;
      OrderDetailRpc.InsertByHurryRecord(order, id);
      lastOrderDetail = order;
      BindOrderGrid();
    }
  }
}
