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 BO.BO.Bill;
using BO.Utils.BillRpc;

namespace WeighAndGrading
{
  public partial class AbnormalModifyForm : Form
  {
    List<GradeAndWeight_Detail> details;
    private DateTime mDate;

    GradeAndWeight_Detail mCurrentSlectItem;
    public AbnormalModifyForm(DateTime date)
    {
      InitializeComponent();
      mDate = date;
      uDataGridView1.AutoGenerateColumns = false;
    }


    private void AbnormalModifyForm_Load(object sender, EventArgs e)
    {
      BindGridView();
      AddKeyPad();
      if (uDataGridView1.Rows.Count > 0)
      {
        uDataGridView1.Rows[0].Selected = true;
        var currentRow = uDataGridView1.Rows[0].DataBoundItem as GradeAndWeight_Detail;
        mCurrentSlectItem = currentRow;
      }

      var tangtuiList = GradeAndWeightRpc.GetGradeAndWeightList(mDate, true);
      var maoboList = GradeAndWeightRpc.GetGradeAndWeightList(mDate, false);

      lblPaiZaiTT.Text = tangtuiList.Sum(x => x.Number).ToString();
      lblPaiZaiMB.Text = maoboList.Sum(x => x.Number).ToString();


      var tangtui = LocalGradeAndWeightBL.GetSumNumber(mDate,0);
      var maobo = LocalGradeAndWeightBL.GetSumNumber(mDate, 1);
      var weight = LocalGradeAndWeightBL.GetSumWeight(mDate);

      lblWeightTT.Text = tangtui.ToString();
      lblWeightMB.Text = maobo.ToString();
      lblWeightWeight.Text = weight.ToString("f2");
    }

    private void BindGridView()
    {
      details = LocalGradeAndWeightBL.GetLostWeightDetails(mDate);
      if (details.Any())
      {
        foreach (GradeAndWeight_Detail detail in details)
        {
          if (detail.Weight.HasValue && detail.Weight == 0)
          {
            detail.Weight = null;
          }

        }
        uDataGridView1.DataSource = details;
      }
    }


    private void AddKeyPad()
    {
      for (var i = 1; i < 10; i++)
      {
        var btn = new Button() { Name = "_3" + i, Text = i.ToString(), Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
        btn.Click += (sender, e) =>
        {
          ModifyWeight(btn.Text);
        };
        flpKeyPanel.Controls.Add(btn);
      }
      var zero = new Button() { Name = "_30", Text = "0", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      zero.Click += (sender, e) =>
      {
        ModifyWeight(zero.Text);
      };
      flpKeyPanel.Controls.Add(zero);

      var dian = new Button() { Name = "_40", Text = ".", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      dian.Click += (sender, e) =>
      {
        ModifyWeight(dian.Text);
      };
      flpKeyPanel.Controls.Add(dian);

      var back = new Button() { Name = "_3back", Text = "←", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      back.Click += (sender, e) =>
      {
        ModifyWeight(back.Text);
      };
      flpKeyPanel.Controls.Add(back);

      var clear = new Button() { Name = "_3clear", Text = "清空", Size = new Size(80, 60), TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding { All = 10 }, Font = new Font("宋体", 15) };
      clear.Click += (sender, e) =>
      {
        ModifyWeight(clear.Text);
      };
      flpKeyPanel.Controls.Add(clear);

    }

    //    private decimal? lastWeght;
    private void ModifyWeight(string input)
    {
      if (mCurrentSlectItem == null)
        throw new Exception("请选择一条记录");

      var destring = DecimalToString(mCurrentSlectItem.Weight);
      var value = GetAfterNumber(destring, input);
      mCurrentSlectItem.Weight = StringToDecimal(value);

      uDataGridView1.Refresh();


    }


    decimal? StringToDecimal(string value)
    {
      if (string.IsNullOrWhiteSpace(value))
      {
        return null;
      }
      value = value.Replace("..", ".");
      if (value.Length > 1)
      {
        var last = value.Substring(value.Length - 1);
        if (last == ".")
        {
          value += "0";
        }
      }
      try
      {
        return decimal.Parse(value);
      }
      catch
      {
        return null;
      }

    }

    string DecimalToString(decimal? value)
    {
      if (value == null)
      {
        return "";
      }

      try
      {

        var newvalue = value.ToString();
        if (newvalue.Length > 2)
        {
          var lasttwo = newvalue.Substring(newvalue.Length - 2);
          if (lasttwo == ".0")
          {
            var intvalue = Convert.ToInt32(value);
            return intvalue.ToString() + ".";
          }
        }

        return value.ToString() + "";
      }
      catch
      {
        return value.ToString();
      }
    }

    string GetAfterNumber(string oldValue, string input)
    {
      bool hasValue = !string.IsNullOrWhiteSpace(oldValue);
      switch (input)
      {
        case ".":
          if (hasValue)
            return (oldValue + ".");
          return null;
        case "0":
          if (hasValue)
            return (oldValue + "0");
          return null;
        case "←":
          if (hasValue)
          {
            var s = oldValue.ToString();
            s = s.Substring(0, s.Length - 1);
            if (string.IsNullOrEmpty(s))
              return null;
            return (s);
          }
          return null;
        case "清空":
          return null;
        default:
          var sn = "";
          if (hasValue)
            sn = oldValue.ToString();
          sn += input;
          return (sn);
      }
    }

    private void button1_Click(object sender, EventArgs e)
    {
      foreach (GradeAndWeight_Detail detail in details.Where(x => x.Weight.HasValue))
      {
        detail.IsLostWeight = false;
        LocalGradeAndWeightBL.Update(detail, "Weight", "IsLostWeight");
      }
      details = LocalGradeAndWeightBL.GetLostWeightDetails(mDate);
      uDataGridView1.Refresh();
      MessageBox.Show("保存成功");
      DialogResult = DialogResult.OK;
      Close();
    }

    private void uDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex < 0)
        return;
      var currentRow = uDataGridView1.CurrentRow.DataBoundItem as GradeAndWeight_Detail;
      mCurrentSlectItem = currentRow;
    }
  }
}
