using ButcherFactory.BO;
using ButcherFactory.BO.LocalBL;
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;

namespace ButcherFactory.Dialogs
{
  public partial class WeightRecordDialog : Form
  {
    static Image CheckImg = System.Drawing.Image.FromFile("Images\\check.png");
    static Image UnCheckImg = System.Drawing.Image.FromFile("Images\\uCheck.png");
    BindingList<CarcassSaleOut_Detail> list;
    SaleOutStore_Detail mDetail;
    long? mBatchID = null;
    public bool Changed = false;
    public bool rolBack = false;
    DateTime? mProductTime;
    public WeightRecordDialog(SaleOutStore_Detail detail, bool readOnly, long? batchID,DateTime? productTime)
    {
      InitializeComponent();
      mDetail = detail;
      mBatchID = batchID;
      mProductTime = productTime;
      if (readOnly)
      {
        addBtn.Enabled = false;
        deleteBtn.Enabled = false;
        rollBackBtn.Enabled = false;
      }
      uDataGridView1.BorderStyle = BorderStyle.FixedSingle;
      BindGrid();

      uDataGridView1.RowPrePaint += uDataGridView1_RowPrePaint;
      uDataGridView1.CellPainting += uDataGridView1_CellPainting;
    }

    void uDataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
      var last = uDataGridView1.Rows.Count - 1;
      if (e.RowIndex == last)
      {
        if (e.ColumnIndex == 2)
        {
          e.PaintBackground(e.ClipBounds, false);
          e.Handled = true;
        }
        else if (e.ColumnIndex == uDataGridView1.Columns.Count - 3)
        {
          using (Brush foreColor = new SolidBrush(e.CellStyle.ForeColor))
          {
            e.PaintBackground(e.ClipBounds, false);
            StringFormat drawFormat = new StringFormat();
            drawFormat.LineAlignment = StringAlignment.Center;
            drawFormat.Alignment = System.Drawing.StringAlignment.Near;

            e.Graphics.DrawString(diff.ToString("#0.##"), e.CellStyle.Font, foreColor, e.CellBounds, drawFormat);
            e.Handled = true;
          }
        }
        else if (e.ColumnIndex == 3)
        {
          using (Brush foreColor = new SolidBrush(e.CellStyle.ForeColor))
          {
            e.PaintBackground(e.ClipBounds, false);
            StringFormat drawFormat = new StringFormat();
            drawFormat.LineAlignment = StringAlignment.Center;
            drawFormat.Alignment = System.Drawing.StringAlignment.Center;

            e.Graphics.DrawString("合计", e.CellStyle.Font, foreColor, e.CellBounds, drawFormat);
            e.Handled = true;
          }
        }
      }
    }

    void uDataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {
      if (e.RowIndex == uDataGridView1.Rows.Count - 1)
      {
        var row = uDataGridView1.Rows[e.RowIndex];
        row.DefaultCellStyle.SelectionForeColor = Color.Black;
        row.DefaultCellStyle.BackColor = Color.Khaki;
        row.DefaultCellStyle.SelectionBackColor = Color.Khaki;
      }
    }

    decimal diff = 0;
    void BindGrid()
    {
      list = CarcassSaleOutBL.GetWeightRecord(mDetail.ID);
      var total = new CarcassSaleOut_Detail();
      total.Number = list.Sum(x => x.Number);
      total.Weight = list.Sum(x => x.Weight);
      total.InStoreWeight = list.Sum(x => x.InStoreWeight ?? 0);
      diff = list.Sum(x => x.DiffWeight ?? 0);
      list.Add(total);
      uDataGridView1.DataSource = list;
      ReBuildTotalRow(diff);
      uDataGridView1.Refresh();
    }

    private void ReBuildTotalRow(decimal diff)
    {
      var row = uDataGridView1.Rows[list.Count - 1];
      row.Cells["R_Time"].Value = null;
    }

    private void addBtn_Click(object sender, EventArgs e)
    {
      if (new AddWeightRecord(mDetail, mBatchID, mProductTime).ShowDialog() == DialogResult.OK)
      {
        BindGrid();
        Changed = true;
      }
    }

    private void deleteBtn_Click(object sender, EventArgs e)
    {
      if (uDataGridView1.CurrentRow == null)
        return;
      var id = (long)uDataGridView1.CurrentRow.Cells[0].Value;
      if (id == 0)
        return;
      if (MessageBox.Show("确定删除该明细？", "删除确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
        return;
      var tag = list.First(x => x.ID == id);
      CarcassSaleOutBL.DeleteAndUpdate(tag);
      BindGrid();
      Changed = true;
    }

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

    private void uDataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
      if (e.RowIndex < 0 || e.RowIndex == list.Count - 1 || e.ColumnIndex != 2)
        return;
      var v = (bool)uDataGridView1.Rows[e.RowIndex].Cells[1].Value;
      e.Value = v ? CheckImg : UnCheckImg;
    }

    private void uDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex == -1 && e.ColumnIndex == 2)
      {
        foreach (var item in list)
          item.Selected = !item.Selected;
        uDataGridView1.Refresh();
        return;
      }
      if (e.RowIndex < 0 || e.RowIndex == list.Count - 1)
        return;
      var id = (long)uDataGridView1.CurrentRow.Cells[0].Value;
      var first = list.First(x => x.ID == id);
      first.Selected = !first.Selected;
      uDataGridView1.Refresh();
    }

    private void rollBackBtn_Click(object sender, EventArgs e)
    {
      var backList = list.Where(x => x.Selected).ToList();
      if (backList.Count() == 0)
        throw new Exception("没有称重记录");
      if (MessageBox.Show("确定退回选中记录？", "请确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
        return;
      CarcassSaleOutBL.RollBackDetails(backList);
      BindGrid();
      Changed = true;
      rolBack = true;
    }

    private void deleteLogBtn_Click(object sender, EventArgs e)
    {
      new WeightDeleteRecord(mDetail.ID).ShowDialog();
    }
  }
}
