using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Payment.Model;
using ASHermed.SinoInterface.Api.ContractModel.Payment.Param;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.Api.IService.Payment;
using ASHermed.SinoInterface.Code;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Exception;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.Tools;
using LopSdk;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ASHermed.SinoInterface.Api.Service.Payment
{
    /// <summary>
    /// 支付相关
    /// </summary>
    public class PaymentService : IPaymentService
    {
        ILinKingService _linKingService;
        IOnlineOrderRepository _onlineOrderRepository;
        IOnlineOrderSourceRepository _onlineOrderSourceRepository;
        AppConfigurtaion _configurtaion;
        IOnlineRefundRepository _onlineRefundRepository;
        IPubPatInfoRepository _pubPatInfoRepository;
        IOnlineAptInfoRepository _onlineAptInfoRepository;
        ITCService _tCService;
        IPrescriptionInfoRepository _prescriptionInfoRepository;
        IDicMedicineRepository _dicMedicineRepository;
        ILogger<PaymentService> _logger;
        IVerifyCodeLogService _verifyCodeLogService;
        IPubUserAddressRepository _pubUserAddressRepository;
        ITencentService _tencentService;
        ISysRepository _sysRepository;
        IPubMessageService _pubMessageService;
        IPubUserInfoRepository _pubUserInfoRepository;
        public PaymentService(ILinKingService linKingService, IOnlineOrderRepository onlineOrderRepository, IOnlineOrderSourceRepository onlineOrderSourceRepository, AppConfigurtaion configurtaion, IOnlineRefundRepository onlineRefundRepository, IPubPatInfoRepository pubPatInfoRepository, IOnlineAptInfoRepository onlineAptInfoRepository, ITCService tCService, IPrescriptionInfoRepository prescriptionInfoRepository, IDicMedicineRepository dicMedicineRepository, ILogger<PaymentService> logger, IVerifyCodeLogService verifyCodeLogService, IPubUserAddressRepository pubUserAddressRepository, ITencentService tencentService, ISysRepository sysRepository, IPubMessageService pubMessageService, IPubUserInfoRepository pubUserInfoRepository)
        {
            _linKingService = linKingService;
            _onlineOrderRepository = onlineOrderRepository;
            _configurtaion = configurtaion;
            _onlineRefundRepository = onlineRefundRepository;
            _pubPatInfoRepository = pubPatInfoRepository;
            _onlineAptInfoRepository = onlineAptInfoRepository;
            _tCService = tCService;
            _prescriptionInfoRepository = prescriptionInfoRepository;
            _dicMedicineRepository = dicMedicineRepository;
            _logger = logger;
            _verifyCodeLogService = verifyCodeLogService;
            _pubUserAddressRepository = pubUserAddressRepository;
            _tencentService = tencentService;
            _sysRepository = sysRepository;
            _pubMessageService = pubMessageService;
            _pubUserInfoRepository = pubUserInfoRepository;
            _onlineOrderSourceRepository = onlineOrderSourceRepository;
        }


        public BaseResponse<string> OrderPay(PayInfo info)
        {
            LcTradeH5PayParam param = new LcTradeH5PayParam();
            param.biz_Content = new Biz_Content();
            var order = _onlineOrderSourceRepository.GetOrderSource(info.OrderNo);
            if (order == null)
            {
                throw new BaseException("参数错误:订单号错误", DetailedStatusCode.Fail);
            }
            if (order.OrderStatus != 1)
            {
                throw new BaseException("订单状态错误,无法支付", DetailedStatusCode.Fail);
            }
            var desc = "";
            if (order.AptType == 1)
            {
                desc = "有赞会员";
            }
            
            param.biz_Content.Body = desc;
            param.biz_Content.Subject = desc;
            param.biz_Content.Notify_Url = _configurtaion.GetSetDomain + "apt/api/payment/PerfPayInfoByNo";
            param.biz_Content.Out_Trade_No = order.OrderNo;
            param.biz_Content.Return_Url = "";//TODO 跳有赞的H5
            param.biz_Content.Timeout_Express = "30m";
            param.biz_Content.Total_Amount = order.PayPrice.ToString();
            var response = _linKingService.LcTradeH5Pay(param);
            return response;
        }

        public BaseResponse<LcTradeAPPPayModel> OrderAPPPay(AppPayInfo info)
        {
            LcTradeAPPPayParam param = new LcTradeAPPPayParam();
            param.biz_Content = new Biz_Content4();
            var order = _onlineOrderRepository.GetOrderByNo(info.OrderNo);
            if (order == null)
            {
                throw new BaseException("参数错误:订单号错误", DetailedStatusCode.Fail);
            }
            if (order.PayWay != info.PayWay)
            {
                _onlineOrderRepository.UpdateOrderPayWay(order.OrderNo, info.PayWay);
                order.PayWay = info.PayWay;
            }
            if (order.OrderStatus != 1)
            {
                throw new BaseException("订单状态错误,无法支付", DetailedStatusCode.Fail);
            }
            var desc = "";
            if (order.AptType == 1)
            {
                desc = "视频咨询";
            }
            if (order.AptType == 2)
            {
                desc = "复诊开药";
            }
            if (order.AptType == 3)
            {
                desc = "处方开药";
                if (info.AddressID != 0)
                {
                    var addr = _pubUserAddressRepository.GetAddressForId(info.AddressID);
                    _prescriptionInfoRepository.UpdateReceipt(order.AptId, addr.ReceiveName, addr.ReceivePhone, addr.Province + " " + addr.City + " " + addr.Area + "|" + addr.Localization);
                    try
                    {
                        var openHelperId = _pubUserInfoRepository.GetMHelper("药助");
                        if (!string.IsNullOrEmpty(openHelperId))
                        {
                            List<int> ids = new List<int>();
                            ids.Add(order.AptId);
                            var pre = _prescriptionInfoRepository.GetPrescriptionForIds(ids).FirstOrDefault();
                            //_pubMessageService.SendOnlineWxMsg(pre.Appt_Number, openHelperId, "您有一笔待发货的处方订单", "请及时前往[互联网医院工作站]去处理");
                        }
                    }
                    catch (System.Exception e) { }
                }
            }
            param.biz_Content.payment_type = order.PayWay;
            param.biz_Content.Body = desc;
            param.biz_Content.Subject = desc;
            param.biz_Content.Notify_Url = _configurtaion.GetSetDomain + "apt/api/payment/appperfpayinfobyno";
            param.biz_Content.Out_Trade_No = order.OrderNo;
            param.biz_Content.Timeout_Express = "30m";
            param.biz_Content.Total_Amount = order.PayPrice.ToString();
            var response = _linKingService.LcTradeAPPPay(param);
            if (response.Data != null)
            {
                response.Data.PayWay = order.PayWay;
            }
            return response;
        }



        private void SendGroupMessage(string groupId, string fromWho, Online_Order order)
        {
            var msg1 = new object();
            if (order.IsEnglish)
            {
                msg1 = new { messageType = "refundOrder", title = "online consultation cancel", content = "Your online consultation on 【" + Convert.ToDateTime(order.AptTime).ToString("MM月dd日") + "】 has cancelled", url = "OrderDetail?orderNo=" + order.OrderNo };
            }
            else
            {
                msg1 = new { messageType = "refundOrder", title = "预约取消", content = "您【" + Convert.ToDateTime(order.AptTime).ToString("MM月dd日") + "】的问诊已取消", url = "OrderDetail?orderNo=" + order.OrderNo };
            }
            _tencentService.SendCusMsgToGroup(groupId, fromWho, JsonConvert.SerializeObject(msg1));
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public BaseResponse<LcTradeQueryModel> LcTradeQuery(LcTradeQueryParam param)
        {
            #region
            string gatewayurl = "https://openapicore.linkingcloud.cn/gateway";
            string appId = "LCOP20200816150536373";
            string privateKey = "MIICWwIBAAKBgQCwoapOaIu0KnilAyfQDMg2u+5wvjuZsnIct/jC7LgY9nmFO85h+kLa1r2JvhZIWELgE8vsdUgBwqoCDkgeZIBfx20DMCq/PeZb0+896EW9wZtkQP0LDCppgBqsWsPZ/QIaUajX10Q8uvFM5Ew9y0hQBfaWRc5UUVcCNeOW6dw2QwIDAQABAoGAMNPwJY7HF/4prcwqhFwUOPVI3Afqp/lpjEDbVt9joRr5yvgWfIVXV/HHIb3XoRYtHo66b9qYFkx+/OR/0U8NIXdtTNwXb0oihrGsRevyjoLvzJrG444LnNlNbsRpELHlAXvr30rEy9xwcNZRE/elt2QaQLgNk75Go3ziYtaKmBECQQDeBK5hVh9qL8dJWFoPeOdrqpXDKW24W2nSL3nEPogw99JMiJPux4jYnvYsERfpPFDJp0ZszUsyMmSwgA2tR3KrAkEAy6qZQ5mN0R2mTOkprRLyGEywVEMgdUuS2TIzpmQ9I5UCDCTP7l02F5bBDdzAyLcvmz4hw6J9/v20H0xzctmKyQJABsWfyApHdQa2Dm+qd5RZgrg2TzihRyFKrgWSskCyCMRWXs0/reXaL7lRivCOiSe00yHODR2J8KMG3Tdas3FddwJAfPvSVjOzXfMODQDBPJ71xoe5ZdxT3Odl1LgEDkZRZraYrQ8iMysseMlg67re683O/zvfyIi9PXA/yz1FU+PAUQJAWPynDQTIQNViwptuxVZsQUeC1//hHiUxdh3+rmY662hQzc4KVbXuhDRhIt73DJSB1bLsJwmQuoH5MEwyyEgSBA==";
            string publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGncH9TmDGpqBy6MhH5j4eyR+jL8R5FF2Fzp7AR3dmlO/G3KRvqOexLm8xfyydaV0oF5e+t4j+b4sIksg72VkX3+aFLF0rIPoUx80sOCYsbs4ng3ohWKc4x4xixp7TIbSe5x+eVlw9yqGULIrmmISlv0emFyJSuXYoXDzjPeKn+wIDAQAB";
            LopSdk.LopSdkClient lopClient = new LopSdk.LopSdkClient(gatewayurl, appId, privateKey, publicKey);
            //ht["out_trade_no"] = "GH2020082320000006768789568";
            string bizContent = JsonConvert.SerializeObject(param);
            string response_text = lopClient.InvokeMethod("lc.trade.query", bizContent);
            #endregion
            var _CityList = JsonConvert.DeserializeObject<LcTradeQueryModel>(response_text);
            var resu = new BaseResponse<LcTradeQueryModel>();

            if (_CityList != null)
            {
                resu.Code = 1;
                resu.Msg = "成功";
                resu.Data = _CityList;
            }
            else
            {
                resu.Code = 0;
                resu.Msg = "未找到数据";
            }
            return resu;
        }


        private string GetRandoms(int leng)
        {
            Random random = new Random();
            var retStr = string.Empty;
            for (int i = 0; i < leng; i++)
            {
                retStr += random.Next(0, 9);
            }
            return retStr;
        }

        public BaseResponse UpdateReVisitStatus(UpdateReVisitReq model)
        {
            return new BaseResponse();
        }

        public BaseResponse PrescriptionSign(PrescriptionParam model)
        {
            BaseResponse res = new BaseResponse();
            var ret = _prescriptionInfoRepository.PrescriptionSign(model.PrescriptionNo, 1024);
            if (ret > 0)
            {
                res.Code = 1;
                res.Msg = "推送成功";
            }
            return res;
        }

        public BaseResponse<List<LKDrugs>> GetMedicineList()
        {
            BaseResponse<List<LKDrugs>> res = new BaseResponse<List<LKDrugs>>();
            var mlist = _dicMedicineRepository.GetMedicineList();
            if (mlist != null)
            {
                res.Code = 1;
                res.Msg = "获取成功";
                res.Data = mlist;
            }
            else
            {
                res.Code = 0;
                res.Msg = "获取失败";
                res.Data = new List<LKDrugs>();
            }
            return res;
        }

        public BaseResponse ConfirmPrescriptionOrder(PrescriptionOrderReq model)
        {
            BaseResponse res = new BaseResponse();
            var result = _linKingService.IFConfirmPrescriptionOrder(model);
            if (result.IsSuccess)
            {
                res.Code = 1;
                res.Msg = "推送成功";
            }
            return res;
        }



    }
}
