using BO;
using BO.BO.Bill;
using BO.Utils;
using BO.Utils.BillRpc;
using BWP.WinFormControl;
using BWP.WinFormControl.WeightDataFormat;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;



namespace CarcassStateWeight
{
  public partial class CarcassStateWeightForm : Form, IAfterLogin
  {

    #region IAfterLogin
    public string RoleName
    {
      get { return "定级员"; }
    }

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

    List<BO.BO.Bill.CarcassStateWeight> list;
    List<BO.BO.Bill.CarcassStateWeight> details;
    Thread syncWork;
    private delegate void InvokeHandler();

    SerialPort weightPort;
    int maxIndex = 0;


    public CarcassStateWeightForm()
    {
      InitializeComponent();

      houseList = ProductEntity.Init(BaseInfoRpcUtil.GetBaseInfoEntity("GetWhiteBarList"));
      AddHouseBtn();
      details = new List<BO.BO.Bill.CarcassStateWeight>();

    }



    private void syncBtn_Click(object sender, EventArgs e)
    {
      list = CarcassStateWeightRpc.GetCarcassStateWeightList(butcherTimeInput.Date.Value);
      BindDataGrid();
      //tangRow = FindRowSetSelected(tangEntity);
      //maoRow = FindRowSetSelected(maoEntity);
      dataGridViewSync.Refresh();
           
      //if (syncWork == null || !syncWork.IsAlive)
      //{
      //  syncWork = new Thread(Sync);
      //  syncWork.Start();
      //  syncBtn.BackColor = Color.FromArgb(15, 215, 107);
      //  syncBtn.ForeColor = Color.White;
      //}
      //else
      //{
      //  syncBtn.BackColor = Color.FromKnownColor(KnownColor.Control)
      //  syncWork.Abort();;
      //  syncBtn.ForeColor = Color.FromKnownColor(KnownColor.ControlText);
      //}
    }

    void Sync()
    {
      while (true)
      {
        Thread.Sleep(5000);
        this.Invoke(new InvokeHandler(delegate ()
        {
          list = CarcassStateWeightRpc.GetCarcassStateWeightList(butcherTimeInput.Date.Value);
          BindDataGrid();
          //tangRow = FindRowSetSelected(tangEntity);
          //maoRow = FindRowSetSelected(maoEntity);
          dataGridViewSync.Refresh();
        }));
      }
    }

    void BindDataGrid()
    {
      dataGridViewSync.DataSource = list.OrderBy(x => x.Time).ToList();
      //foreach (DataGridViewRow row in dataGridViewSync.Rows)
      //{
      //  if ((bool)row.Cells["D_Finish"].Value)
      //    row.DefaultCellStyle.BackColor = Color.YellowGreen;
      //}
    }
 
    DataGridViewRow FindRowSetSelected(GradeAndWeight tag)
    {
      ////if (tag == null)
      ////  return null;
      ////foreach (DataGridViewRow row in dataGridViewSync.Rows)
      ////{
      ////  if ((long)row.Cells["D_OrderDetail_ID"].Value == tag.OrderDetail_ID && (string)row.Cells["D_Technics_Name"].Value == tag.Technics_Name)
      ////  {
      ////    if (tag.Finish)
      ////      row.DefaultCellStyle.BackColor = Color.YellowGreen;
      ////    else
      ////      row.DefaultCellStyle.BackColor = tag.Technics == 1 ? Color.Yellow : dataGridViewSync.RowsDefaultCellStyle.SelectionBackColor;

      ////    if (tag.Technics == 0)
      ////      tangEntity = row.DataBoundItem as GradeAndWeight;
      ////    else
      ////      maoEntity = row.DataBoundItem as GradeAndWeight;
      ////    return row;
      ////  }
      ////}
      return null;
    }





    private void commitBtn_Click(object sender, EventArgs e)
    {
      List<BO.BO.Bill.CarcassStateWeight> listCsw = new List<BO.BO.Bill.CarcassStateWeight>();
      for (int i = 0; i < dataGridViewCode.Rows.Count; i++)
      {
        DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell) dataGridViewCode.Rows[i].Cells["cb_check"];
        Boolean flag = Convert.ToBoolean(checkCell.Value);
        if (flag == true) //查找被选择的数据行 
        {
          DataGridViewRow row = dataGridViewCode.Rows[i];
          BO.BO.Bill.CarcassStateWeight slectedCSW = row.DataBoundItem as BO.BO.Bill.CarcassStateWeight;
          listCsw.Add(slectedCSW);
        }
      }
      foreach (var csw in listCsw)
      {
        CarcassStateWeightRpc.UpdateOrInsertDetail(csw);
        details.Remove(csw);
      }

      dataGridViewCode.DataSource = null;
      dataGridViewCode.DataSource = details;
      dataGridViewCode.Refresh();

    }




    List<Button> houseSelectedBtn = new List<Button>();
    List<Button> houseBtn = new List<Button>();
    List<ProductEntity> houseList;
    readonly Color btnSelectForeColor = Color.FromArgb(255, 255, 255);
    readonly Color btnSelectBackColor = Color.FromArgb(66, 163, 218);
    Color btnUnSelectForeColor = SystemColors.ControlText;
    Color btnUnSelectBackColor = Color.FromArgb(225, 225, 225);
    private void AddHouseBtn()
    {
      int pageSize = 48;
      foreach (var houseItems in houseList)
      {
        var tabPage = new TabPage(houseItems.Part);
        tabPage.Name = string.Format("house_{0}", houseItems.Part);
        var flowCount = houseItems.Details.Count / 48;
        if (houseItems.Details.Count % 48 != 0)
          flowCount += 1;
        FlowLayoutPanel pageBtnPanel = null;
        for (var i = 0; i < flowCount; i++)
        {
          var houseFlow = new FlowLayoutPanel() { RightToLeft = RightToLeft.No, Name = string.Format("houseFlow_{0}", houseItems.Part), BorderStyle = BorderStyle.FixedSingle };
          if (flowCount > 1)
          {
            if (i == 0)
            {
              pageBtnPanel = new FlowLayoutPanel() { Dock = DockStyle.Bottom, Height = 65, RightToLeft = RightToLeft.No, BorderStyle = BorderStyle.FixedSingle };
              pageBtnPanel.Location = new Point(3, 492 - 65);
            }
            else
              houseFlow.Visible = false;
            var btn = new Button() { Text = (i + 1).ToString(), Tag = houseFlow, Size = new Size(75, 55), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 5 }, Font = new Font("宋体", 15) };
            pageBtnPanel.Controls.Add(btn);
            btn.Click += (sender, e) =>
            {
              var currentBind = btn.Tag as FlowLayoutPanel;
              foreach (var subControl in pageBtnPanel.Controls)
              {
                var pb = subControl as Button;
                var p = pb.Tag as FlowLayoutPanel;
                p.Visible = currentBind == p;
              }
            };
            houseFlow.Width = 709;
            houseFlow.Height = 492 - 70;
          }
          else
            houseFlow.Dock = DockStyle.Fill;
          tabPage.Controls.Add(houseFlow);
          if (pageBtnPanel != null)
            tabPage.Controls.Add(pageBtnPanel);
          int idx = i * pageSize;
          for (var j = 0; j < pageSize; j++)
          {
            var padding = new Padding { All = 5 };
            if ((idx + 1) % 8 != 0 && (idx + 1) % 4 == 0)
              padding = new Padding(5, 5, 15, 5);
            var house = houseItems.Details[idx];
            var btn = new Button() { Name = "_" + house.Item1, Tag = house, Text = house.Item2, Size = new Size(77, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = padding, Font = new Font("宋体", 12), BackColor = btnUnSelectBackColor };
            btn.Click += (sender, e) =>
            {
              if (houseSelectedBtn.Contains(btn))
              {
                btn.BackColor = btnUnSelectBackColor;
                btn.ForeColor = btnUnSelectForeColor;
                houseSelectedBtn.Remove(btn);
              }
              else
              {
                btn.BackColor = btnSelectBackColor;
                btn.ForeColor = btnSelectForeColor;
                houseSelectedBtn.Add(btn);
              }
            };
            houseBtn.Add(btn);
            houseFlow.Controls.Add(btn);
            idx += 1;
            if (idx == houseItems.Details.Count)
              break;
          }
        }
        uTabControl1.TabPages.Add(tabPage);
      }
      if (uTabControl1.TabPages.Count != 0)
        uTabControl1.SelectedIndex = uTabControl1.TabPages.Count - 1;
    }





    private void textBox1_TextChanged(object sender, EventArgs e)
    {

      string value = textBox1.Text.ToString().Trim();
      long code = Convert.ToInt64(value);
      List<GradeAndWeight_Detail> gawDetailList = CarcassStateWeightRpc.GetGradeAndWeight_DetailByCode(code);
      GradeAndWeight_Detail gawDetail = gawDetailList[0];
      if (gawDetail != null)
      {
        BO.BO.Bill.CarcassStateWeight newCarcassStateWeight;
        newCarcassStateWeight = new BO.BO.Bill.CarcassStateWeight();
        newCarcassStateWeight.Code = code;
        newCarcassStateWeight.Nubmber = 1;
        newCarcassStateWeight.State1Weight = gawDetail.Weight;
        int r = new Random().Next();
        newCarcassStateWeight.GradeAndWeight_ID = DateTime.Now.ToFileTime() + r;
        newCarcassStateWeight.Product_ID = gawDetail.Livestock_ID;
        newCarcassStateWeight.Product_Name = gawDetail.Livestock_Name;
        newCarcassStateWeight.Time = DateTime.Now;
        AddDetail(newCarcassStateWeight);
      }

    }

    static object _obj = new object();
    void AddDetail(BO.BO.Bill.CarcassStateWeight currentRow)
    {
      lock (_obj)
      {
        maxIndex++;
        var entity = new BO.BO.Bill.CarcassStateWeight();
        //entity.Index = maxIndex;
        if (currentRow != null)
        {
          details.Insert(0, currentRow);
        }
        //CarcassStateWeightRpc.UpdateOrInsertDetail(entity, true);
        BindDetailGrid();
      }
    }
    void BindDetailGrid()
    {
      dataGridViewCode.DataSource = null;
      if (details.Any())
        dataGridViewCode.DataSource = details;
      if (lastSelectID.HasValue)
      {
        foreach (DataGridViewRow row in dataGridViewCode.Rows)
        {
          if ((long)row.Cells["GradeAndWeight_ID"].Value == lastSelectID)
          {
            dataGridViewCode.CurrentCell = row.Cells[row.Cells.Count - 1];
            break;
          }
        }
      }
     dataGridViewCode.Refresh();
    }






    BO.BO.Bill.CarcassStateWeight lastCheckItem;
    long? lastSelectID = null;
    BO.BO.Bill.CarcassStateWeight modifyDetail;
    private void dataGridViewCode_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

      //if (e.RowIndex < 0)
      //  return;
      //var currentRow = dataGridViewCode.CurrentRow.DataBoundItem as BO.BO.Bill.CarcassStateWeight;
      //lastSelectID = currentRow.GradeAndWeight_ID;
      //if (e.ColumnIndex == 2)
      //{
      //  if (lastCheckItem != null && lastCheckItem.ID != currentRow.ID)
      //    lastCheckItem.ReadWeight = false;
      //  lastCheckItem = currentRow;
      //  lastCheckItem.ReadWeight = !lastCheckItem.ReadWeight;

      //  modifyDetail = null;
      //  //if (modifyPanel.Visible)
      //    //modifyPanel.Hide();
      //  dataGridViewCode.Refresh();
      //  if (lastCheckItem.ReadWeight)
      //  {
      //    //noWeightList = new ConcurrentQueue<CarcassStateWeight>();
      //    var stack = new Stack<BO.BO.Bill.CarcassStateWeight>();
      //    foreach (var item in details)
      //    {
      //      stack.Push(item);
      //      if (item.ID == lastCheckItem.ID)
      //        break;
      //    }
      //    //while (stack.Count > 0)
      //      //noWeightList.Enqueue(stack.Pop());
      //  }
      //  else
      //  {
      //    //FillQueue();
      //    lastCheckItem = null;
      //  }
      //  return;
      //}
      //modifyDetail = currentRow;
      ////stateLabel.Text = string.Format("您正在修改序号为 {0} 的信息", modifyDetail.Index);
      ////modifyPanel.Show();
    }

    private void dataGridViewSync_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void CarcassStateWeightForm_Load(object sender, EventArgs e)
    {

    }
  }

  class ProductEntity
  {
    public string Part { get; set; }

    List<Tuple<string, string>> details = new List<Tuple<string, string>>();
    public List<Tuple<string, string>> Details { get { return details; } }

    public static List<ProductEntity> Init(List<Tuple<string, string>> list)
    {
      var result = new List<ProductEntity>();
      foreach (var item in list)
      {
        var part = item.Item2[0].ToString();
        if (part.Contains("去"))
          part = "去皮白条";
        else if (part.Contains("带"))
          part = "带皮白条";
        var first = result.FirstOrDefault(x => x.Part == part);
        if (first == null)
        {
          first = new ProductEntity { Part = part };
          result.Add(first);
        }
        first.Details.Add(new Tuple<string, string>(item.Item1, item.Item2));
      }
      result.Reverse();
      return result;
    }
  }


}
