using System;
using System.Collections.Generic;
using Aop.Api;
using Library;
using Microsoft.AspNetCore.Http;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Util;
using MySystem.Models;
using System.Linq;

namespace MySystem
{
    public class AlipayFunctionForHD
    {
        public readonly static AlipayFunctionForHD Instance = new AlipayFunctionForHD();
        private AlipayFunctionForHD()
        { }

        // public string Pid = "2088720140260314";
        private string AppId = "2021004109682585";
        private string PrivateKey = "MIIEpAIBAAKCAQEAvf75JGQL9IDg8xu2C6qWrIO3H4roSwpvwUeh6y2kQ8iH0gqQXlyLj13ku8pzY1H9JTSeARCsHSD/VJFxMoPOBO+/xGDV3CSdxhOE5Fu5E30ZZMA5XmnMKyN8q+MEh7refGuCmldedTmzr9mNw4HDjS1uqJoqYRl3eUEaC/Syl620iiaSh7Q9/rsT/qNcnP5hO9P3DWionNt78elmjLt0sBdBkQ10o2XwC5RuzBfP8DCBEdL/DPOOE4vtmLP1IdDI7qtjBhX8PdL+/IRxe/4OGvYSPnHW7JNlN970h2UN5i0Yu0AkidJvlS59nX9C1WJ4U37HiMnkMNXLB/Ubi5BkgQIDAQABAoIBAQC1itVKpWIa/a5z/Q2EtjqEmtK2jAcL9Ov11dlsm07zCcBlvXxW/bzIf6IYogiBZY0qKM21HNYoeygeCV8NMo3/f4pQPWr7j+1Fn88CWHZOneFOuLHYeeUBb0YoA6KHgtImNqAzk7oI7tq383uWzP4qfrfW2IAYCbp0HPWjaOvhKw7qrejcTPW0oCsPjm6nkjzW6FzjkPCwiiivvpC67EzpXKF8HnYyF1KMEuH6h7qZl4jtloW8CkgkwnBhc9iYhN/ygllYdPU9aRdThG7tFVCHft7cIq5F54pJoUm/ML3fpdVjFDAVGZFbkZyg4gkIYCLIEgTVt2W4Lfr8/61PimC1AoGBAOAt7Un2B3ouxN/31Z8ApcTL9QfElPcepTfKhwUDI+KRlygele1r7bIzlDgYVVrMSzzkoYD1vb0scc3hO1EBvURM9BbJJHRl9qncDbF0BPiznm688G26jNwLSn5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vYSPnHW7JNlN970h2UN5i0Yu0AkidJvlS59nX9C1WJ4U37HiMnkMNXLB/Ubi5BkgQIDAQAB";
        public string AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiXVtTk6opnYllnH/X40k/jSw/82WZ+lGbYQLYH/nVONFJ7Gr9C/dlKpJFIbS+vNDn+YLtM923KmEVSgf8zU0WrTkRjWvKEiyLswWZVqSZW5Jfon1e2SfjNrAVi6XBZa7urAItKQsdD2vFFuyG/ohlXBL103xC1wnjvECD/iholoruEFOLyfobJKTY/6iyrKeOElem1V7OWl6gdjG2oozj3nbVZhtkQvPJECYlolH96eK2mieTkFK82aZ5Tdzx1LPk/3hxRAmzz/9X7xfXdOly88hKBmW8LC9RhTlOWbrXJhhFz13A4brnbnOiY/X7b2OkAYifammc2uh0AIJlCmBTQIDAQAB";
        //"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";


        #region 商家认证申请单提交
        public string AuthOrderCreate(MerchantAddInfo info, string MerToken)
        {            
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayMerchantIndirectAuthorderCreateRequest request = new AlipayMerchantIndirectAuthorderCreateRequest() ;
            string out_biz_no = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
            string identity_type = info.SubjectType;
            if(identity_type == "SUBJECT_TYPE_ENTERPRISE") identity_type = "ENTERPRISE";
            if(identity_type == "SUBJECT_TYPE_INDIVIDUAL") identity_type = "IND_BIZ";
            if(identity_type == "SUBJECT_TYPE_SMALL") identity_type = "MSE";
            string PeriodEnd = info.PeriodEnd.Value.ToString("yyyy-MM-dd");
            if(PeriodEnd.Substring(0, 4) == "2050")
            {
                PeriodEnd = "forever";
            }
            string CardPeriodEnd = info.CardPeriodEnd.Value.ToString("yyyy-MM-dd");
            if(CardPeriodEnd.Substring(0, 4) == "2050")
            {
                CardPeriodEnd = "forever";
            }
            string BizContent = "{" +
            "  \"out_biz_no\":\"" + out_biz_no + "\"," +
            "  \"contact_person_info\":{" +
            "    \"contact_name\":\"" + info.CertLegalPerson + "\"," +
            "    \"contact_phone_no\":\"" + info.MobilePhone + "\"," +
            "    \"contact_card_no\":\"" + info.IdCardNumber + "\"," +
            "    \"contact_cert_type\":\"RESIDENT\"" +
            "  }," +
            "  \"auth_identity_info\":{" +
            "    \"identity_type\":\"" + identity_type + "\"," +
            "    \"is_financial_org\":false," +
            "    \"certificate_type\":\"BUSINESS_CERT\"," +
            "    \"certificate_info\":{" +
            "      \"cert_type\":\"UNIT_SOCIAL_CREDIT\"," +
            "      \"cert_no\":\"" + info.LicenseNumber + "\"," +
            "      \"cert_image\":\"" + UploadPic(info.LicenseCopy) + "\"," +
            "      \"merchant_name\":\"" + info.CertMerchantName + "\"," +
            "      \"legal_person_name\":\"" + info.CertLegalPerson + "\"," +
            "      \"register_address\":\"" + info.BizAddressCode.Replace(",", "") + info.BizStoreAddress + "\"," +
            "      \"effect_time\":\"" + info.PeriodBegin.Value.ToString("yyyy-MM-dd") + "\"," +
            "      \"expire_time\":\"" + PeriodEnd + "\"" +
            "    },";
            if(info.SubjectType == "SUBJECT_TYPE_SMALL")
            {
                string bizAddressCode = info.BizAddressCode;
                string province_code = "", city_code = "", district_code = "";
                string province = "", city = "", district = "";
                WebCMSEntities db = new WebCMSEntities();
                OpenBankCityTable cityItem = db.OpenBankCityTable.FirstOrDefault(m => m.CityName.EndsWith(bizAddressCode));
                if(cityItem != null)
                {
                    district_code = cityItem.Code;
                    city_code = district_code.Substring(0, 4) + "00";
                    province_code = district_code.Substring(0, 2) + "0000";
                    string[] CityNames = cityItem.CityName.Split(',');
                    district = CityNames[CityNames.Length - 3];
                    city = CityNames[CityNames.Length - 2];
                    province = CityNames[CityNames.Length - 1];
                }
                BizContent += "    \"support_credentials\":{" +
                "      \"merchant_type\":\"STORE\"," +
                "      \"store_name\":\"" + info.BizStoreName + "\"," +
                "      \"province_code\":\"" + province_code + "\"," +
                "      \"province\":\"" + province + "\"," +
                "      \"city_code\":\"" + city_code + "\"," +
                "      \"city\":\"" + city + "\"," +
                "      \"district_code\":\"" + district_code + "\"," +
                "      \"district\":\"" + district + "\"," +
                "      \"store_address\":\"" + info.BizStoreAddress + "\"," +
                "      \"store_door_img\":\"" + UploadPic(info.StoreEntrancePic.Split(',')[0]) + "\"," +
                "      \"store_inner_img\":\"" + UploadPic(info.IndoorPic.Split(',')[0]) + "\"" +
                "    }";
            }
            BizContent += "  }," +
            "  \"legal_person_info\":{" +
            "    \"legal_type\":\"LEGAL_PERSON\"," +
            "    \"card_type\":\"RESIDENT\"," +
            "    \"person_name\":\"" + info.CertLegalPerson + "\"," +
            "    \"card_no\":\"" + info.IdCardNumber + "\"," +
            "    \"effect_time\":\"" + info.CardPeriodBegin.Value.ToString("yyyy-MM-dd") + "\"," +
            "    \"expire_time\":\"" + CardPeriodEnd + "\"," +
            "    \"card_front_img\":\"" + UploadPic(info.IdCardCopy) + "\"," +
            "    \"card_back_img\":\"" + UploadPic(info.IdCardNational) + "\"," +
            "    \"is_benefit_person\":true" +
            "  }" +
            "}";
            request.BizContent = BizContent;
            LogHelper.Instance.WriteLog(BizContent, "商家认证申请单提交异常");

            string result = "";
            try
            {
                AlipayMerchantIndirectAuthorderCreateResponse response = client.Execute(request, null, MerToken);
                result = response.Body;
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "商家认证申请单提交异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region 查询商家认证申请单状态
        public string AuthOrderQuery(string OrderNo)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayMerchantIndirectAuthorderQuerystatusRequest request = new AlipayMerchantIndirectAuthorderQuerystatusRequest();
            request.BizContent = "{" +
            "  \"order_no\":\"" + OrderNo + "\"" +
            "}";
            LogHelper.Instance.WriteLog(request.BizContent, "查询商家认证申请单状态");

            string result = "";
            try
            {
                AlipayMerchantIndirectAuthorderQuerystatusResponse response = client.Execute(request);
                result = response.Body;
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "查询商家认证申请单状态异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region 图片上传

        public string UploadPic(string path)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            string fileName = path.Substring(path.LastIndexOf("/") + 1);
            string imageBase64 = function.imageToBase64String(function.getPath(path));
            // imageBase64 = imageBase64.Substring(imageBase64.IndexOf(";base64,") + 8);
            AntMerchantExpandIndirectImageUploadRequest request = new AntMerchantExpandIndirectImageUploadRequest();
            FileItem imageContent = new FileItem(fileName,Convert.FromBase64String(imageBase64));
            request.ImageContent = imageContent;
            request.ImageType = "jpg";
            AntMerchantExpandIndirectImageUploadResponse response = client.Execute(request);
            return fileName;
        }

        #endregion






    }
}
