TbBoxOrderService.cs 42.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Blind.Interfaces.TbBoxOrder;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Blind.Entitys;
using NCC.Blind.Entitys.Dto.TbBoxOrder;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using NCC.ClayObject;
using NCC.System.Interfaces.System;
using NCC.System.Entitys.Permission;
using NCC.Education.Entitys;
using NCC.BlindBox;
using Microsoft.Extensions.Logging;
using Antis.Pay.Core.Enum;
using System.Collections;
using Microsoft.AspNetCore.Http;
using NCC.Common.Extensions;
using Antis.Pay.Core.Interface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Antis.Pay.Core.Model;
using Microsoft.AspNetCore.Authorization;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using MySqlX.XDevAPI.Common;
using Spire.Presentation.Drawing.TimeLine;
using NCC.Common.Model;
using NCC.Blind.Entitys.Dto.TbAreaLineNode;
using NCC.Blind.Entitys.Dto.TbMbtLine;
using NCC.Blind.Entitys.Dto.TbMbtLineNode;
using NCC.Blind.Entitys.Dto.TbAreaLine;
using Serilog;

namespace NCC.Blind.TbBoxOrder
{
    /// <summary>
    /// 盲盒订单服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "盲盒订单",Name = "TbBoxOrder", Order = 200)]
    [Route("api/Blind/[controller]")]
    public class TbBoxOrderService : ITbBoxOrderService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<TbBoxOrderEntity> _tbBoxOrderRepository;
        private readonly IDbLinkService _dbLinkService;
        private readonly IDataBaseService _dataBaseService;
        private readonly SqlSugarScope _db;
        private readonly ILogger<TbBoxOrderEntity> _logger;
        private readonly IHostingEnvironment _hostingEnvironment;

        private readonly IUserManager _userManager;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWePay _wepay;

        private static WepayOptions WepayConfig = App.GetConfig<PaymentSettingsOptions>("PaymentSettings", true).WepayConfig;

        /// <summary>
        /// 初始化一个<see cref="TbBoxOrderService"/>类型的新实例
        /// </summary>
        public TbBoxOrderService(
            ISqlSugarRepository<TbBoxOrderEntity> tbBoxOrderRepository,
            IDbLinkService dbLinkService,
            IDataBaseService dataBaseService,
            IUserManager userManager,
            ILogger<TbBoxOrderEntity> logger,
            IHttpContextAccessor httpContextAccessor,
            IHostingEnvironment hostingEnvironment,
            IWePay wepay)
        {
            _tbBoxOrderRepository = tbBoxOrderRepository;
            _db = _tbBoxOrderRepository.Context;
            _dbLinkService = dbLinkService;
            _dataBaseService = dataBaseService;
            _userManager = userManager;
            _logger = logger;
            _httpContextAccessor = httpContextAccessor;
            _hostingEnvironment = hostingEnvironment;
            _wepay = wepay;
        }


        public class OutOrderLineOptions
        {

            /// <summary>
            /// 地域线路信息
            /// </summary>
            public TbAreaLineInfoOutput areaLine { get; set; }
            /// <summary>
            /// MBTI线路信息
            /// </summary>
            public TbMbtLineInfoOutput mbtLine { get; set; }

            /// <summary>
            /// 地域线路节点集合
            /// </summary>
            public List<TbAreaLineNodeListOutput> areaLineNodeList { get; set; }
            /// <summary>
            /// MBTI人格线路节点集合
            /// </summary>
            public List<TbMbtLineNodeListOutput> mbtLineNodeList { get; set; }

            /// <summary>
            /// 类型 1--地域线路  2--MBT线路
            /// </summary>
            public string type { get; set; }
        }




        /// <summary>
        /// 根据订单ID查询路线信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("GetOrderLineByOrderId")]
        public async Task<dynamic> GetOrderLineByOrderId(string id)
        {
            OutOrderLineOptions result = new OutOrderLineOptions();
            var order = _db.Queryable<TbBoxOrderEntity>().Where(o => o.Id == id).First();
            if (order.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到订单信息!");
            if (order.Type == BlindBoxStatus.BlindBoxLineStatus.地域线路.GetHashCode().ToString())
            {
                //地域路线
                var entity = await _db.Queryable<TbAreaLineEntity>().FirstAsync(p => p.Id == order.AreaLineId);
                var output = entity.Adapt<TbAreaLineInfoOutput>();
                result.areaLine = output;
                Log.Information($"查询的订单路线ID:{order.AreaLineId}");
                var model = _db.Queryable<TbAreaLineNodeEntity>().Where(o => o.AreaLineId == order.AreaLineId).Select(it => new TbAreaLineNodeListOutput
                {
                    id = it.Id,
                    areaLineId = it.AreaLineId,
                    title = it.Title,
                    description = it.Description,
                    remark = it.Remark,
                    creatorTime = it.CreatorTime,
                    lastModifyTime = it.LastModifyTime,
                    banner = it.Banner,
                    sorts = it.Sorts,
                }).MergeTable().Mapper(p =>
                {
                    //p.areaLine = _db.Queryable<TbAreaLineEntity>().Where(o => o.Id == p.areaLineId).First();
                }).ToList();
                Log.Information($"路线节点集合:{JsonConvert.SerializeObject(model)}");

                result.areaLineNodeList = model;

                    
            }
            else
            {
                //人格路线
                var entity = await _db.Queryable<TbMbtLineEntity>().FirstAsync(p => p.Id == order.MbtLineId);
                var output = entity.Adapt<TbMbtLineInfoOutput>();
                result.mbtLine = output;
                var model = _db.Queryable<TbMbtLineNodeEntity>().Where(o => o.MbtLineId == order.MbtLineId).Select(it => new TbMbtLineNodeListOutput
                {
                    id = it.Id,
                    mbtLineId = it.MbtLineId,
                    title = it.Title,
                    description = it.Description,
                    remark = it.Remark,
                    creatorTime = it.CreatorTime,
                    lastModifyTime = it.LastModifyTime,
                    sorts = it.Sorts,
                    banner=it.Banner
                }).MergeTable().Mapper(p =>
                {
                    //p.mbtLine = _db.Queryable<TbMbtLineEntity>().Where(o => o.Id == p.mbtLineId).First();
                }).ToList();
                result.mbtLineNodeList = model;
            }
            result.type = order.Type;
            return result;
        }











        /// <summary>
        /// 扫码获得盲盒券
        /// </summary>
        public class ConfirmBindingCouponOptions
        {
            /// <summary>
            /// 盲盒订单ID
            /// </summary>
            public string boxOrderId { get; set; }

            /// <summary>
            /// 用户ID
            /// </summary>
            public string userId { get; set; }

        }

        /// <summary>
        /// 扫码获得盲盒券
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost("CofirmBindingCoupon")]
        public async Task CofirmBindingCoupon(ConfirmBindingCouponOptions query)
        {
            var boxOrder = _db.Queryable<TbBoxOrderEntity>().Where(o => o.Id == query.boxOrderId).First();
            if (boxOrder.IsNullOrEmpty()) throw NCCException.Oh($"暂无此订单哦");
            if (!boxOrder.GiveUserId.IsNullOrEmpty()) throw NCCException.Oh($"该券已经被送出人接收了哦");
            var user = _db.Queryable<UserEntity>().Where(o => o.Id == query.userId).First();
            if (user.IsNullOrEmpty()) throw NCCException.Oh($"暂无此用户哦");
            var coupon = _db.Insertable(new TbMyBoxCouponEntity
            {
                Id=YitIdHelper.NextId().ToString(),
                GiveUserId= boxOrder.UserId,
                OrderId=boxOrder.Id,
                Remark=$"赠送盲盒抽奖",
                Title="赠送盲盒抽奖",
                Type=BlindBoxStatus.BlindBoxCouponStatus.未使用.GetHashCode().ToString(),
                UserId= user.Id,
                CreatorTime=DateTime.Now
            }).ExecuteReturnEntity();
            _logger.LogInformation($"添加盲盒券实体:{coupon.ToJson()}");
            boxOrder.GiveUserId = user.Id;
            boxOrder.MyBoxCouponId = coupon.Id;
            var result = _db.Updateable(boxOrder).ExecuteCommand();
            _logger.LogInformation($"补全赠送信息:{result}");
        }


        /// <summary>
        /// 立即抽奖入参
        /// </summary>
        public class ConfirmDrawOptions
        {
            /// <summary>
            /// 盲盒订单ID
            /// </summary>
            public string boxOrderId { get; set; }

            /// <summary>
            /// 盲盒券ID  赠送订单需传入
            /// </summary>
            public string myBoxCouponId { get; set; }
        }

        /// <summary>
        /// 立即抽奖
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpPost("ConFirmDraw")]
        public async Task<dynamic> ConFirmDraw(ConfirmDrawOptions query)
        {
            var model = _db.Queryable<TbBoxOrderEntity>().Where(o => o.Id == query.boxOrderId).First();
            if (model.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到该订单,无法抽奖!");
            var logData = _db.Queryable<TbBoxLogEntity>().Where(o => o.BoxOrderId == model.Id).Count();
            if (logData > 1) throw NCCException.Oh($"您的次数已用完了哦");
            if (model.Type == BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString())
            {
                //人格
                var list = _db.Queryable<TbMbtLineEntity>().Where(o=>o.MbtId==model.MbtId).ToList();
                List<string> ids = new List<string>();
                foreach (var item in list)
                {
                    ids.Add(item.Id);
                }
                int r = new Random().Next(ids.Count);
                var data = list.Find(o => o.Id == ids[r]);
                if (data.IsNullOrEmpty()) throw NCCException.Oh($"暂无人格路线哦");
                var logResult = new TbBoxLogEntity
                {
                    Id = YitIdHelper.NextId().ToString(),
                    Type = BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString(),
                    BoxOrderId = model.Id,
                    CreatorTime = DateTime.Now,
                    MbtId = model.MbtId,
                    MbtLineId = data.Id,
                    UserId = model.UserId,
                };
                try
                {
                    _db.BeginTran();
                    if (model.IsMe == BlindBoxStatus.BlindIsMeStatus.赠送他人.GetHashCode().ToString())
                    {
                        logResult.UserId = model.GiveUserId;
                        var couponResult = _db.Updateable<TbMyBoxCouponEntity>().SetColumns(o => o.Type == BlindBoxStatus.BlindBoxCouponStatus.已使用.GetHashCode().ToString()).Where(o => o.Id == query.myBoxCouponId).ExecuteCommand();
                        _logger.LogInformation($"我的盲盒券状态更改失败:{couponResult}");
                    }
                    var result = _db.Insertable(logResult).ExecuteCommand();
                    _logger.LogInformation($"添加MBT抽奖记录状态:{result}");
                    model.MbtLineId = data.Id;
                    var orderResult = _db.Updateable(model).ExecuteCommand();
                    _logger.LogInformation($"更改人格订单抽奖线路信息:{orderResult}");
                    _db.CommitTran();
                    var lineNode = _db.Queryable<TbMbtLineNodeEntity>().Where(o => o.MbtLineId == data.Id).ToList();
                    return new
                    {
                        type = BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString(),
                        mbtLine = data,
                        mbtLineNode = lineNode,
                    };
                }
                catch (Exception ex)
                {
                    _logger.LogInformation($"抽奖人格报错:{ex.Message}");
                    _db.RollbackTran();
                    throw NCCException.Oh($"抽奖人格报错:{ex.Message}");
                }
            }
            else
            {
                //地域
                var list = _db.Queryable<TbAreaLineEntity>().Where(o => o.AreaId == model.AreaId).ToList();
                List<string> ids = new List<string>();
                foreach (var item in list)
                {
                    ids.Add(item.Id);
                }
                var data = GetRandomItem(list);
                Log.Information($"概率值:{JsonConvert.SerializeObject(data)}");
                //int r = new Random().Next(ids.Count);
                //var data = list.Find(o => o.Id == ids[r]);
                if (data.IsNullOrEmpty()) throw NCCException.Oh($"暂无地域路线或者百分比之和不等于100!");
                var logResult = new TbBoxLogEntity
                {
                    Id = YitIdHelper.NextId().ToString(),
                    Type = BlindBoxStatus.BlindBoxLineStatus.地域线路.GetHashCode().ToString(),
                    BoxOrderId = model.Id,
                    CreatorTime = DateTime.Now,
                    AreaId = model.AreaId,
                    AreaLineId = data.Id,
                    UserId = model.UserId,
                };
            try
            {
                _db.BeginTran();
                    if (model.IsMe == BlindBoxStatus.BlindIsMeStatus.赠送他人.GetHashCode().ToString())
                    {
                        logResult.UserId = model.GiveUserId;
                        var couponResult = _db.Updateable<TbMyBoxCouponEntity>().SetColumns(o => o.Type == BlindBoxStatus.BlindBoxCouponStatus.已使用.GetHashCode().ToString()).Where(o => o.Id == query.myBoxCouponId).ExecuteCommand();
                        _logger.LogInformation($"我的盲盒券状态更改失败:{couponResult}");
                    }
                    var result = _db.Insertable(logResult).ExecuteCommand();
                _logger.LogInformation($"添加地域抽奖记录状态:{result}");
                model.AreaLineId = data.Id;
                var orderResult = _db.Updateable(model).ExecuteCommand();
                _logger.LogInformation($"更改地域订单抽奖线路信息:{orderResult}");
                var lineNode = _db.Queryable<TbAreaLineNodeEntity>().Where(o => o.AreaLineId == data.Id).ToList();
                _db.CommitTran();
            return new
            {
                type=BlindBoxStatus.BlindBoxLineStatus.地域线路.GetHashCode().ToString(),
                areaLine = data,
                areaLineNode = lineNode,
            };
        }
            catch (Exception ex)
            {
                _logger.LogInformation($"抽奖地域报错:{ex.Message}");
                _db.RollbackTran();
                throw NCCException.Oh($"抽奖地域报错:{ex.Message}");
            }
            }


        }

        /// <summary>
        /// 概率算法
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static TbAreaLineEntity GetRandomItem(List<TbAreaLineEntity> items)
        {
            double totalPercentage = items.Sum(x => x.Ratio.ToDouble());
            double randomValue = new Random().NextDouble() * totalPercentage;

            foreach (TbAreaLineEntity item in items)
            {
                randomValue -= item.Ratio.ToDouble();
                if (randomValue <= 0)
                {
                    return item;
                }
            }

            return null; // 如果总百分比小于100%或列表为空,则返回null
        }







        /// <summary>
        /// 支付后回调处理
        /// </summary>
        /// <returns></returns>
        [HttpGet("WePayNotify")]
        [HttpPost("WePayNotify")]
        [AllowAnonymous]
        public string WePayNotify()
        {
            _logger.LogInformation("进入支付回调");
            WePayReturnModel payResult = new WePayReturnModel();
            if (_wepay.VerifyNotify(out payResult))
            {
                _logger.LogInformation("验证成功" + JsonConvert.SerializeObject(payResult));
                var boxOrder = _db.Queryable<TbBoxOrderEntity>().Where(o => o.OrderNumber == payResult.OutTradeNo).First();
                if (boxOrder.Status == BlindBoxStatus.BlindBoxOrderStatus.已付款.GetHashCode().ToString())
                {
                    return _wepay.GetReturnXml("SUCCESS", "OK");
                }
                else
                {
                    boxOrder.Status = BlindBoxStatus.BlindBoxOrderStatus.已付款.GetHashCode().ToString();
                    var result = _db.Updateable(boxOrder).ExecuteCommand();
                    _logger.LogInformation($"盲盒回调更改订单状态:{result}");
                }
            }
            _logger.LogInformation("支付回调验证失败 payResult=" + JsonHelper.ToJson((object)payResult));
            return _wepay.GetReturnXml("FAIL", "ERROR");
        }

        /// <summary>
        /// 盲盒订单下单参数
        /// </summary>
        public class PlanceBoxOptions
        {
            /// <summary>
            /// 用户ID
            /// </summary>
            public string userId { get; set; }


            /// <summary>
            /// 路线  1--地域路线  2--MBT人格路线
            /// </summary>
            public string type { get; set; }

            /// <summary>
            /// 地域ID
            /// </summary>
            public string areaId { get; set; }


            /// <summary>
            /// 人格ID
            /// </summary>
            public string mbtId { get; set; }


            /// <summary>
            /// 购买类型  1--自己购买  2--赠送他人
            /// </summary>
            public string isMe { get; set; }

            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime? creatorTime { get; set; }

            /// <summary>
            /// 修改时间
            /// </summary>
            public DateTime? lastModifyTime { get; set; }
        }

        /// <summary>
        /// 盲盒订单下单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("PlanceBoxOrder")]
        public async Task<dynamic> PlanceBoxOrder(PlanceBoxOptions input)
        {
            if (input.userId.IsNullOrEmpty()) throw NCCException.Oh($"请设置用户标识");
            if (input.type.IsNullOrEmpty()) throw NCCException.Oh($"请选择路线类型");
            if (input.isMe.IsNullOrEmpty()) throw NCCException.Oh($"请选择购买类型");
            var user = _db.Queryable<UserEntity>().Where(o => o.Id == input.userId).First();
            if (user.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到该用户");
            if (input.type.Equals(BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString()))
            {
                //人格
                if (input.mbtId.IsNullOrEmpty()) throw NCCException.Oh($"请选择人格");
                var mbt = _db.Queryable<TbMbtCharacterEntity>().Where(o => o.Id == input.mbtId).First();
                if (mbt.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到人格");
            }
            else
            {
                //地域
                if (input.areaId.IsNullOrEmpty()) throw NCCException.Oh($"请选择地域!");
                var area = _db.Queryable<TbAreaEntity>().Where(o => o.Id == input.areaId).First();
                if (area.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到地域");
            }
            //if(input.isMe==BlindBoxStatus.BlindIsMeStatus.自己购买.GetHashCode().ToString())
            //{
            //    //自己购买
            //    if (input.type.Equals(BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString()))
            //    {
            //        //人格路线
            //        if (input.mbtLineId.IsNullOrEmpty()) throw NCCException.Oh($"请选择人格路线");
            //        var mbtLine = _db.Queryable<TbMbtLineEntity>().Where(o => o.Id == input.mbtLineId).First();
            //        if (mbtLine.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到人格路线");
            //    }
            //    else
            //    {
            //        //地域路线
            //        if (input.areaLineId.IsNullOrEmpty()) throw NCCException.Oh($"请选择地域路线!");
            //        var areaLine = _db.Queryable<TbAreaLineEntity>().Where(o => o.Id == input.areaLineId).First();
            //        if (areaLine.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到地域路线");
            //    }
            //}
            var settingPrice = _db.Queryable<TbSettingPriceEntity>().ToList();
            if (settingPrice.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到价格设定数据,请联系管理员!");
            var manghe = settingPrice.Find(o => o.Type == BlindBoxStatus.BlindBoxSettingPriceType.盲盒价格.GetHashCode().ToString());
            var menpiao = settingPrice.Find(o => o.Type == BlindBoxStatus.BlindBoxSettingPriceType.门票价格.GetHashCode().ToString());
            if (menpiao.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到门票价格,请联系管理员!");
            if (manghe.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到盲盒价格,请联系管理员!");
            decimal totalMoneys = manghe.Price + menpiao.Price;
            Log.Information($"支付总价:{totalMoneys}");
            var entity = input.Adapt<TbBoxOrderEntity>();
            entity.OrderNumber = ServiceHelper.getTime().ToString();
            entity.Status = BlindBoxStatus.BlindBoxOrderStatus.未付款.GetHashCode().ToString();
            entity.CreatorTime = DateTime.Now;
            entity.TotalPrice = totalMoneys;
            entity.Status = BlindBoxStatus.BlindBoxOrderStatus.未付款.GetHashCode().ToString();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.CreatorTime = DateTime.Now;
            var orderResult = _db.Insertable(entity).ExecuteReturnEntity();
            _logger.LogInformation($"添加订单状态:{orderResult.ToJson()}");
            if (entity.IsMe == "2")
            {
                _logger.LogInformation($"进入二维码");
                entity.QrCode = GetQRCode("pages/index/index", $"boxOrderId={orderResult.Id}").GetAwaiter().GetResult();
                _logger.LogInformation($"生成二维码:{entity.QrCode}");

            }
            //1--盲盒下单
            string result = _wepay.BuildWePay(user.OpenId, entity.OrderNumber, "盲盒抽奖", _wepay.GetMoneyYuanToFen(entity.TotalPrice), HttpContextExtensions.GetRemoteIpAddressToIPv4(_httpContextAccessor.HttpContext),0,1);
            _logger.LogInformation($"这是盲和下单数据:{result.ToJson()}");
            var dataResult = new PlanceBoxOrderResult
            {
                order = entity,
                data =JObject.Parse(result)
            };
            return dataResult;

        }

        /// <summary>
        /// 盲盒下单返回信息
        /// </summary>
        public class PlanceBoxOrderResult
        {
            /// <summary>
            /// 订单信息
            /// </summary>
            public TbBoxOrderEntity order { get; set; }
            public object data { get; set; }
        }

        /// <summary>
        /// 小程序获取accesstoken
        /// </summary>
        public class WXApi
        {
            public string access_token { get; set; }
        }

        public class ModelJson
        {
            public string scene = "";

            public string page = "";

            public bool check_path = false;
        }
        /// <summary>
        /// 获取小程序accesstoken
        /// </summary>
        /// <param name="appId">APPID</param>
        /// <param name="appSecret">密钥</param>
        /// <returns></returns>
        [HttpGet("GetAccessToken")]
        [AllowAnonymous]
        public string GetAccessToken()
        {
            string apiurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WepayConfig.APPLETE_APPID + "&secret=" + WepayConfig.APPLETE_APPSECRET;
            WebRequest request = WebRequest.Create(apiurl);
            request.Method = "GET";
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            Encoding encode = Encoding.UTF8;
            StreamReader reader = new StreamReader(stream, encode);
            string detail = reader.ReadToEnd();
            _logger.LogInformation($"信息access:{detail}");
            WXApi jd = JsonConvert.DeserializeObject<WXApi>(detail);
            return jd.access_token;
        }
        /// <summary>
        /// 获取二维码数据 带参数
        /// </summary>
        /// <param name="page">扫描二维码跳转的页面</param>
        /// <param name="scene">携带的参数多个参数逗号隔开</param>
        /// <returns></returns>
        [HttpPost("GetQRCode")]
        [AllowAnonymous]
        public async Task<string> GetQRCode(string page = "", string scene = "")
        {
            ModelJson jsons = new ModelJson();
            _ = string.Empty;
            string access_token = GetAccessToken();
            _logger.LogInformation($"获取token:{access_token}");
            string apiurl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            WebRequest request = WebRequest.Create(apiurl);
            request.Method = "POST";
            request.ContentType = "image/jpeg";
            jsons.scene = scene;
            jsons.page = page;
            jsons.check_path = false;
            string DataJson = JsonHelper.ToJson((object)jsons);
            byte[] bytearray = Encoding.UTF8.GetBytes(DataJson);
            request.ContentLength = bytearray.Length;
            Stream strStream = request.GetRequestStream();
            strStream.Write(bytearray, 0, bytearray.Length);
            strStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            Bitmap bitimg = new Bitmap(stream);
            MemoryStream memoryStream = new MemoryStream();
            bitimg.Save(memoryStream, ImageFormat.Jpeg);
            byte[] arr = new byte[memoryStream.Length];
            memoryStream.Position = 0L;
            memoryStream.Read(arr, 0, (int)memoryStream.Length);
            Image imgs = Image.FromStream(memoryStream);
            string filename = _hostingEnvironment.ContentRootPath + "\\UploadFile\\SystemFile\\" + Guid.NewGuid().ToString() + ".jpg";
            imgs.Save(filename);
            return Path.GetFileName(filename);
        }




        /// <summary>
        /// 获取盲盒订单
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var dbLink = await _dbLinkService.GetInfo("218239598550058245");
            _db.AddConnection(new ConnectionConfig()
            {
                ConfigId = dbLink.Id,
                DbType = _dataBaseService.ToDbType(dbLink.DbType),
                ConnectionString = _dataBaseService.ToConnectionString(dbLink),
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });
            _db.ChangeDatabase(dbLink.Id);
            var entity = await _db.Queryable<TbBoxOrderEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<TbBoxOrderInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取盲盒订单列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] TbBoxOrderListQueryInput input)
        {
            var dbLink = await _dbLinkService.GetInfo("218239598550058245");
            _db.AddConnection(new ConnectionConfig()
            {
                ConfigId = dbLink.Id,
                DbType = _dataBaseService.ToDbType(dbLink.DbType),
                ConnectionString = _dataBaseService.ToConnectionString(dbLink),
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });
            _db.ChangeDatabase(dbLink.Id);
            var sidx = input.sidx == null ? "id" : input.sidx;
            var data = await _db.Queryable<TbBoxOrderEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Equals(input.userId))
                .WhereIF(!string.IsNullOrEmpty(input.orderNumber), p => p.OrderNumber.Contains(input.orderNumber))
                .WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
                .WhereIF(!string.IsNullOrEmpty(input.areaId), p => p.AreaId.Equals(input.areaId))
                .WhereIF(!string.IsNullOrEmpty(input.areaLineId), p => p.AreaLineId.Equals(input.areaLineId))
                .WhereIF(!string.IsNullOrEmpty(input.mbtId), p => p.MbtId.Equals(input.mbtId))
                .WhereIF(!string.IsNullOrEmpty(input.mbtLineId), p => p.MbtLineId.Equals(input.mbtLineId))
                .WhereIF(!string.IsNullOrEmpty(input.status), p => p.Status.Equals(input.status))
                .WhereIF(!string.IsNullOrEmpty(input.isMe), p => p.IsMe.Equals(input.isMe))
                .WhereIF(!string.IsNullOrEmpty(input.giveUserId), p => p.GiveUserId.Equals(input.giveUserId))
                .WhereIF(!string.IsNullOrEmpty(input.myBoxCouponId), p => p.MyBoxCouponId.Equals(input.myBoxCouponId))
                .Select(it=> new TbBoxOrderListOutput
                {
                    id = it.Id,
                    userId=it.UserId,
                    orderNumber=it.OrderNumber,
                    type=it.Type,
                    areaId=it.AreaId,
                    areaLineId=it.AreaLineId,
                    mbtId=it.MbtId,
                    mbtLineId=it.MbtLineId,
                    totalPrice=it.TotalPrice,
                    status=it.Status,
                    isMe=it.IsMe,
                    giveUserId=it.GiveUserId,
                    myBoxCouponId=it.MyBoxCouponId,
                    creatorTime=it.CreatorTime,
                    lastModifyTime=it.LastModifyTime,
                    qrCode=it.QrCode
                }).MergeTable().Mapper(p =>
                {
                    var logData = _db.Queryable<TbBoxLogEntity>().Where(o => o.BoxOrderId == p.id).Count();
                    p.isAnewDraw = logData > 1 ? "1" : "2";
                    p.tickets = _db.Queryable<TbTicketsOrderEntity>().Where(o => o.OrderId == p.id).First();
                    p.isAppend = p.tickets.IsNullOrEmpty() ? "1" : "2";
                    p.user = _db.Queryable<UserEntity>().Where(o => o.Id == p.userId).First();
                    p.area = _db.Queryable<TbAreaEntity>().Where(o => o.Id == p.areaId).First();
                    p.areaLine = _db.Queryable<TbAreaLineEntity>().Where(o => o.Id == p.areaLineId).First();
                    p.mbt = _db.Queryable<TbMbtCharacterEntity>().Where(o => o.Id == p.mbtId).First();
                    p.mbtLine = _db.Queryable<TbMbtLineEntity>().Where(o => o.Id == p.mbtLineId).First();
                    p.giveUser = _db.Queryable<UserEntity>().Where(o => o.Id == p.giveUserId).First();
                    p.myBoxCoupon = _db.Queryable<TbMyBoxCouponEntity>().Where(o => o.Id == p.myBoxCouponId).First();
                }).OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<TbBoxOrderListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建盲盒订单
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] TbBoxOrderCrInput input)
        {
            var dbLink = await _dbLinkService.GetInfo("218239598550058245");
            _db.AddConnection(new ConnectionConfig()
            {
                ConfigId = dbLink.Id,
                DbType = _dataBaseService.ToDbType(dbLink.DbType),
                ConnectionString = _dataBaseService.ToConnectionString(dbLink),
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });
            _db.ChangeDatabase(dbLink.Id);
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<TbBoxOrderEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.CreatorTime = DateTime.Now;  
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
		/// 获取盲盒订单无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] TbBoxOrderListQueryInput input)
        {
            var dbLink = await _dbLinkService.GetInfo("218239598550058245");
            _db.AddConnection(new ConnectionConfig()
            {
                ConfigId = dbLink.Id,
                DbType = _dataBaseService.ToDbType(dbLink.DbType),
                ConnectionString = _dataBaseService.ToConnectionString(dbLink),
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });
            _db.ChangeDatabase(dbLink.Id);
            var sidx = input.sidx == null ? "id" : input.sidx;
            var data = await _db.Queryable<TbBoxOrderEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Equals(input.userId))
                .WhereIF(!string.IsNullOrEmpty(input.orderNumber), p => p.OrderNumber.Contains(input.orderNumber))
                .WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
                .WhereIF(!string.IsNullOrEmpty(input.areaId), p => p.AreaId.Equals(input.areaId))
                .WhereIF(!string.IsNullOrEmpty(input.areaLineId), p => p.AreaLineId.Equals(input.areaLineId))
                .WhereIF(!string.IsNullOrEmpty(input.mbtId), p => p.MbtId.Equals(input.mbtId))
                .WhereIF(!string.IsNullOrEmpty(input.mbtLineId), p => p.MbtLineId.Equals(input.mbtLineId))
                .WhereIF(!string.IsNullOrEmpty(input.status), p => p.Status.Equals(input.status))
                .WhereIF(!string.IsNullOrEmpty(input.isMe), p => p.IsMe.Equals(input.isMe))
                .WhereIF(!string.IsNullOrEmpty(input.giveUserId), p => p.GiveUserId.Equals(input.giveUserId))
                .WhereIF(!string.IsNullOrEmpty(input.myBoxCouponId), p => p.MyBoxCouponId.Equals(input.myBoxCouponId))
                .Select(it=> new TbBoxOrderListOutput
                {
                    id = it.Id,
                    userId=it.UserId,
                    orderNumber=it.OrderNumber,
                    type=it.Type,
                    areaId=it.AreaId,
                    areaLineId=it.AreaLineId,
                    mbtId=it.MbtId,
                    mbtLineId=it.MbtLineId,
                    totalPrice=it.TotalPrice,
                    status=it.Status,
                    isMe=it.IsMe,
                    giveUserId=it.GiveUserId,
                    myBoxCouponId=it.MyBoxCouponId,
                    creatorTime=it.CreatorTime,
                    lastModifyTime=it.LastModifyTime,
                }).MergeTable().OrderBy(sidx+" "+input.sort).ToListAsync();
                return data;
        }

        /// <summary>
		/// 导出盲盒订单
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] TbBoxOrderListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<TbBoxOrderListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.GetList(input));
                exportData = data.Solidify<PageResult<TbBoxOrderListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"用户\",\"field\":\"userId\"},{\"value\":\"订单号\",\"field\":\"orderNumber\"},{\"value\":\"路线\",\"field\":\"type\"},{\"value\":\"地域\",\"field\":\"areaId\"},{\"value\":\"地域线路\",\"field\":\"areaLineId\"},{\"value\":\"人格\",\"field\":\"mbtId\"},{\"value\":\"人格线路\",\"field\":\"mbtLineId\"},{\"value\":\"状态\",\"field\":\"status\"},{\"value\":\"购买类型\",\"field\":\"isMe\"},{\"value\":\"赠送人\",\"field\":\"giveUserId\"},{\"value\":\"盲盒券\",\"field\":\"myBoxCouponId\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},{\"value\":\"修改时间\",\"field\":\"lastModifyTime\"},{\"value\":\"总金额\",\"field\":\"totalPrice\"},]".ToList<ParamsModel>();           
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "盲盒订单.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<TbBoxOrderListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
            };
            return output;
        }

        /// <summary>
        /// 批量删除盲盒订单
        /// </summary>
        /// <param name="ids">主键数组</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var dbLink = await _dbLinkService.GetInfo("218239598550058245");
            _db.AddConnection(new ConnectionConfig()
            {
                ConfigId = dbLink.Id,
                DbType = _dataBaseService.ToDbType(dbLink.DbType),
                ConnectionString = _dataBaseService.ToConnectionString(dbLink),
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });
            _db.ChangeDatabase(dbLink.Id);
            var entitys = await _db.Queryable<TbBoxOrderEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //批量删除盲盒订单
                    await _db.Deleteable<TbBoxOrderEntity>().In(d => d.Id,ids).ExecuteCommandAsync();
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw NCCException.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 更新盲盒订单
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] TbBoxOrderUpInput input)
        {
            var dbLink = await _dbLinkService.GetInfo("218239598550058245");
            _db.AddConnection(new ConnectionConfig()
            {
                ConfigId = dbLink.Id,
                DbType = _dataBaseService.ToDbType(dbLink.DbType),
                ConnectionString = _dataBaseService.ToConnectionString(dbLink),
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });
            _db.ChangeDatabase(dbLink.Id);
            var entity = input.Adapt<TbBoxOrderEntity>();
            entity.LastModifyTime = DateTime.Now;  
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除盲盒订单
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var dbLink = await _dbLinkService.GetInfo("218239598550058245");
            _db.AddConnection(new ConnectionConfig()
            {
                ConfigId = dbLink.Id,
                DbType = _dataBaseService.ToDbType(dbLink.DbType),
                ConnectionString = _dataBaseService.ToConnectionString(dbLink),
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });
            _db.ChangeDatabase(dbLink.Id);
            var entity = await _db.Queryable<TbBoxOrderEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<TbBoxOrderEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
        }
    }
}