using BO.BO.Bill;
using BO.Utils;
using BO.Utils.BillRpc;
using BWP.WinFormControl;
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 DropPigReOrder
{
  public partial class ReOrderForm : Form, IAfterLogin
  {
    public string RoleName
    {
      get { return "掉猪处理员"; }
    }

    public Form Generate()
    {
      return this;
    }

    private delegate void InvokeHandler();
    List<DropPigOrderList> list;
    Thread syncThread;
    public ReOrderForm()
    {
      InitializeComponent();
      this.uDatePicker1.Date = DateTime.Today;
      orderGridView.AutoGenerateColumns = false;
      orderGridView.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()
        {
          BindOrderGrid();
        }));
        Thread.Sleep(5000);
      }
    }

    DropPigOrderList lastSelect;
    void BindOrderGrid()
    {
      list = OrderDetailRpc.GetDropPigOrderList(uDatePicker1.Date.Value);
      orderGridView.DataSource = list.OrderBy(x => x.Order).ToList();
      if (lastSelect == null && orderGridView.CurrentRow != null)
      {
        lastSelect = orderGridView.CurrentRow.DataBoundItem as DropPigOrderList;
      }
      foreach (DataGridViewRow row in orderGridView.Rows)
      {
        if ((bool)row.Cells["D_IsDrop"].Value)
          row.DefaultCellStyle.BackColor = Color.Red;
        if (lastSelect != null && lastSelect.Order == (int)row.Cells["D_Order"].Value)
        {
          lastSelect = row.DataBoundItem as DropPigOrderList;
          if (lastSelect.IsDrop)
            row.DefaultCellStyle.BackColor = Color.Red;
          row.DefaultCellStyle.BackColor = orderGridView.RowsDefaultCellStyle.SelectionBackColor;
        }
      }
      InitScrollBar1();
      orderGridView.ClearSelection();
      try
      {
        if (roll != -1)
          orderGridView.FirstDisplayedScrollingRowIndex = roll;
      }
      catch
      {
        roll = -1;
      }
      orderGridView.Refresh();
    }

    int roll = -1;
    private void InitScrollBar1()
    {
      vScrollBar1.Maximum = (orderGridView.RowCount - orderGridView.DisplayedRowCount(false) + 30) * orderGridView.RowTemplate.Height;
      vScrollBar1.Minimum = 0;
      vScrollBar1.SmallChange = orderGridView.RowTemplate.Height;
      vScrollBar1.LargeChange = orderGridView.RowTemplate.Height * 30;
      this.vScrollBar1.Scroll += (sender, e) =>
      {
        roll = e.NewValue / orderGridView.RowTemplate.Height;
        orderGridView.FirstDisplayedScrollingRowIndex = roll;
      };
    }
    private void OkBtn_Click(object sender, EventArgs e)
    {
      if (lastSelect == null)
        throw new Exception("请选选择掉猪的行记录");
      if(lastSelect.IsDrop)
        throw new Exception("不可以对掉猪的明细在做掉猪处理。");
      bool ok = false;
      List<int> order = new List<int>();
      if (!string.IsNullOrEmpty(tangInput.Text))
      {
        var num = int.Parse(tangInput.Text);
        if (num != 0)
        {
          ok = true;
          order.Add(OrderDetailRpc.InsertDropPig(lastSelect.OrderDetail_ID, num, 0));
        }
        tangInput.Clear();
      }
      if (!string.IsNullOrEmpty(maoInput.Text))
      {
        var num = int.Parse(maoInput.Text);
        if (num != 0)
        {
          ok = true;
          order.Add(OrderDetailRpc.InsertDropPig(lastSelect.OrderDetail_ID, num, 1));
        }
        maoInput.Clear();
      }
      if (ok)
      {
        UMessageBox.Show(string.Format("处理成功！{0}新的排宰顺序号为：{1}", Environment.NewLine, string.Join("、", order)), "成功提示");
        BindOrderGrid();
      }
      else
        UMessageBox.Show("请输入烫褪或毛剥头数", "错误");
    }

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

    private void orderGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      var entity = orderGridView.CurrentRow.DataBoundItem as DropPigOrderList;
      if (lastSelect != null)
      {
        foreach (DataGridViewRow row in orderGridView.Rows)
        {
          if (lastSelect.Order == (int)row.Cells["D_Order"].Value)
          {
            if (lastSelect.IsDrop)
              row.DefaultCellStyle.BackColor = Color.Red;
            else
              row.DefaultCellStyle.BackColor = orderGridView.RowsDefaultCellStyle.BackColor;
            break;
          }
        }
      }
      lastSelect = entity;

      if (lastSelect.IsDrop)
        orderGridView.CurrentRow.DefaultCellStyle.SelectionBackColor = Color.Red;
      orderGridView.Refresh();
    }
  }
}
