using Com.Bocom.OpenApi.Utils;
using Com.Bocom.OpenApi;
using Kivii.Web;
using Kivii;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kivii.Linq;
using Kivii.Text;

namespace Njzj.Bocoms.Openapis.Transforms
{
    public class WriteOffResultNotifyCallBack : RestfulExecution<WriteOffResultNotify>
    {
        public string biz_content { get; set; }
        public string msg_id { get; set; }
        public string timestamp { get; set; }
        public string encrypt_key { get; set; }
        public string sign { get; set; }
        public override object OnExecution(IRequest req, IResponse res)
        {
            Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
            Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
            var rtns = new RestfulExecutionResponse<WriteOffResultNotify>();
            rtns.Results = new List<WriteOffResultNotify>();

            if (biz_content.IsNullOrEmpty()) return rtns;
            if (msg_id.IsNullOrEmpty()) return rtns;
            if (timestamp.IsNullOrEmpty()) return rtns;
            if (encrypt_key.IsNullOrEmpty()) return rtns;
            if (sign.IsNullOrEmpty()) return rtns;
            var dic = new Dictionary<string, string>();
            dic.Add("biz_content", biz_content);
            dic.Add("msg_id", msg_id);
            dic.Add("timestamp", timestamp);
            dic.Add("encrypt_key", encrypt_key);
            dic.Add("sign", sign);
            Console.WriteLine("------------------------------------WriteOffResultNotifyCallBack-----------------------------------------");
            Console.WriteLine("------------------------------------Start-----------------------------------------");
            try
            {
                var result = ApiUtils.ParseCommunicationJsonWithBocomSign(dic, "utf-8", Configs.priKeyZhjz, Configs.pubKeyZhjz);

                var conn = KiviiContext.GetOpenedDbConnection<WriteOffResultNotify>();
                conn.InitEntityType<EntityLog<WriteOffResultNotify>>();
                //var log = conn.Single<EntityLog<WriteOffResultNotify>>(o => true);
                //if (log == null) return rtns;

                result.BillId = result.biz_content.bill_id;
                if (Guid.TryParse(result.biz_content.cont_id, out var bizKvid))
                {
                    result.BizKvid = bizKvid;
                }
                conn.Insert(result);

                var resp = "{\"rsp_code\":\"0\",\"biz_state\":\"S\",\"rsp_msg\":\"核销处理成功\"}";

                //var rspBizContent = "{\"rsp_head\":{\"response_msg\":\"非白名单客户\",\"response_code\":\"CIPP0004MT0017\"},\"rsp_body\":{\"context_no\":\"P21201026566300000019\",\"account_exist_flag\":\"EF00\"}";
                var rsp = ApiUtils.SignRspBizContent(resp, result.encrypt_key, Configs.priKeyZhjz);
                rtns.Results.Add(result);
                return rsp;
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                Console.WriteLine("------------------------------------WriteOffResultNotifyCallBack-----------------------------------------");
                Console.WriteLine("------------------------------------End-----------------------------------------");
                Console.WriteLine("-----------------------------------------------------------------------------------------------------");
                Console.WriteLine("-----------------------------------------------------------------------------------------------------");
            }

        }
    }

    [RequiresAnyRole(SystemRoles.Everyone)]
    public class WriteOffResultResponseV2Request : RestfulExecution<WriteOffResultResponseV2>
    {
        public string BillId { get; set; }
        public string WriteOffNo { get; set; }
        public string WriteOffDate { get; set; }
        public override object OnExecution(IRequest req, IResponse res)
        {
            //BillId.ThrowIfNullOrEmpty("请传入订单号");
            DefaultBocomClient client = new DefaultBocomClient(Configs.appIdZhjz, Configs.priKeyZhjz, Configs.pubKeyZhjz);

            //测试环境可以忽略SSL证书告警，生产环境不可忽略
            //client.IgnoreSslHostnameVerifier();
            WriteOffResultRequestV2 request = new WriteOffResultRequestV2();
            request.SetServiceUrl(Configs.basicUrlZhjz + Configs.WriteOffResultRequestV2);
            WriteOffResultRequestV2.WriteOffResultRequestV2Biz bizContent = new WriteOffResultRequestV2.WriteOffResultRequestV2Biz();
            bizContent.org_id = Configs.ORG_ID;
            bizContent.bill_id = BillId;
            //bizContent.subOrgId = Configs.SUB_ORG_ID;
            bizContent.write_off_dte = WriteOffDate;
            bizContent.write_off_no = WriteOffNo;
            bizContent.pageablerequest_pagenum = "1";
            bizContent.pageablerequest_pagesize = "10";
            request.SetBizContent(bizContent);
            var response = client.Execute(request, Guid.NewGuid().ToString().Replace("-", ""));

            var rtns = new RestfulExecutionResponse<WriteOffResultResponseV2>();
            rtns.Results = new List<WriteOffResultResponseV2>();
            if (response.IsSuccess())
            {
                var resp = response as WriteOffResultResponseV2;
                rtns.Results.Add(resp);
            }
            else
            {
                throw new Exception($"ReturnCode:{response.GetRspCode()}{Environment.NewLine}ReturnMsg:{response.GetRspMsg()}");
            }
            return rtns;
        }
    }

    [RequiresAnyRole(SystemRoles.Everyone)]
    public class UnWriteOffResponseV1Request : RestfulExecution<UnWriteOffResponseV1>
    {
        public string BillId { get; set; }
        public override object OnExecution(IRequest req, IResponse res)
        {
            BillId.ThrowIfNullOrEmpty("请传入订单号");
            DefaultBocomClient client = new DefaultBocomClient(Configs.appIdZhjz, Configs.priKeyZhjz, Configs.pubKeyZhjz, BocomConstants.ENCRYPT_TYPE_RSA_AND_AES);

            //测试环境可以忽略SSL证书告警，生产环境不可忽略
            //client.IgnoreSslHostnameVerifier();
            var request = new UnWriteOffRequestV1();
            request.SetServiceUrl(Configs.basicUrlZhjz + Configs.DelContractOrderRequestV1);

            var bizContent = new UnWriteOffRequestV1.UnWriteOffRequestV1Biz();
            bizContent.org_id = Configs.ORG_ID;
            bizContent.bill_id = BillId;
            request.SetBizContent(bizContent);
            var response = client.Execute(request, Guid.NewGuid().ToString().Replace("-", ""));

            var rtns = new RestfulExecutionResponse<UnWriteOffResponseV1>();
            rtns.Results = new List<UnWriteOffResponseV1>();
            if (response.IsSuccess())
            {
                var resp = response as UnWriteOffResponseV1;
                rtns.Results.Add(resp);
            }
            else
            {
                throw new Exception($"ReturnCode:{response.GetRspCode()}{Environment.NewLine}ReturnMsg:{response.GetRspMsg()}");
            }
            return rtns;
        }
    }

    [RequiresAnyRole(SystemRoles.Everyone)]
    public class QueryContractOrderResponseV2Request : RestfulExecution<QueryContractOrderResponseV2>
    {
        public string BillId { get; set; }
        public override object OnExecution(IRequest req, IResponse res)
        {
            BillId.ThrowIfNullOrEmpty("请传入订单号");
            DefaultBocomClient client = new DefaultBocomClient(Configs.appIdZhjz, Configs.priKeyZhjz, Configs.pubKeyZhjz, BocomConstants.ENCRYPT_TYPE_RSA_AND_AES);
            /**
   * 测试环境可以忽略SSL证书告警，生产环境不可忽略
   */
            client.IgnoreSslHostnameVerifier();

            var request = new QueryContractOrderRequestV2();
            request.SetServiceUrl(Configs.basicUrlZhjz + Configs.QueryContractOrderRequestV2);

            var bizContent = new QueryContractOrderRequestV2.QueryContractOrderRequestV2Biz();
            bizContent.setOrgId(Configs.ORG_ID);
            bizContent.setBillId(BillId);
            request.SetBizContent(bizContent);
            var json = JsonSerializer.SerializeToString(request);
            var response = client.Execute(request, Guid.NewGuid().ToString().Replace("-", ""));

            var rtns = new RestfulExecutionResponse<QueryContractOrderResponseV2>();
            rtns.Results = new List<QueryContractOrderResponseV2>();
            if (response.IsSuccess())
            {
                var resp = response as QueryContractOrderResponseV2;
                rtns.Results.Add(resp);
            }
            else
            {
                throw new Exception($"ReturnCode:{response.GetRspCode()}{Environment.NewLine}ReturnMsg:{response.GetRspMsg()}");

            }
            return rtns;
        }
    }


    [RequiresAnyRole(SystemRoles.Everyone)]
    public class WriteOffResultNotifyQuery : RestfulQuery<WriteOffResultNotify>
    {
    }
}
