using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BO.BO.BaseInfo;
using BWP.WinFormControl;
using Forks.EnterpriseServices.DomainObjects2.DQuery;
using Forks.JsonRpc.Client;
using Newtonsoft.Json;

namespace BO.Utils.BillRpc
{
  public  class DeliverGoodsLineRpc
  {
    /// <summary>
    ///  获取送货线路档案  在线则在线查询 同时更新本地数据库 ，不在线则从本地数据查
    /// </summary>
    /// <param name="input">查询用的</param>
    /// <param name="updateLocalDb">是否更新本地数据库，如果更新则尽量减少使用该方法的次数， 因为客户会有很多</param>
    /// <returns></returns>
    public static List<DeliverGoodsLine> SyncList(string input = "", bool updateLocalDb = true)
    {
      if (LoginRpcUtil.TestConnection(100))
      {
        //在线
        var json = RpcFacade.Call<string>("/MainSystem/B3ClientService/Rpcs/BillRpc/BaseInfoRpc/SyncDeliverGoodsLine", input);
        var list = JsonConvert.DeserializeObject<List<DeliverGoodsLine>>(json);

        if (updateLocalDb)
        {
          using (var session = LocalDmoSession.New())
          {
            var sql1 = @"truncate table [DeliverGoodsLine];";
            session.ExecuteSqlNonQuery(sql1);
            foreach (DeliverGoodsLine dmo in list)
            {
              session.Insert(dmo);
            }
            session.Commit();
          }
        }
        return list;
      }


      var dmoquery = new DmoQuery(typeof(DeliverGoodsLine));
      if (!string.IsNullOrWhiteSpace(input))
      {
        dmoquery.Where.Conditions.Add(DQCondition.Or(DQCondition.Like("Name", input), DQCondition.Like("Spell", input)));
      }
      using (var session = LocalDmoSession.New())
      {
        return session.ExecuteList(dmoquery).Cast<DeliverGoodsLine>().ToList();
      }
    }


    public static List<WordPair> SyncListForDropDown(string input = "", bool updateLocalDb = true)
    {
      var list = SyncList(input, updateLocalDb);
      return list.Select(x => new WordPair(x.Name, x.ID.ToString())).ToList();
    }
  }
}
