using BO;
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.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WeighAndGrading
{
  public partial class DataConfirm : Form
  {
    List<DataConfirmList> leftList;
    List<GradeAndWeight_Detail> weightList;
    public DataConfirm()
    {
      InitializeComponent();

      uDatePicker1.Date = DateTime.Today;
      orderGridView.AutoGenerateColumns = false;
      weightGrid.AutoGenerateColumns = false;
      AddLivestockBtn();
    }

    private void leftBtn_Click(object sender, EventArgs e)
    {
      orderGridView.DataSource = null;
      int? order = null;
      if (!string.IsNullOrEmpty(leftOrder.Text))
        order = int.Parse(leftOrder.Text);
      leftList = GradeAndWeightRpc.GetDataConfirmList(uDatePicker1.Date.Value, order);
      orderGridView.DataSource = leftList;
      orderGridView.Refresh();
    }

    private void rightBtn_Click(object sender, EventArgs e)
    {
      weightGrid.DataSource = null;
      int? order = null;
      if (!string.IsNullOrEmpty(rightOrder.Text))
        order = int.Parse(rightOrder.Text);
      int? idx = null;
      if (!string.IsNullOrEmpty(rightIndex.Text))
        idx = int.Parse(rightIndex.Text);
      weightList = LocalGradeAndWeightBL.GetGradeAndWeightDetails(uDatePicker1.Date.Value, order, idx);
      weightGrid.DataSource = weightList;
      InitTangScrollBar();
      try
      {
        if (rollIdx != -1)
          weightGrid.FirstDisplayedScrollingRowIndex = rollIdx;
      }
      catch
      {
        rollIdx = -1;
      }
      weightGrid.Refresh();
      var number = LocalGradeAndWeightBL.GetSumNumber(uDatePicker1.Date.Value, order);
      var tang = number.FirstOrDefault(x => x.Item1 == 0);
      tangNumber.Text = "0";
      if (tang != null)
        tangNumber.Text = tang.Item2.ToString();
      var mao = number.FirstOrDefault(x => x.Item1 == 1);
      maoNumber.Text = "0";
      if (mao != null)
        maoNumber.Text = mao.Item2.ToString();
      tangNumber.Refresh();
      maoNumber.Refresh();
    }

    void AddLivestockBtn()
    {
      var fileName = Path.Combine(GradeFrom.DATA_PATH, "Livestocks.xml");

      var livestocks = XmlUtil.DeserializeFromFile<List<CTuple<long, string, short, string>>>(fileName);
      foreach (var item in livestocks)
      {
        var btn = new Button() { Name = "_" + item.Item1, Text = item.Item2, Tag = item, Size = new Size(90, 75), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 15 }, Font = new Font("宋体", 18) };

        btn.Click += (sender, e) =>
        {
          var tg = btn.Tag as CTuple<long, string, short, string>;
          if (select == null)
            throw new Exception("请选择修改的记录");
          select.Livestock_ID = tg.Item1;
          select.Livestock_Name = tg.Item2;
          select.Technics = tg.Item3;
          select.Technics_Name = tg.Item3 == 0 ? "烫褪" : "毛剥";
          weightGrid.Refresh();
        };
        if (item.Item3 == 0)
        {
          ttPanel.Controls.Add(btn);
        }
        else
        {
          mbPanel.Controls.Add(btn);
        }
      }
      SetMargin(ttPanel);
      SetMargin(mbPanel);
    }

    void SetMargin(FlowLayoutPanel panel)
    {
      for (var i = 0; i < panel.Controls.Count; i++)
      {
        var c = panel.Controls[i];
        if (i % 3 == 0)//left
          c.Margin = new Padding(0, c.Margin.Top, c.Margin.Right, c.Margin.Bottom);
        if ((i + 1) % 3 == 0)//right
          c.Margin = new Padding(c.Margin.Left, c.Margin.Top, 0, c.Margin.Bottom);
        if (i <= 2)//firstRow
          c.Margin = new Padding(c.Margin.Left, 0, c.Margin.Right, c.Margin.Bottom);
      }
    }

    GradeAndWeight_Detail select;
    GradeAndWeight_Detail old;
    private void weightGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      if (e.ColumnIndex == 7)
      {
        LocalGradeAndWeightBL.InsertOrUpdate(select);
        rightBtn_Click(sender, EventArgs.Empty);
      }
    }

    private void weightGrid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      select = weightGrid.CurrentRow.DataBoundItem as GradeAndWeight_Detail;
      old = new GradeAndWeight_Detail { Order = select.Order, OrderDetail_ID = select.OrderDetail_ID, Technics = select.Technics };
      if (e.ColumnIndex==1||e.ColumnIndex == 2 || e.ColumnIndex == 5)
      {
        var keyBoard = new NumberPad();
        if (keyBoard.ShowDialog() == true)
        {
          var num = keyBoard.Result;
          if (e.ColumnIndex == 1)
          {
            if (string.IsNullOrEmpty(num))
              throw new Exception("请输入序号");
            select.Index = int.Parse(num);
          }
          else if (e.ColumnIndex == 2)
            select.Order = string.IsNullOrEmpty(num) ? 0 : int.Parse(num);
          else
            select.Weight = string.IsNullOrEmpty(num) ? 0 : decimal.Parse(num);
          weightGrid.Refresh();
        }
      }
    }

    private void orderGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1)
        return;
      var row = orderGridView.CurrentRow.DataBoundItem as DataConfirmList;
      rightOrder.Text = row.Order.ToString();
      rightIndex.Text = string.Empty;
      rightBtn_Click(sender, EventArgs.Empty);
    }

    private void AddBtn_Click(object sender, EventArgs e)
    {
      weightList.Add(new GradeAndWeight_Detail() { Time = DateTime.Now, Date = uDatePicker1.Date.Value });
      weightGrid.DataSource = null;
      weightGrid.DataSource = weightList;
      weightGrid.Refresh();
    }

    private void deleteBtn_Click(object sender, EventArgs e)
    {
      if (MessageBox.Show("确定删除选中一条称重记录？", "删除选中", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
      {
        return;
      }
      if (select == null)
        throw new Exception("请选择删除的行");
      var first = weightList.First(x => x.SID == select.SID);
      if (first.SID == 0)
        weightList.Remove(first);
      else
        LocalGradeAndWeightBL.DeleteBySID(select.SID);
      select = null;
      rightBtn_Click(sender, EventArgs.Empty);
    }

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