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.Tasks;
using System.Windows.Forms;
using ButcherFactory.Utils;
using ButcherFactory.BO.LocalBL;
using WinFormControl;
using System.Threading;
using ButcherFactory.Controls;
using ButcherFactory.Dialogs;

namespace ButcherFactory.CarcassInStore_
{
  public partial class CarcassInStoreForm : Form, IWithRoleForm
  {
    #region IWithRoleForm

    public List<short> RoleName
    {
      get { return new List<short> { (short)设备类别.白条入库 }; }
    }

    public Form Generate()
    {
      return this;
    }

    #endregion

    Thread syncBeforeWeight;
    Thread uploadData;
    Thread checkWeight;
    BindingList<CarcassInStore> needSubmitedList;
    BindingList<CarcassInStore> historyList;
    Dictionary<string, List<ClientGoodsSet_Detail>> goodsSetDic;
    long? workUnitID;
    long? batchID;
    List<int> errorWeight = new List<int>();
    string strErrorWeight = "";
    public long? changeID = null;
    public CarcassInStoreForm()
    {
      InitializeComponent();
      netStateWatch1.GetConnectState = () => LoginUtil.TestConnection(500);
      this.FormClosing += delegate
      {
        if (syncBeforeWeight != null && syncBeforeWeight.IsAlive)
          syncBeforeWeight.Abort();
        if (uploadData != null && uploadData.IsAlive)
          uploadData.Abort();
        if (checkWeight != null && checkWeight.IsAlive)
          checkWeight.Abort();
      };
      workUnitSelect.SelectedIndexChanged += delegate
      {
        if (workUnitSelect.SelectedValue == null)
          workUnitID = null;
        else
          workUnitID = (long)workUnitSelect.SelectedValue;
        XmlUtil.SerializerObjToFile(new CarcassInStoreFormConfig { Weight = strErrorWeight, WorkUnitID = workUnitID });
      };
      productBatchSelect.SelectedIndexChanged += delegate
      {
        if (productBatchSelect.SelectedValue == null)
          batchID = null;
        else
          batchID = (long)productBatchSelect.SelectedValue;
      };
    }

    protected override void OnLoad(EventArgs e)
    {
      //this.uWeightControl1.SettingBtn.BackgroundImage = null;
      //this.uWeightControl1.SettingBtn.BackColor = Color.FromArgb(2, 167, 240);
      //this.uWeightControl1.SettingBtn.ForeColor = Color.White;

      //this.uWeightControl1.WeightSwitchBtn.BackgroundImage = null;
      //this.uWeightControl1.WeightSwitchBtn.BackColor = Color.FromArgb(0, 191, 191);
      //this.uWeightControl1.WeightSwitchBtn.ForeColor = Color.White;
      //noWeightBtn.BackgroundImage = null;
      //deleteSelectBtn.BackgroundImage = null;
      //closeBtn.BackgroundImage = null;
      base.OnLoad(e);
      var initTask = new Thread(LoadBind);
      initTask.Start();

      syncBeforeWeight = new Thread(GetBeforeWeight);
      syncBeforeWeight.Start();

      uploadData = new Thread(UpLoadLocalData);
      uploadData.Start();
      weightControl1.ReceivedValue += ReceiveWeight;
    }

    void ReceiveWeight(decimal weight)
    {
      this.Invoke(new Action(() =>
      {
        if (weight <= 0 || weight >= 300)
          return;
        Insert(weight);
        checkWeight = new Thread(new ParameterizedThreadStart(CheckWeight));
        checkWeight.Start(weight);
      }));
    }

    void CheckWeight(object objWeight)
    {
      decimal weight = (decimal)objWeight;
      var first = errorWeight.FirstOrDefault(x => x > weight);
      if (first != 0)
        SoundPalyUtil.PlaySound(string.Format("Sounds\\l{0}.wav", first));
    }

    void LoadBind()
    {
      this.Invoke(new Action(() =>
      {
        BLUtil.DeleteLocalDb<CarcassInStore>();
        if (netStateWatch1.NetState)
        {
          BaseInfoSyncRpc.SyncGoodsByTag(ApplyClient.白条出入库);
          BaseInfoSyncRpc.SyncBaseInfo<WorkUnit>();
          BaseInfoSyncRpc.SyncProductBatch(0);
        }
        productBatchSelect.EBindComboBox<ProductBatch>(x => x.Date == DateTime.Today, 6, "Date");
        var config = XmlUtil.DeserializeFromFile<CarcassInStoreFormConfig>();
        if (!string.IsNullOrEmpty(config.Weight))
        {
          strErrorWeight = config.Weight;
          var arr = strErrorWeight.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).OrderBy(x => x);
          errorWeight.AddRange(arr);
        }
        var m = config.WorkUnitID;
        workUnitSelect.EBindComboBox<WorkUnit>(x => x.ID == m, top: 100);

        BindGoods();
        BindGrid();
      }));
    }

    bool noCode = false;
    static object _lock = new object();

    private void goodsSetBtn_Click(object sender, EventArgs e)
    {
      new ClientGoodsSetDialog().ShowDialog();
      BindGoods();
    }

    void BindGoods()
    {
      goodsSetDic = FormClientGoodsSetBL.GetSelectedDetail();

      flowLayoutPanel1.Controls.Clear();
      flowLayoutPanel2.Controls.Clear();
      foreach (var item in goodsSetDic)
      {
        var btn = new ColorButton() { Width = 100, Height = 62, Text = item.Key, Font = new Font("宋体", 15), Margin = new Padding(15, 3, 15, 0), EnableGroup = true };
        btn.BackColor = Color.FromArgb(22, 155, 213);
        btn.SelectedColor = Color.FromArgb(0, 191, 191);
        btn.Click += GroupGoodsSetClick;
        flowLayoutPanel2.Controls.Add(btn);
      }
    }

    private void GroupGoodsSetClick(object sender, EventArgs e)
    {
      flowLayoutPanel1.Controls.Clear();
      var groupBtn = sender as ColorButton;
      var arr = goodsSetDic[groupBtn.Text];
      foreach (var item in arr)
      {
        var btn = new ColorButton() { 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, EnableGroup = true };
        btn.SelectedColor = Color.Black;
        btn.Click += GoodsBtnClick;
        flowLayoutPanel1.Controls.Add(btn);
      }
    }

    void GoodsBtnClick(object sender, EventArgs e)
    {
      lock (_lock)
      {
        if (changeID.HasValue)
        {
          ChangeGoods(sender);
          return;
        }
        var last = needSubmitedList.LastOrDefault();
        if (last == null)
          throw new Exception("列表无记录");
        var code = uScanPanel1.TextBox.Text;
        if (!noCode && code.Length != 23)
          throw new Exception("条码格式不正确");
        var c = sender as ColorButton;
        CarcassInStoreBL.FillCodeAndGoods(last.ID, code, (long)c.Tag);
        last.Goods_Name = c.Text;
        last.BarCode = code;
        needSubmitedList.Remove(last);
        needSubmitGrid.Refresh();

        historyList.Insert(0, last);
        if (historyList.Count > 30)
          historyList.RemoveAt(30);
        historyDataGrid.FirstDisplayedScrollingRowIndex = 0;
        historyDataGrid.Refresh();

        if (noCode)
        {
          noCodeBtn_Click(sender, EventArgs.Empty);
          noCodeBtn.Selected = false;
        }
        else
          uScanPanel1.TextBox.Text = string.Empty;
      }
    }

    void ChangeGoods(object sender)
    {
      var btn = sender as ColorButton;
      var tag = historyList.First(x => x.ID == changeID.Value);
      CarcassInStoreBL.ChangeGoods(changeID.Value, (long)btn.Tag);
      tag.Goods_Name = btn.Text;
      changeID = null;
      historyDataGrid.Refresh();
    }

    void Insert(decimal weight)
    {
      lock (_lock)
      {
        if (batchID == null)
          throw new Exception("没有批次信息");

        var entity = CarcassInStoreBL.Insert(workUnitID, batchID.Value, weight);
        needSubmitedList.Insert(0, entity);
        needSubmitGrid.FirstDisplayedScrollingRowIndex = 0;
        needSubmitGrid.Refresh();
      }
    }

    void BindGrid()
    {
      needSubmitedList = CarcassInStoreBL.GetLocalDataWithState(false);
      needSubmitGrid.DataSource = needSubmitedList;
      needSubmitGrid.Refresh();

      historyList = CarcassInStoreBL.GetLocalDataWithState(true);
      historyDataGrid.DataSource = historyList;
      historyDataGrid.Refresh();
    }

    void GetBeforeWeight()
    {
      while (true)
      {
        if (this.IsHandleCreated)
        {
          this.Invoke(new Action(() =>
          {
            if (netStateWatch1.NetState)
            {
              var list = historyList.Where(x => x.BeforeWeight == null && !string.IsNullOrEmpty(x.BarCode)).Take(5);
              if (list.Any())
              {
                var back = CarcassInStoreBL.GetBeforeWeight(list.Select(x => x.BarCode));
                if (back.Any())
                {
                  foreach (var item in back)
                    list.First(x => x.BarCode == item.StringExt1).BeforeWeight = item.DecimalExt1;
                  historyDataGrid.Refresh();
                }
              }
            }
          }));
        }
        Thread.Sleep(2000);
      }
    }

    void UpLoadLocalData()
    {
      while (true)
      {
        if (this.IsHandleCreated)
        {
          this.Invoke(new Action(() =>
          {
            if (netStateWatch1.NetState)
              CarcassInStoreBL.UploadCarcassInfo();
          }));
        }
        Thread.Sleep(2000);
      }
    }

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

    private void noWeightBtn_Click(object sender, EventArgs e)
    {
      Insert(0);
    }

    private void noCodeBtn_Click(object sender, EventArgs e)
    {
      noCode = !noCode;
      noCodeBtn.Text = noCode ? "等待插入" : "无 码";
      noCodeBtn.Selected = noCode;
    }

    private void historyDataGrid_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {
      if (e.RowIndex < 0)
        return;
      DataGridViewRow dgrSingle = historyDataGrid.Rows[e.RowIndex];
      if ((long)dgrSingle.Cells[0].Value == changeID)
      {
        dgrSingle.DefaultCellStyle.ForeColor = Color.Red;
        dgrSingle.DefaultCellStyle.SelectionForeColor = Color.Red;
      }
      else
      {
        dgrSingle.DefaultCellStyle.ForeColor = historyDataGrid.DefaultCellStyle.ForeColor;
        dgrSingle.DefaultCellStyle.SelectionForeColor = historyDataGrid.DefaultCellStyle.SelectionForeColor;
      }
    }

    private void historyDataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex < 0)
        return;
      var v = (long)historyDataGrid.CurrentRow.Cells[0].Value;
      if (v == changeID)
        changeID = null;
      else
        changeID = v;
    }

    private void deleteSelectBtn_Click(object sender, EventArgs e)
    {
      if (MessageBox.Show("确定删除选中记录？", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
        return;
      if (needSubmitGrid.CurrentRow == null)
        return;
      var id = (long)needSubmitGrid.CurrentRow.Cells["U_ID"].Value;
      CarcassInStoreBL.DeleteUnSubmit(id);
      needSubmitedList.Remove(needSubmitedList.First(x => x.ID == id));
      needSubmitGrid.Refresh();
    }
  }
}

