using Aliyun.OSS;
using Elasticsearch.Net;
using JiaZhiQuan.Common.AliOSS;
using JiaZhiQuan.Common.Config;
using JiaZhiQuan.Common.ElasticSearch;
using JiaZhiQuan.Common.ElasticSearch.Models;
using JiaZhiQuan.Common.Response;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.Containers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Cache;
using Wicture.DbRESTFul.Infrastructure.Repository;
using static JiaZhiQuan.Common.Models.ApiOrderModel;
using static JiaZhiQuan.Common.YCTech.YCTechModel;

namespace JiaZhiQuan.Common
{
    public static partial class RepositoryExtension
    {
        //下单api直充
        public static async Task<OperateResult> PurchaseApiOrder(this DbRESTFulRepository repository,
            IHttpClientFactory httpClientFactory, ConfigFromDb config, SupplierOrder orderInfo) {
            var rst = new OperateResult() { count = 0 };
            orderInfo.supplierId = config.YCTechSupplierId;
            CheckOrder(orderInfo);
            var httpClient = httpClientFactory.CreateClient();
            var request = new YCTechSubmitOrderRequest {
                OutOrderId = orderInfo.id.ToString(), Account = orderInfo.rechargeAccount,
                CallbackUrl = config.YCTechOrderCallBackUrl, ProductId = orderInfo.productId.ToString(),
                Timestamp = DateTime.Now.ToString("yyyyMMddHHmmssfff")
            };
            //下单成功和状态未更新时，不能重复下单。
            var count = await repository.QuerySingleOrDefaultAsync<int>(
                $@"select count(*) from n_supplier_order 
                    where orderId={orderInfo.orderId} and orderStatus in (0,1)");
            if (count > 0) throw new Exception("不能重复下单");
            //尝试3次
            for (int i = 0; i < 3; i++) {
                await request.ExeRequest(httpClient, config);
                if (request.Response.Sucess) {
                    break;
                } else {
                    Thread.Sleep(200);
                }
            }
            if (!request.Response.Sucess|| request.Response.Data == null) {
                LoggerManager.Logger.Error($"供应商下单失败:{request.Response.Msg}");
                throw new Exception($"供应商下单失败:{request.Response.Msg}");
            }
            orderInfo.supplierOrderId = request.Response.Data.OrderId;
            orderInfo.purchaseTime = DateTime.Now;
            orderInfo.purchasePrice = (int)(request.Response.Data.Cost * 100);
            orderInfo.orderStatus = 0;
            orderInfo.orderMethod = 1;
            orderInfo.createAt = DateTime.Now;

            using var conn = repository.ConnectionManager.GetConnection();
            conn.Open();
            var trans = conn.BeginTransaction();
            try {
                var insert = await repository.SimpleInsert("n_supplier_order", orderInfo, conn, trans);
                if (insert.count > 0) {
                    await repository.QuerySingleOrDefaultAsync<int>(
                        $@"update n_exchange_order set supplierOrderId=@supplierOrderId where id={orderInfo.orderId}"
                        , new { orderInfo.supplierOrderId },conn,trans);
                }
                trans.Commit();
                return new OperateResult { count = insert.count };
            } catch (Exception ex) {
                trans.Rollback();
                LoggerManager.Logger.Error(ex,$"未入库供应商订单号：{request.Response.Data.OrderId}");
                throw ex;
            }
        }
        
        private static void CheckOrder(SupplierOrder orderInfo) {
            if (orderInfo == null) throw new Exception("订单信息不能为空");
            if (orderInfo.id <= 0) throw new Exception("订单id不能为空");
            if(orderInfo.orderId<=0) throw new Exception("平台订单id不能为空");
            if (orderInfo.productId <= 0) throw new Exception("采购商品id不能为空");
            if(string.IsNullOrEmpty(orderInfo.productName)) throw new Exception("采购商品名称不能为空");
            if (orderInfo.supplierId <= 0) throw new Exception("供应商id不能为空");
            if (string.IsNullOrEmpty(orderInfo.rechargeAccount)) throw new Exception("充值号码不能为空");
            if (orderInfo.userId <= 0) throw new Exception("下单用户id不能为空");
        }
    }

}
