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.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
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();





    public static void ClearWeightBySID(long sid)
    {
      var updateDom = new DQUpdateDom(typeof(GradeAndWeight_Detail));
      updateDom.Where.Conditions.Add(DQCondition.EQ("SID", sid));
      updateDom.Columns.Add(new DQUpdateColumn("Weight", DQExpression.NULL));
      using (var session = LocalDmoSession.New())
      {
        session.ExecuteNonQuery(updateDom);
        session.Commit();
      }
    }

    public static void DeleteBySID(long sid)
    {
      var delDom = new DQDeleteDom(typeof(GradeAndWeight_Detail));
      delDom.Where.Conditions.Add(DQCondition.EQ("SID", sid));
      using (var session = LocalDmoSession.New())
      {
        session.ExecuteNonQuery(delDom);
        session.Commit();
      }
    }

    public static void UpdateLosted(long sid)
    {
      var updateDom = new DQUpdateDom(typeof(GradeAndWeight_Detail));
      updateDom.Where.Conditions.Add(DQCondition.EQ("SID", sid));
      updateDom.Columns.Add(new DQUpdateColumn("IsLostWeight", true));

      using (var session = LocalDmoSession.New())
      {
        session.ExecuteNonQuery(updateDom);
        session.Commit();
      }
    }

    public static BindingList<GradeAndWeight_Detail> GetDetails(DateTime date, int top = 15)
    {
      var bindList = new BindingList<GradeAndWeight_Detail>();
      //      var bindList=new BlockingCollection<GradeAndWeight_Detail>();
      var list = new List<GradeAndWeight_Detail>();

      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 = LocalDmoSession.New())
      {
        list = session.ExecuteList(query).Cast<GradeAndWeight_Detail>().ToList();
      }
      foreach (GradeAndWeight_Detail detail in list)
      {
        bindList.Add(detail);
      }
      return bindList;
    }

    public static int GetTangTuiSumNumber(DateTime date)
    {
      var query = new DQueryDom(new JoinAlias(typeof(GradeAndWeight_Detail)));
      query.Where.Conditions.Add(DQCondition.EQ("Date", date));
      query.Where.Conditions.Add(DQCondition.EQ("Technics_Name", "烫褪"));
      query.Columns.Add(DQSelectColumn.Count());
      using (var session = LocalDmoSession.New())
      {
        return Convert.ToInt32(session.ExecuteScalar(query));
      }
    }

    public static int GetMaoBoSumNumber(DateTime date)
    {
      var query = new DQueryDom(new JoinAlias(typeof(GradeAndWeight_Detail)));
      query.Where.Conditions.Add(DQCondition.EQ("Date", date));
      query.Where.Conditions.Add(DQCondition.EQ("Technics_Name", "毛剥"));
      query.Columns.Add(DQSelectColumn.Count());
      using (var session = LocalDmoSession.New())
      {
        return Convert.ToInt32(session.ExecuteScalar(query));
      }
    }
    public static decimal GetSumWeight(DateTime date)
    {
      var query = new DQueryDom(new JoinAlias(typeof(GradeAndWeight_Detail)));
      query.Where.Conditions.Add(DQCondition.EQ("Date", date));

      query.Columns.Add(DQSelectColumn.Sum("Weight"));
      using (var session = LocalDmoSession.New())
      {
        return Convert.ToDecimal(session.ExecuteScalar(query));
      }
    }


    public static List<GradeAndWeight_Detail> GetLostWeightDetails(DateTime date)
    {
      var query = new DmoQuery(typeof(GradeAndWeight_Detail));
      query.Where.Conditions.Add(DQCondition.EQ("IsLostWeight", true));
      query.Where.Conditions.Add(DQCondition.EQ("Date", date));
      query.OrderBy.Expressions.Add(DQOrderByExpression.Create("Index", true));

      using (var session = LocalDmoSession.New())
      {
        return session.ExecuteList(query).Cast<GradeAndWeight_Detail>().ToList();
      }
    }

    public static void Insert(GradeAndWeight_Detail detail)
    {
      using (var session = LocalDmoSession.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 = LocalDmoSession.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)));
        }

        //只要修改就设置 Sync为False
        update.Columns.Add(new DQUpdateColumn("Sync", false));

        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/UpdateOrInsertDetailOrDelete";
        var id = RpcFacade.Call<long>(method, serializer.Serialize(detail));

        SetDetailSynced(detail, id);
      }
    }

    static IEnumerable<GradeAndWeight_Detail> GetAllNeedSyncDetails()
    {
      using (var session = LocalDmoSession.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 = LocalDmoSession.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();
      }
    }

    public static void SaveWeightData(decimal weight)
    {
      using (var session = LocalDmoSession.New())
      {
        var record = new WeightData { Weight = weight, Time = DateTime.Now };
        session.Insert(record);
        session.Commit();
      }
    }

    public static int GetTodayTotalCount(DateTime date)
    {
      var query = new DQueryDom(new JoinAlias(typeof(GradeAndWeight_Detail)));
      query.Columns.Add(DQSelectColumn.Count());
      query.Where.Conditions.Add(DQCondition.EQ("Date", date));
      using (var session = LocalDmoSession.New())
      {
        return Convert.ToInt32(session.ExecuteScalar(query));
      }
    }
  }
}
