using BO.BO;
using BO.Utils;
using BO.Utils.BillRpc;
using BWP.WinFormControl;
using BwpClientPrint.DocumentRenders;
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;

namespace ButcherWeight
{
  public partial class WeightForm : Form, IAfterLogin
  {
    #region IAfterLogin Member
    public string RoleName
    {
      get { return "过磅员"; }
    }

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

    private delegate void InvokeHandler();
    bool mainIsRun = false;

    private List<WeightBillList> dmoList;
    private WeightBill Dmo = new WeightBill();
    private List<WeightBill_FarmerDetail> _farmerDetails = new List<WeightBill_FarmerDetail>();
    private List<WeightBill_Detail> _details = new List<WeightBill_Detail>();
    private List<WeightBill_FarmerDetail> _fDelete = new List<WeightBill_FarmerDetail>();
    private List<WeightDetail> weightRecord = new List<WeightDetail>();

    public WeightForm()
    {
      InitializeComponent();
      supplierSelect.Init("BaseInfoRpc/GetSupplierList");
      purchaseTypeSelect.Init("BaseInfoRpc/GetPurchaseTypeList");
      carSelect.Init("BaseInfoRpc/GetCarList");
      liveVarietiesSelect.Init("BaseInfoRpc/GetLiveVarietiesList");
      employeeSelect.Init("BaseInfoRpc/GetEmployeeList");
      hogGradeSelect.Init("BaseInfoRpc/GetHogGradeList");
      zoneSelect.Init("BaseInfoRpc/GetZoneList");
      farmerSelect.Init("BaseInfoRpc/GetFarmerList");

      qCarSelect.Init("BaseInfoRpc/GetCarList");
      qSupplierSelect.Init("BaseInfoRpc/GetSupplierList");
      farmerSelect.EnableTopItem = false;
      weightTimeSelect.Date = DateTime.Now;
      testTimeInput.Date = null;
      dmoList = WeightBillRpc.GetWeightBillList(null, null);
      billGrid.AutoGenerateColumns = false;
      farmerGrid.AutoGenerateColumns = false;
      weightGrid.AutoGenerateColumns = false;
      houseGird.AutoGenerateColumns = false;
      abnormalGrid.AutoGenerateColumns = false;
      mainIsRun = true;
      var syncThread = new Thread(SyncTask);
      syncThread.Start();
      this.FormClosing += delegate
      {
        if (syncThread.IsAlive)
          syncThread.Abort();
        if (_inQueryThread != null && _inQueryThread.IsAlive)
          DisableWeight();
      };
    }

    private void WeightForm_Load(object sender, EventArgs e)
    {
      BindWeightBill();
    }

    private void SyncTask()
    {
      while (mainIsRun)
      {
        Thread.Sleep(5000);
        bool changed = false;
        var result = WeightBillRpc.SyncBillB3IdsAndSanctionMoney();
        foreach (var item in result)
        {
          var first = dmoList.FirstOrDefault(x => x.ID == item.Item1);
          if (first != null)
          {
            first.B3ID = item.Item2;
            first.SanctionMoney = item.Item3;
            first.HouseNames = item.Item4;
            if (!changed)
              changed = true;
          }
        }
        if (changed)
        {
          this.Invoke(new InvokeHandler(delegate()
          {
            billGrid.Refresh();
          }));
        }
      }
    }

    void BindWeightBill()
    {
      billGrid.DataSource = dmoList.OrderByDescending(x => x.ID).OrderBy(x => x.FinishWeight).ToList();
      foreach (DataGridViewRow row in billGrid.Rows)
      {
        if ((bool)row.Cells["M_FinishWeight"].Value)
          row.DefaultCellStyle.BackColor = Color.YellowGreen;
        if ((int)row.Cells["M_PrintNumber"].Value > 0)
          row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#CC9999");
      }
      billGrid.Refresh();
    }

    private void exitBtn_Click(object sender, EventArgs e)
    {
      if (enableCheckBox.Checked)
        enableCheckBox.Checked = false;
      this.Close();
    }

    private void commitBtn_Click(object sender, EventArgs e)
    {
      if (!_details.Any())
        throw new Exception("没有称重记录");
      //if (!_farmerDetails.Any())
      //throw new Exception("没有养殖户信息");
      GetFromUI();
      Dmo.Details.Clear();
      Dmo.Details.AddRange(_details.ToList());

      Dmo.FarmerDetails.Clear();
      Dmo.FarmerDetails.AddRange(_farmerDetails.ToList());
      Dmo.FarmerDetails.AddRange(_fDelete.ToList());

      var send = weightRecord.Where(x => x.Delete || x.ID == 0).ToList();
      var result = WeightBillRpc.UpdateOrInsert(Dmo, send);
      weightRecord.Clear();
      UpdateOrInsertList();
      BindWeightBill();
      if (result)
        MessageBox.Show("保存成功！");
      AppToUI();
    }

    void UpdateOrInsertList()
    {
      var entity = dmoList.FirstOrDefault(x => x.ID == Dmo.ID);
      if (entity == null)
      {
        entity = new WeightBillList();
        entity.ID = Dmo.ID;
        entity.B3ID = Dmo.B3ID;
        dmoList.Add(entity);
      }
      entity.Car_Name = Dmo.Car_Name;
      entity.Supplier_Name = Dmo.Supplier_Name;
      entity.Employee_Name = Dmo.Employee_Name;
      entity.PurchaseType_Name = Dmo.PurchaseType_Name;
      var detail = Dmo.Details.First();
      entity.Number = detail.Number;
      entity.Weight = detail.Weight;
      entity.Remark = Dmo.Remark;
      entity.FinishWeight = detail.MaoWeight.HasValue && detail.PiWeight.HasValue;
    }

    private void createBtn_Click(object sender, EventArgs e)
    {
      Dmo = new WeightBill();
      Dmo.WeighTime = DateTime.Now;
      AppToUI();
    }

    private void readMaoBtn_Click(object sender, EventArgs e)
    {
      var d = new WeightBill_Detail();
      if (weightGrid.CurrentRow == null)
      {
        _details.Add(d);
        d.Index = _details.Max(x => x.Index) + 1;
        d.WeightBill_ID = Dmo.ID;
      }
      else
        d = weightGrid.CurrentRow.DataBoundItem as WeightBill_Detail;
      d.MaoWeight = (d.MaoWeight ?? 0) + (WeightValue ?? 0);
      d.Weight = (d.MaoWeight ?? 0) - (d.PiWeight ?? 0);


      var record = new WeightDetail();
      record.Time = DateTime.Now;
      record.Type = "毛重";
      record.Weight = WeightValue ?? 0;
      record.WeightBill_Detail_ID = d.ID;
      weightRecord.Add(record);

      weightGrid.DataSource = _details;
      weightGrid.Refresh();
      WeightValue = 0;
    }

    private void readPiBtn_Click(object sender, EventArgs e)
    {
      if (weightGrid.SelectedRows.Count == 0)
      {
        MessageBox.Show("请选中过磅记录");
        return;
      }
      var target = weightGrid.CurrentRow.DataBoundItem as WeightBill_Detail;
      target.PiWeight = (target.PiWeight ?? 0) + (WeightValue ?? 0);
      target.Weight = target.MaoWeight - target.PiWeight;
      var record = new WeightDetail();
      record.Time = DateTime.Now;
      record.Type = "皮重";
      record.Weight = WeightValue ?? 0;
      record.WeightBill_Detail_ID = target.ID;
      weightRecord.Add(record);
      weightGrid.Refresh();
      WeightValue = 0;
    }

    private void farmerSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (farmerSelect.IsEmpty)
        return;
      var detail = new WeightBill_FarmerDetail();
      detail.Farmer_ID = farmerSelect.LongValue.Value;
      if (_farmerDetails.Any(x => x.Farmer_ID == detail.Farmer_ID))
        return;
      detail.Farmer_Name = farmerSelect.DisplayValue;
      _farmerDetails.Add(detail);
      detail.Index = _farmerDetails.Max(x => x.Index) + 1;
      detail.WeightBill_ID = Dmo.ID;
      farmerGrid.DataSource = null;
      farmerGrid.DataSource = _farmerDetails;
      farmerGrid.Refresh();
      farmerSelect.Clear();
    }

    void GetFromUI()
    {
      Dmo.Employee_ID = employeeSelect.LongValue;
      Dmo.Employee_Name = employeeSelect.DisplayValue;
      Dmo.WeighTime = weightTimeSelect.Date;
      Dmo.Supplier_ID = supplierSelect.LongValue;
      Dmo.Supplier_Name = supplierSelect.DisplayValue;
      Dmo.Zone_ID = zoneSelect.LongValue;
      Dmo.Zone_Name = zoneSelect.DisplayValue;
      Dmo.PurchaseType_ID = null;
      if (!purchaseTypeSelect.IsEmpty)
        Dmo.PurchaseType_ID = short.Parse(purchaseTypeSelect.Value);
      Dmo.PurchaseType_Name = purchaseTypeSelect.DisplayValue;
      Dmo.Car_ID = carSelect.LongValue;
      Dmo.Car_Name = carSelect.DisplayValue;
      Dmo.LiveVarieties_ID = liveVarietiesSelect.LongValue;
      Dmo.LiveVarieties_Name = liveVarietiesSelect.DisplayValue;
      Dmo.HogGrade_ID = hogGradeSelect.LongValue;
      Dmo.HogGrade_Name = hogGradeSelect.DisplayValue;
      if (!string.IsNullOrEmpty(penWeightInput.Text))
      {
        decimal pw = 0;
        if (!decimal.TryParse(penWeightInput.Text.Trim(), out pw))
          throw new Exception("棚前重量输入错误");
        Dmo.ShackWeight = pw;
      }
      else
        Dmo.ShackWeight = null;
      if (!string.IsNullOrEmpty(penPriceInput.Text))
      {
        decimal pp = 0;
        if (!decimal.TryParse(penPriceInput.Text.Trim(), out pp))
          throw new Exception("棚前单价输入错误");
        Dmo.ShackPrice = pp;
      }
      else
        Dmo.ShackPrice = null;
      if (!string.IsNullOrEmpty(jingjianInput.Text))
      {
        decimal jjf = 0;
        if (!decimal.TryParse(jingjianInput.Text.Trim(), out jjf))
          throw new Exception("经检费输入错误");
        Dmo.JingJianFee = jjf;
      }
      else
        Dmo.JingJianFee = null;
      if (!string.IsNullOrEmpty(discontInput.Text))
      {
        decimal dicont = 0;
        if (!decimal.TryParse(discontInput.Text.Trim(), out dicont))
          throw new Exception("猪场扣款输入错误");
        Dmo.DiscontMoney = dicont;
      }
      else
        Dmo.DiscontMoney = null;
      Dmo.AnimalTestNumber = testCardNumberInput.Text;
      Dmo.AnimalTestDate = testTimeInput.Date;
      Dmo.AnimalTestMan = testManInput.Text;
      Dmo.Remark = remarkInput.Text;

      foreach (DataGridViewRow data in farmerGrid.Rows)
      {
        var detail = data.DataBoundItem as WeightBill_FarmerDetail;
        var first = _farmerDetails.First(x => x.Index == detail.Index);
        first.Number = detail.Number;
        first.Weight = detail.Weight;
      }

      foreach (DataGridViewRow data in weightGrid.Rows)
      {
        var detail = data.DataBoundItem as WeightBill_Detail;
        var first = _details.First(x => x.Index == detail.Index);
        first.Number = detail.Number;
        first.MaoWeight = detail.MaoWeight;
        first.PiWeight = detail.PiWeight;
        first.Weight = (detail.MaoWeight ?? 0) - (detail.PiWeight ?? 0);
      }
    }

    void AppToUI()
    {
      ResetControl();
      if (Dmo.Employee_ID.HasValue)
        employeeSelect.Fill(Dmo.Employee_Name, Dmo.Employee_ID.ToString());

      if (Dmo.WeighTime.HasValue)
        weightTimeSelect.Date = Dmo.WeighTime;

      if (Dmo.Supplier_ID.HasValue)
        supplierSelect.Fill(Dmo.Supplier_Name, Dmo.Supplier_ID.ToString());

      if (Dmo.Zone_ID.HasValue)
        zoneSelect.Fill(Dmo.Zone_Name, Dmo.Zone_ID.ToString());

      if (Dmo.PurchaseType_ID.HasValue)
        purchaseTypeSelect.Fill(Dmo.PurchaseType_Name, Dmo.PurchaseType_ID.ToString());

      if (Dmo.Car_ID.HasValue)
        carSelect.Fill(Dmo.Car_Name, Dmo.Car_ID.ToString());

      if (Dmo.LiveVarieties_ID.HasValue)
        liveVarietiesSelect.Fill(Dmo.LiveVarieties_Name, Dmo.LiveVarieties_ID.ToString());

      if (Dmo.HogGrade_ID.HasValue)
        hogGradeSelect.Fill(Dmo.HogGrade_Name, Dmo.HogGrade_ID.ToString());

      if (Dmo.ShackWeight.HasValue)
        penWeightInput.Text = Dmo.ShackWeight.Value.ToString("#0.######");

      if (Dmo.ShackPrice.HasValue)
        penPriceInput.Text = Dmo.ShackPrice.Value.ToString("#0.######");

      if (Dmo.ShackMoney.HasValue)
        penMoneyInput.Text = Dmo.ShackMoney.Value.ToString("#0.######");

      if (Dmo.JingJianFee.HasValue)
        jingjianInput.Text = Dmo.JingJianFee.Value.ToString("#0.######");

      if (Dmo.DiscontMoney.HasValue)
        discontInput.Text = Dmo.DiscontMoney.Value.ToString("#0.######");

      if (!string.IsNullOrEmpty(Dmo.AnimalTestNumber))
        testCardNumberInput.Text = Dmo.AnimalTestNumber;

      if (Dmo.AnimalTestDate.HasValue)
        testTimeInput.Date = Dmo.AnimalTestDate.Value;

      if (!string.IsNullOrEmpty(Dmo.AnimalTestMan))
        testManInput.Text = Dmo.AnimalTestMan;

      if (!string.IsNullOrEmpty(Dmo.Remark))
        remarkInput.Text = Dmo.Remark;

      _farmerDetails = Dmo.FarmerDetails.Where(x => !x.DeleteState).ToList();
      _details = Dmo.Details.ToList();
      _fDelete.Clear();
      weightRecord.Clear();

      if (_farmerDetails.Any())
        farmerGrid.DataSource = _farmerDetails;
      if (_details.Any())
        weightGrid.DataSource = _details;
    }

    void ResetControl()
    {
      employeeSelect.Clear();
      weightTimeSelect.Date = null;
      supplierSelect.Clear();
      zoneSelect.Clear();
      purchaseTypeSelect.Clear();
      carSelect.Clear();
      liveVarietiesSelect.Clear();
      hogGradeSelect.Clear();
      penWeightInput.Text = null;
      penPriceInput.Text = null;
      penMoneyInput.Text = null;
      jingjianInput.Text = null;
      discontInput.Text = null;
      testCardNumberInput.Text = null;
      testTimeInput.Date = null;
      testManInput.Text = null;
      remarkInput.Text = null;
      farmerGrid.DataSource = null;
      weightGrid.DataSource = null;
    }

    private void billGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex < 0)
        return;

      var id = Convert.ToInt64(billGrid.CurrentRow.Cells["M_ID"].Value);
      Dmo = WeightBillRpc.Load(id);
      AppToUI();
    }

    private void weightSet_Click(object sender, EventArgs e)
    {
      new WeightConfig().ShowDialog();
    }

    private void deleteBtn_Click(object sender, EventArgs e)
    {
      if (Dmo.ID == 0)
        throw new Exception("无效的单据");
      WeightBillRpc.Delete(Dmo.ID);
      if (dmoList.Any(x => x.ID == Dmo.ID))
      {
        var idx = dmoList.FindIndex(x => x.ID == Dmo.ID);
        dmoList.RemoveAt(idx);
        BindWeightBill();
      }
      createBtn_Click(sender, e);
      MessageBox.Show("删除成功！");
    }

    private void queryBtn_Click(object sender, EventArgs e)
    {
      dmoList = WeightBillRpc.GetWeightBillList(qCarSelect.LongValue, qSupplierSelect.LongValue);
      BindWeightBill();
    }

    private void farmerGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
      if (e.Button == MouseButtons.Right)
      {
        if (e.RowIndex >= 0)
        {
          //若行已是选中状态就不再进行设置
          if (farmerGrid.Rows[e.RowIndex].Selected == false)
          {
            farmerGrid.ClearSelection();
            farmerGrid.Rows[e.RowIndex].Selected = true;
          }
          ////只选中一行时设置活动单元格
          //if (weightGrid.SelectedRows.Count == 1)
          //{
          //  weightGrid.CurrentCell = weightGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
          //}
          //弹出操作菜单
          farmerMenu.Show(MousePosition.X, MousePosition.Y);
        }
      }
    }

    private void farmerDelete_Click(object sender, EventArgs e)
    {
      var d = farmerGrid.CurrentRow.DataBoundItem as WeightBill_FarmerDetail;
      _farmerDetails.Remove(d);
      for (var i = 0; i < _farmerDetails.Count; i++)
        _farmerDetails[i].Index = i + 1;
      if (d.ID != 0)
      {
        d.DeleteState = true;
        _fDelete.Add(d);
      }
      farmerGrid.DataSource = null;
      if (_farmerDetails.Any())
        farmerGrid.DataSource = _farmerDetails;
      farmerGrid.Refresh();
    }

    private void viewDetailBtn_Click(object sender, EventArgs e)
    {
      if (_details.Count == 0)
      {
        MessageBox.Show("没有过磅记录");
        return;
      }
      var first = _details.First();
      if (first.ID != 0)
      {
        var exist = WeightBillRpc.GetWeightRecord(first.ID).OrderByDescending(x => x.ID);
        foreach (var item in exist)
        {
          if (!weightRecord.Any(x => x.ID == item.ID))
            weightRecord.Insert(0, item);
        }
      }
      if (new RecordView(weightRecord).ShowDialog() == DialogResult.OK)
      {
        first.MaoWeight = weightRecord.Where(x => x.Type == "毛重" && !x.Delete).Sum(x => x.Weight);
        first.PiWeight = weightRecord.Where(x => x.Type == "皮重" && !x.Delete).Sum(x => x.Weight);
        first.Weight = first.MaoWeight - first.PiWeight;
        weightGrid.Refresh();
      }
    }

    private void penWeightPriceInput_TextChanged(object sender, EventArgs e)
    {
      decimal w = 0;
      decimal price = 0;
      if (decimal.TryParse(penWeightInput.Text, out w) && decimal.TryParse(penPriceInput.Text, out price))
        penMoneyInput.Text = (w * price).ToString("#0.######");
      else
        penMoneyInput.Text = "0";
    }

    private void printBtn_Click(object sender, EventArgs e)
    {
      if (Dmo.ID == 0)
        throw new Exception("请先保存");
      var entity = WeightBillRpc.GetPrintWeightBill(Dmo.ID);
      if (string.IsNullOrEmpty(entity.Supplier_Name))
        throw new Exception("缺少供应商信息，打印失败");
      ClientPrint.BwpClientPrint print = new ClientPrint.BwpClientPrint("WeightBillPrint.xaml", entity, new DocumentRenderer());
      print.PrintDirect();
      WeightBillRpc.DoCheck(Dmo.ID);
      var first = dmoList.FirstOrDefault(x => x.ID == Dmo.ID);
      if (first != null)
      {
        first.PrintNumber += 1;
        foreach (DataGridViewRow row in billGrid.Rows)
        {
          if ((long)row.Cells["M_ID"].Value == Dmo.ID)
          {
            row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#CC9999");
            break;
          }
        }
        billGrid.Refresh();
      }
    }
  }
}