using BO.BO.Bill;
using BO.Utils;
using BO.Utils.BillRpc;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Linq;
using System.Threading;

namespace ButcherOrder
{
  public partial class ButcherOrderForm : Form, IAfterLogin
  {
    #region IAfterLogin
    public string RoleName
    {
      get
      {
        return "排宰员";
      }
    }

    public Form Generate()
    {
      return this;
    }
    # endregion

    private delegate void InvokeHandler();
    List<SecondOrder> orderList;
    Thread syncWork;
    public ButcherOrderForm()
    {
      InitializeComponent();
      this.uDatePicker1.Date = DateTime.Today;
      secondOrderGridView.AutoGenerateColumns = false;
      secondOrderGridView.DataSource = null;
      AddKeyPad();
      this.FormClosing += delegate
      {
        if (syncWork != null && syncWork.IsAlive)
          syncWork.Abort();
      };
    }

    private void AddKeyPad()
    {
      for (var i = 1; i < 10; i++)
      {
        var btn = new Button() { Name = "_" + i, Text = i.ToString(), Size = new Size(70, 70), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 15 }, Font = new Font("宋体", 15) };
        btn.Click += (sender, e) =>
        {
          numberInput.Text += btn.Text;
        };
        keyPanel.Controls.Add(btn);
      }
      var zero = new Button() { Name = "_0", Text = "0", Size = new Size(70, 70), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 15 }, Font = new Font("宋体", 15) };
      zero.Click += (sender, e) =>
      {
        if (!string.IsNullOrEmpty(numberInput.Text))
          numberInput.Text += "0";
      };
      keyPanel.Controls.Add(zero);
      var back = new Button() { Name = "_back", Text = "←", Size = new Size(70, 70), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 15 }, Font = new Font("宋体", 15) };
      back.Click += (sender, e) =>
      {
        if (!string.IsNullOrEmpty(numberInput.Text))
          numberInput.Text = numberInput.Text.Substring(0, numberInput.Text.Length - 1);
      };
      keyPanel.Controls.Add(back);

      var clear = new Button() { Name = "_clear", Text = "清空", Size = new Size(70, 70), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 15 }, Font = new Font("宋体", 15) };
      clear.Click += (sender, e) =>
      {
        numberInput.Text = null;
      };
      keyPanel.Controls.Add(clear);
    }

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

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

    void Sync()
    {
      while (true)
      {
        this.Invoke(new InvokeHandler(delegate()
        {
          orderList = SecondOrderRpc.GetSecondOrderList(this.uDatePicker1.Date.Value);
          BindGrid();
        }));
        Thread.Sleep(5000);
      }
    }

    SecondOrder last;
    void BindGrid()
    {
      secondOrderGridView.DataSource = orderList.OrderBy(x => x.Order).OrderBy(x => x.Finish).ToList();
      if (last == null && secondOrderGridView.CurrentRow != null)
      {
        last = secondOrderGridView.CurrentRow.DataBoundItem as SecondOrder;
        if (last.Finish)
          last = null;
      }
      foreach (DataGridViewRow row in secondOrderGridView.Rows)
      {
        if ((bool)row.Cells["Finish"].Value)
          row.DefaultCellStyle.BackColor = Color.YellowGreen;
        if (last != null && last.Order == (int)row.Cells["Order"].Value)
        {
          last = row.DataBoundItem as SecondOrder;
          if (last.Finish)
            row.DefaultCellStyle.BackColor = Color.Yellow;
          else
            row.DefaultCellStyle.BackColor = secondOrderGridView.RowsDefaultCellStyle.SelectionBackColor;
        }
      }
      if (last != null && !last.Finish)
        orderLabel.Text = last.Order.ToString();
      else
        orderLabel.Text = "0";
      InitScrollBar1();
      secondOrderGridView.ClearSelection();
      try
      {
        if (roll != -1)
          secondOrderGridView.FirstDisplayedScrollingRowIndex = roll;
      }
      catch
      {
        roll = -1;
      }
      secondOrderGridView.Refresh();
    }

    private void okBtn_Click(object sender, EventArgs e)
    {
      if (string.IsNullOrEmpty(numberInput.Text))
        return;
      if (last == null)
        throw new Exception("请先同步数据");
      if (last.Finish)
      {
        var result = MessageBox.Show("当前行已更新\n确定要继续修改吗？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
        if (result != DialogResult.OK)
          return;
      }
      var number = int.Parse(numberInput.Text);
      if (last.HotFadeNumber + number > last.PlanNumber)
        throw new Exception("烫褪头数多余总头数，请确认！");
      var detail = new SecondOrder_Detail() { Number = number, SecondOrder_ID = last.ID, Time = DateTime.Now };
      last.HotFadeNumber += detail.Number;
      SecondOrderRpc.Insert(detail, last);
      secondOrderGridView.Refresh();

      numberInput.Text = string.Empty;
    }

    private void secondOrderGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      var entity = secondOrderGridView.CurrentRow.DataBoundItem as SecondOrder;

      if (e.ColumnIndex < secondOrderGridView.ColumnCount - 2)
        return;
      if (e.ColumnIndex == secondOrderGridView.ColumnCount - 2)//更新
      {
        if (entity.Finish)
          return;
        entity.Finish = true;
        SecondOrderRpc.SetFinish(entity.ID, entity.OrderDetail_ID, entity);
        BindGrid();
      }
      else//查看
      {
        var view = new ViewDetail(entity);
        if (view.ShowDialog() == DialogResult.OK)
        {
          entity.HotFadeNumber = view.HotFadeNumber;
          secondOrderGridView.Refresh();
        }
      }
    }

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

    private void secondOrderGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      var entity = secondOrderGridView.CurrentRow.DataBoundItem as SecondOrder;
      if (e.ColumnIndex != secondOrderGridView.Columns.Count - 2)//非更新列
      {
        if (last != null)
        {
          foreach (DataGridViewRow row in secondOrderGridView.Rows)
          {
            if (last.Order == (int)row.Cells["Order"].Value)
            {
              row.DefaultCellStyle.BackColor = last.Finish ? Color.YellowGreen : secondOrderGridView.RowsDefaultCellStyle.BackColor;
              break;
            }
          }
        }
        last = entity;
        secondOrderGridView.CurrentRow.DefaultCellStyle.SelectionBackColor = last.Finish ? Color.Yellow : secondOrderGridView.RowsDefaultCellStyle.SelectionBackColor;
      }
      else//更新列
      {
        secondOrderGridView.CurrentRow.DefaultCellStyle.SelectionBackColor = last.Finish ? Color.YellowGreen : secondOrderGridView.RowsDefaultCellStyle.BackColor;
        last = null;
      }
      secondOrderGridView.Refresh();
    }
  }
}
