using ButcherFactory.BO.Utils;
using Forks.EnterpriseServices.DomainObjects2;
using Forks.EnterpriseServices.DomainObjects2.DQuery;
using Forks.JsonRpc.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ButcherFactory.BO.LocalBL
{
  public static class SegmentSaleOutBL
  {
    const string RpcPath = @"/MainSystem/B3Sale/Rpcs/";
    const string MESPath = @"/MainSystem/B3ClientService/Rpcs/";
    public static BindingList<SaleOutStore> GetSaleOutStoreList(DateTime sendDate, long? deliverGoodsLineID, long? customerID, int billState, long? storeID, bool already = false)
    {
      return CarcassSaleOutBL.GetSaleOutStoreList(sendDate, deliverGoodsLineID, customerID, billState, storeID, already);
    }

    public static BindingList<SaleOutStore_Detail> GetSaleOutStoreDetailList(long id)
    {
      return CarcassSaleOutBL.GetSaleOutStoreDetailList(id);
    }

    public static bool HasNoAssignDetail(long billID)
    {
      return CarcassSaleOutBL.HasNoAssignDetail(billID);
    }

    public static BindingList<SegmentSaleOut_Detail> GetWeightRecord(long detailID)
    {
      var query = new DmoQuery(typeof(SegmentSaleOut_Detail));
      query.Where.Conditions.Add(DQCondition.EQ("DetailID", detailID));
      query.OrderBy.Expressions.Add(DQOrderByExpression.Create("ID", true));
      var list = query.EExecuteList().Cast<SegmentSaleOut_Detail>().ToList();
      var idx = list.Count;
      foreach (var item in list)
      {
        item.Idx = idx;
        idx--;
      }
      return new BindingList<SegmentSaleOut_Detail>(list);
    }

    public static SegmentSaleOut_Detail Insert(decimal weight)
    {
      using (var session = DmoSession.New())
      {
        var detail = new SegmentSaleOut_Detail() { Number = weight, SecondNumber = 1 };
        session.Insert(detail);
        session.Commit();
        return detail;
      }
    }

    public static List<ProductBatch> GetBatchFromEMS()
    {
      return CarcassSaleOutBL.GetBatchFromEMS(1);
    }

    static void SubmitDetails(IDmoSession session, IEnumerable<SegmentSaleOut_Detail> details, SaleOutStore_Detail detail, int flag)
    {
      var arr = details.Select(x => new WeightRecord { Flag = flag, ID = x.ID, WeightTime = x.Time, MainUnitNum = x.Number, SecondNumber = x.SecondNumber, ProductBatch_ID = x.ProductBatch_ID, BarCode = x.BarCode });
      var json = RpcFacade.Call<string>(RpcPath + "SaleOutStoreRpc/SaveWeightRecord", JsonConvert.SerializeObject(arr), detail.ID);
      var back = JsonConvert.DeserializeObject<Tuple<decimal?, decimal?, List<ExtensionObj>>>(json);
      foreach (var item in details)
      {
        var first = back.Item3.First(x => x.LongExt1 == item.ID);

        Update(session, item.ID,
          new Tuple<string, object>("WeightRecord_ID", first.LongExt2),
          new Tuple<string, object>("ScanRecord_ID", first.LongExt3)
          );
        item.WeightRecord_ID = first.LongExt2;
        item.ScanRecord_ID = first.LongExt3;
      }
    }

    static void Update(IDmoSession session, long id, params Tuple<string, object>[] pops)
    {
      var update = new DQUpdateDom(typeof(SegmentSaleOut_Detail));
      foreach (var item in pops)
        update.Columns.Add(new DQUpdateColumn(item.Item1, item.Item2));
      update.Where.Conditions.Add(DQCondition.EQ("ID", id));
      session.ExecuteNonQuery(update);
    }

    public static void SetGoodsFinish(long id)
    {
      CarcassSaleOutBL.SetGoodsFinish(id);
    }

    public static void SetGoodsUnFinish(long id)
    {
      CarcassSaleOutBL.SetGoodsUnFinish(id);
    }

    static void Delete(long id)
    {
      var delete = new DQDeleteDom(typeof(SegmentSaleOut_Detail));
      delete.Where.Conditions.Add(DQCondition.EQ("ID", id));
      delete.EExecute();
    }

    public static void AddAndUpdate(SegmentSaleOut_Detail detail)
    {
      using (var session = DmoSession.New())
      {
        session.Insert(detail);
        var arr = new List<WeightRecord> { new WeightRecord { Flag = 2, ID = detail.ID, WeightTime = detail.Time, MainUnitNum = detail.Number, SecondNumber = detail.SecondNumber } };
        var json = RpcFacade.Call<string>(RpcPath + "SaleOutStoreRpc/SaveWeightRecord", JsonConvert.SerializeObject(arr), detail.DetailID);
        var back = JsonConvert.DeserializeObject<Tuple<decimal?, decimal?, List<ExtensionObj>>>(json);

        var first = back.Item3.First();

        Update(session, detail.ID, new Tuple<string, object>("WeightRecord_ID", first.LongExt2),
          new Tuple<string, object>("ScanRecord_ID", first.LongExt3)
          );

        session.Commit();
      }
    }

    public static void DeleteAndUpdate(SegmentSaleOut_Detail tag)
    {
      var json = JsonConvert.SerializeObject(new List<ExtensionObj>() { new ExtensionObj { LongExt1 = tag.DetailID, LongExt2 = tag.WeightRecord_ID, LongExt3 = tag.ScanRecord_ID } });
      RpcFacade.Call<int>(RpcPath + "SaleOutStoreRpc/DeleteAndUpdate", json);
      Delete(tag.ID);
    }

    public static void InsertByCode(SaleOutStore_Detail orderDetail, SegmentSaleOut_Detail detail)
    {
      var json = ButcherFactoryUtil.SecondUrlCall<string>(MESPath + "SegmentSaleOutStoreRpc/GetSegmentInfo", detail.BarCode);
      var scanInfo = JsonConvert.DeserializeObject<ExtensionObj>(json);
      if (scanInfo.StringExt1 != orderDetail.Goods_Code)
        throw new Exception("扫码明细与发货明细 存货不一致！");
      detail.BillID = orderDetail.SaleOutStore_ID;
      detail.DetailID = orderDetail.ID;
      detail.Goods_ID = orderDetail.Goods_ID;
      detail.Goods_Code = orderDetail.Goods_Code;
      detail.Goods_Name = orderDetail.Goods_Name;
      detail.Number = scanInfo.DecimalExt1.Value;
      if (orderDetail.Number.HasValue && orderDetail.SecondNumber.HasValue && orderDetail.Number != 0)
        detail.SecondNumber = decimal.Round(orderDetail.SecondNumber.Value * detail.Number / orderDetail.Number.Value, 2);
      detail.Operator = "扫码发货";
      using (var session = DmoSession.New())
      {
        session.Insert(detail);

        SubmitDetails(session, new SegmentSaleOut_Detail[] { detail }, orderDetail, 1);
        session.Commit();
      }
    }

    public static void InsertReadWeight(SaleOutStore_Detail orderDetail, SegmentSaleOut_Detail detail)
    {
      detail.BillID = orderDetail.SaleOutStore_ID;
      detail.DetailID = orderDetail.ID;
      detail.Goods_ID = orderDetail.Goods_ID;
      detail.Goods_Code = orderDetail.Goods_Code;
      detail.Goods_Name = orderDetail.Goods_Name;
      if (orderDetail.Number.HasValue && orderDetail.SecondNumber.HasValue && orderDetail.Number != 0)
        detail.SecondNumber = decimal.Round(orderDetail.SecondNumber.Value * detail.Number / orderDetail.Number.Value, 2);
      detail.Operator = "读入重量";
      using (var session = DmoSession.New())
      {
        session.Insert(detail);
        SubmitDetails(session, new SegmentSaleOut_Detail[] { detail }, orderDetail, 2);
        session.Commit();
      }
    }

    public static bool BarCodeUsed(string barCode)
    {
      var query = new DQueryDom(new JoinAlias(typeof(SegmentSaleOut_Detail)));
      query.Where.Conditions.Add(DQCondition.EQ("BarCode", barCode));
      query.Columns.Add(DQSelectColumn.Create(DQExpression.Value(1), "c"));
      return query.EExecuteScalar() != null;
    }

    public static List<SegmentSaleOut_Detail> InsertByStockUp(string barCode, IEnumerable<SaleOutStore_Detail> orderDetails)
    {
      var id = orderDetails.First().SaleOutStore_ID;
      var json = RpcFacade.Call<string>(RpcPath + "SaleOutStoreRpc/GetCustomerStockUp", barCode, id);
      if (string.IsNullOrEmpty(json))
        throw new Exception("无备货信息或条码跟客户不匹配");
      var list = JsonConvert.DeserializeObject<List<SegmentSaleOut_Detail>>(json);
      //detail.BillID = orderDetail.SaleOutStore_ID;
      //detail.DetailID = orderDetail.ID;
      //detail.Goods_ID = orderDetail.Goods_ID;
      //detail.Goods_Code = orderDetail.Goods_Code;
      //detail.Goods_Name = orderDetail.Goods_Name;
      //detail.Number = scanInfo.DecimalExt1.Value;
      //if (orderDetail.Number.HasValue && orderDetail.SecondNumber.HasValue && orderDetail.Number != 0)
      //  detail.SecondNumber = decimal.Round(orderDetail.SecondNumber.Value * detail.Number / orderDetail.Number.Value, 2);
      //detail.Operator = "扫码发货";
      using (var session = DmoSession.New())
      {
        if (list.Any())
        {
          var existCodes = GetExistCodes(session, list.Select(x => x.BarCode));
          foreach (var item in existCodes)
            list.Remove(list.First(x => x.BarCode == item));
        }
        foreach (var item in list)
        {
          item.BillID = id;
          item.Operator = "按备货发货";
          session.Insert(item);
        }
        foreach (var g in list.GroupBy(x => x.DetailID))
        {
          var first = orderDetails.FirstOrDefault(x => x.ID == g.Key);
          if (first == null)
            throw new Exception(string.Format("备货与出库单不符,出库单缺少存货{0}", g.First().Goods_Name));
          SubmitDetails(session, g, first, 1);
        }
        session.Commit();
      }
      return list;
    }

    private static List<string> GetExistCodes(IDmoSession session, IEnumerable<string> codes)
    {
      var query = new DQueryDom(new JoinAlias(typeof(SegmentSaleOut_Detail)));
      query.Columns.Add(DQSelectColumn.Field("BarCode"));
      query.Where.Conditions.Add(DQCondition.InList(DQExpression.Field("BarCode"), codes.Select(x => DQExpression.Value(x)).ToArray()));
      return query.EExecuteList<string>(session);
    }
  }
}
