using BO.BO.BaseInfo;
using BO.BO.Bill;
using Forks.EnterpriseServices.DomainObjects2;
using Forks.EnterpriseServices.DomainObjects2.DQuery;
using Forks.EnterpriseServices.SqlDoms;
using Forks.JsonRpc.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using TSingSoft.WebPluginFramework;

namespace BO.Utils.BillRpc
{
  public static class GradeAndWeightRpc
  {
    static JavaScriptSerializer serializer = new JavaScriptSerializer();

    public static List<GradeAndWeight> GetGradeAndWeightList(DateTime date, bool isTang)
    {
      const string method = "/MainSystem/B3ClientService/Rpcs/BillRpc/GradeAndWeightRpc/GetGradeAndWeightList";
      var result = RpcFacade.Call<string>(method, date, isTang);
      return serializer.Deserialize<List<GradeAndWeight>>(result);
    }

    public static void SetGradeFinish(long orderDetailID, short technics)
    {
      const string method = "/MainSystem/B3ClientService/Rpcs/BillRpc/GradeAndWeightRpc/SetGradeFinish";
      RpcFacade.Call<int>(method, orderDetailID, technics);
    }

    public static List<BodyDiscontItem> GetBodyDiscontItem()
    {
      const string method = "/MainSystem/B3ClientService/Rpcs/BillRpc/GradeAndWeightRpc/GetBodyDiscontItemSetting";
      var json = RpcFacade.Call<string>(method);
      return serializer.Deserialize<List<BodyDiscontItem>>(json);
    }

    public static void SaveBodyDiscontItem(List<CTuple<long, decimal?>> list)
    {
      const string method = "/MainSystem/B3ClientService/Rpcs/BillRpc/GradeAndWeightRpc/SaveBodyDiscontItemSetting";
      RpcFacade.Call<int>(method, serializer.Serialize(list));
    }
  }

  public static class LocalGradeAndWeightBL
  {
    static JavaScriptSerializer serializer = new JavaScriptSerializer();

    class DmoSession
    {
      public static IDmoSessionWithTransaction New()
      {
        return Dmo.NewSession(ButcherAppContext.Context.UrlConfig.OfflineSqlConnection);
      }
    }

    public static bool ConnectionTest()
    {
      using (var session = DmoSession.New())
      {
        try
        {
          var q = new DQueryDom(new JoinAlias(typeof(GradeAndWeight_Detail)));
          q.Columns.Add(DQSelectColumn.Create(DQExpression.Value(1), "c"));
          q.Range = SelectRange.Top(1);
          session.ExecuteScalar(q);
          return true;
        }
        catch
        { return false; }
      }
    }

    public static List<GradeAndWeight_Detail> GetDetails(DateTime date, int top = 15)
    {
      var query = new DmoQuery(typeof(GradeAndWeight_Detail));
      query.Where.Conditions.Add(DQCondition.EQ("Date", date));
      query.OrderBy.Expressions.Add(DQOrderByExpression.Create("Index", true));
      query.Range = SelectRange.Top(top);
      using (var session = DmoSession.New())
      {
        return session.ExecuteList(query).Cast<GradeAndWeight_Detail>().ToList();
      }
    }

    public static void Insert(GradeAndWeight_Detail detail)
    {
      using (var session = DmoSession.New())
      {
        if (detail.SID != 0)
          throw new Exception("Insert时要保证SID不为0");
        session.Insert(detail);
        session.Commit();
      }
    }

    public static void Update(GradeAndWeight_Detail detail, params string[] properties)
    {
      var type = typeof(GradeAndWeight_Detail);
      using (var session = DmoSession.New())
      {
        if (detail.SID == 0)
          throw new Exception("Update时要保证SID不能为0");
        if (properties.Contains("ID"))
          throw new Exception("ID不能通过该方法维护");
        if (properties.Length == 0)
          throw new Exception("Update时要给出属性数组");
        var update = new DQUpdateDom(type);
        update.Where.Conditions.Add(DQCondition.EQ("SID", detail.SID));
        foreach (var p in properties)
        {
          if (p == "Sync" && detail.Sync)
            detail.Sync = false;
          update.Columns.Add(new DQUpdateColumn(p, type.GetProperty(p).GetValue(detail)));
        }
        session.ExecuteNonQuery(update);
        session.Commit();
      }
    }

    public static void Sync()
    {
      var syncs = GetAllNeedSyncDetails();
      foreach (var detail in syncs)
      {
        const string method = "/MainSystem/B3ClientService/Rpcs/BillRpc/GradeAndWeightRpc/UpdateOrInsertDetail";
        var id = RpcFacade.Call<long>(method, serializer.Serialize(detail));

        SetDetailSynced(detail, id);
      }
    }

    static IEnumerable<GradeAndWeight_Detail> GetAllNeedSyncDetails()
    {
      using (var session = DmoSession.New())
      {
        var query = new DmoQuery(typeof(GradeAndWeight_Detail));
        query.OrderBy.Expressions.Add(DQOrderByExpression.Create("SID"));
        query.Range = SelectRange.Top(50);
        query.Where.Conditions.Add(DQCondition.And(DQCondition.EQ("Sync", false), DQCondition.IsNotNull(DQExpression.Field("Technics"))));
        return session.ExecuteList(query).Cast<GradeAndWeight_Detail>();
      }
    }

    static void SetDetailSynced(GradeAndWeight_Detail detail, long id)
    {
      using (var session = DmoSession.New())
      {
        var update = new DQUpdateDom(typeof(GradeAndWeight_Detail));
        update.Columns.Add(new DQUpdateColumn("Sync", true));
        if (detail.ID == 0)
        {
          detail.ID = id;
          update.Columns.Add(new DQUpdateColumn("ID", id));
        }
        update.Where.Conditions.Add(DQCondition.EQ("SID", detail.SID));
        session.ExecuteNonQuery(update);
        session.Commit();
      }
    }
  }
}
