using Com.Bocom.OpenApi;
using Kivii;
using Kivii.Finances.Entities;
using Kivii.Linq;
using Kivii.Web;
using Njzj.Bocoms.Openapis.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Njzj.Bocoms.Openapis
{
    public class SettlementGenerateReceiveCode : RestfulExecution<Settlement>
    {
        public List<Guid> SettlementKvids { get; set; }

        public string View { get; set; }

        public override object OnExecution(IRequest req, IResponse res)
        {
            SettlementKvids.ThrowIfNullOrEmpty("请传入要收款的结算!");
            var conn = KiviiContext.GetOpenedDbConnection<Settlement>();
            var settlements = conn.SelectByIds<Settlement>(SettlementKvids);
            settlements.ThrowIfNullOrEmpty("未找到要收款的结算信息");
            var rtns = new RestfulExecutionResponse<MPNG020702ResponseV1>();
            rtns.Results = new List<MPNG020702ResponseV1>();
            try
            {
                var results = Extension.GenerateReceiveCode(settlements);
                var payMerTranNo = results.rsp_body.pay_mer_tran_no;

                var order = Extension.GetReceiveCodeOrder(payMerTranNo, settlements);
                order.pay_mer_tran_no = payMerTranNo;
                order.display_code_text = results.rsp_body.display_code_text;

                var connB = KiviiContext.GetOpenedDbConnection<ReceiveCode>();
                var item = new ReceiveCode();
                item.trans_code = results.rsp_head.trans_code;
                item.response_code = results.rsp_head.response_code;
                item.response_status= results.rsp_head.response_status;
                item.response_time= results.rsp_head.response_time;
                item.response_msg= results.rsp_head.response_msg;
                item.shop_id = results.rsp_body.shop_id;
                item.pay_mer_tran_no= payMerTranNo;
                item.display_code_text = results.rsp_body.display_code_text;

                item.tran_state = order.rsp_body.tran_state;
                item.tran_state_code = order.rsp_body.tran_state_code;
                item.tran_state_msg = order.rsp_body.tran_state_msg;
                item.mer_memo= order.rsp_body.mer_memo;
                item.total_amount= order.rsp_body.total_amount;
                item.order_status= order.rsp_body.order_status;
                item.tran_content= order.rsp_body.tran_content;
                connB.Insert(item);

                if (View.IsNullOrEmpty())
                {
                    rtns.Results.Add(order);
                    return rtns;
                }
                else
                {
                    return new HttpResult
                    {
                        Response = order,
                        View = View
                    };
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
