using ButcherFactory.BO;
using ButcherFactory.BO.Rpcs;
using ButcherFactory.BO.Utils;
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;
using ButcherFactory.Utils;
using WinFormControl;
using ButcherFactory.BO.LocalBL;
using ButcherFactory.Dialogs;
using ButcherFactory.BO.Bill;

namespace ButcherFactory.SegmentPickUp_
{
  public partial class SegmentPickUpForm : Form, IWithRoleForm
  {
    #region IWithRoleForm
    public List<short> RoleName
    {
      get { return new List<short> { (short)设备类别.分割领用 }; }
    }

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

    const string FilePatch = @"Config\NumberSetDialog.cfg";
    Thread uploadData;
    BindingList<SegmentPickUp> needSubmitedList;
    BindingList<SegmentPickUp> historyList;
    SegmentPickUpConfig config;

    long? batchID;

    public SegmentPickUpForm()
    {
      InitializeComponent();
      BuildNumberPanel();
      workUnitSelect.SelectedIndexChanged += delegate
      {
        if (workUnitSelect.SelectedValue == null)
          config.WorkUnitID = null;
        else
          config.WorkUnitID = (long)workUnitSelect.SelectedValue;
        XmlUtil.SerializerObjToFile(config);
      };
      storeSelect.SelectedIndexChanged += delegate
      {
        if (storeSelect.SelectedValue == null)
          config.Store_ID = null;
        else
          config.Store_ID = (long)storeSelect.SelectedValue;
        XmlUtil.SerializerObjToFile(config);
      };
      productBatchSelect.SelectedIndexChanged += delegate
      {
        if (productBatchSelect.SelectedValue == null)
          batchID = null;
        else
          batchID = (long)productBatchSelect.SelectedValue;
      };
      this.FormClosing += delegate
      {
        if (uploadData != null && uploadData.IsAlive)
          uploadData.Abort();
      };
    }

    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
      var initTask = new Thread(LoadBind);
      initTask.Start();

      uploadData = new Thread(UpLoadLocalData);
      uploadData.Start();
    }

    private void LoadBind()
    {
      this.Invoke(new Action(() =>
      {
        BLUtil.DeleteLocalDb<SegmentPickUp>();
        BaseInfoSyncRpc.SyncGoodsByTag(ApplyClient.分割领用);
        BaseInfoSyncRpc.SyncBaseInfo<WorkUnit>();
        BaseInfoSyncRpc.SyncProductBatch(1);
        BaseInfoSyncRpc.SyncBaseInfo<Store>();

        productBatchSelect.EBindComboBox<ProductBatch>(x => x.Date == DateTime.Today, 6, "Date");
        config = XmlUtil.DeserializeFromFile<SegmentPickUpConfig>();
        workUnitSelect.EBindComboBox<WorkUnit>(x => x.ID == config.WorkUnitID, top: 100);
        storeSelect.EBindComboBox<Store>(x => x.ID == config.Store_ID, top: 100);
        BindGoods();
        BindGrid();
      }));
    }

    List<UButton> goodsBtns = new List<UButton>();
    void BindGoods()
    {
      var goods = FormClientGoodsSetBL.GetGoodsList();
      foreach (var item in goods)
      {
        var btn = new UButton() { Width = 120, Height = 75, Text = item.Goods_Name, Tag = item.Goods_ID, Font = new Font("宋体", 15), Margin = new Padding(22, 10, 22, 30), PlaySound = true };
        btn.Click += GoodsBtnClick;
        goodsBtns.Add(btn);
        flowLayoutPanel1.Controls.Add(btn);
      }
    }

    void GoodsBtnClick(object sender, EventArgs e)
    {
      if (batchID == null)
        throw new Exception("请先选择批次");
      if (config.Store_ID == null)
        throw new Exception("请先选择仓库");
      if (uWeightControl1.Weight == 0)
        throw new Exception("重量不能为0！");
      var c = sender as UButton;
      var entity = new SegmentPickUp();
      entity.RowIndex = GetRowIndex();
      entity.Weight = uWeightControl1.Weight;
      entity.Goods_ID = (long)c.Tag;
      entity.Goods_Name = c.Text;
      entity.ProductBatch_ID = batchID;
      entity.WorkUnit_ID = config.WorkUnitID;
      entity.Store_ID = config.Store_ID;
      SegmentPickUpBL.InsertEntityByWeight(entity);
      needSubmitedList.Insert(0, entity);
      AfterInsert();
    }

    void BindGrid()
    {
      needSubmitedList = SegmentPickUpBL.GetSegmentPickUp(false);
      needSubmitGrid.DataSource = needSubmitedList;
      needSubmitGrid.Refresh();

      historyList = SegmentPickUpBL.GetSegmentPickUp(true);
      historyDataGrid.DataSource = historyList;
      historyDataGrid.Refresh();
    }

    private void UpLoadLocalData()
    {
      while (true)
      {
        if (this.IsHandleCreated)
        {
          this.Invoke(new Action(() =>
          {
            SegmentPickUpBL.UploadSegmentInfo();
          }));
        }
        Thread.Sleep(2000);
      }
    }

    void AfterInsert()
    {
      needSubmitGrid.FirstDisplayedScrollingRowIndex = 0;
      needSubmitGrid.Rows[0].Selected = true;
      needSubmitGrid.CurrentCell = needSubmitGrid.Rows[0].Cells[2];
      needSubmitGrid.Refresh();
    }

    int GetRowIndex()
    {
      var f = needSubmitedList.FirstOrDefault(x => x.CreateTime.Date == DateTime.Today);
      if (f != null)
        return f.RowIndex.Value + 1;
      else if (historyList.Any())
        return historyList.First().RowIndex.Value + 1;
      else
        return 1;
    }

    private void closeBtn_Click(object sender, EventArgs e)
    {
      Close();
    }

    private void submitBtn_Click(object sender, EventArgs e)
    {
      if (needSubmitedList.Count == 0)
        throw new Exception("没有待提交记录");
      var arr = needSubmitedList.ToList();
      arr.Reverse();
      SegmentPickUpBL.UpdateSubmit(needSubmitedList.Select(x => x.ID));
      foreach (var item in arr)
      {
        historyList.Insert(0, item);
        if (historyList.Count > 50)
          historyList.RemoveAt(50);
        needSubmitedList.Remove(item);
      }
      historyDataGrid.FirstDisplayedScrollingRowIndex = 0;
      historyDataGrid.Refresh();
      needSubmitGrid.Refresh();
    }

    private void numSetBtn_Click(object sender, EventArgs e)
    {
      new NumberSetDialog().ShowDialog();
      BuildNumberPanel();
    }

    void BuildNumberPanel()
    {
      numFlowPanel.Controls.Clear();
      if (!System.IO.File.Exists(FilePatch))
        return;
      var simpBtn = new UButton() { Width = 100, Height = 34, Text = "自定义", Font = new Font("宋体", 15), Margin = new Padding(6, 2, 6, 0), WithStataHode = true, EnableGroup = true };
      simpBtn.Click += delegate
      {
        var cr = GetCurrentRowEntity();
        if (cr == null)
          return;
        var keyBoard = new NumberPad();
        if (keyBoard.ShowDialog() == true)
        {
          var v = 0;
          if (int.TryParse(keyBoard.Result, out v) && v > 0)
          {
            cr.Number = v;
            SegmentPickUpBL.UpdateNumber(cr.ID, cr.Number);
            needSubmitGrid.Refresh();
          }
          else
            throw new Exception("输入数量有误！");
        }
      };
      numFlowPanel.Controls.Add(simpBtn);
      var arr = System.IO.File.ReadAllText(FilePatch).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Reverse();
      foreach (var item in arr)
      {
        var btn = new UButton() { Width = 100, Height = 34, Text = item, Font = new Font("宋体", 15), Margin = new Padding(6, 2, 6, 0), WithStataHode = true, EnableGroup = true };
        btn.Click += (sender, e) =>
        {
          var row = GetCurrentRowEntity();
          if (row == null)
            return;
          var b = sender as UButton;
          row.Number = int.Parse(b.Text);
          SegmentPickUpBL.UpdateNumber(row.ID, row.Number);
          needSubmitGrid.Refresh();
        };
        numFlowPanel.Controls.Add(btn);
      }
    }

    SegmentPickUp GetCurrentRowEntity()
    {
      if (needSubmitGrid.CurrentRow == null)
        return null;
      return needSubmitGrid.CurrentRow.DataBoundItem as SegmentPickUp;
    }
  }
}
