
from odoo import http
from odoo.http import request
from werkzeug import urls
import datetime
import json

import pytz
from odoo.addons.payment_spgateway.controllers.main import SpGatewayController

class PayWithController(SpGatewayController):
    '''
    將超商取號所得到的號碼寫入
    '''
    @http.route('/payment/spgateway/get_number', type='http', auth="none", methods=['POST', 'GET'], csrf=False)
    def return_post_number(self, **post):
        if not post:
            return '接受POST失敗，請洽技術人員'
        else:
            AES_value = post['TradeInfo']
            RSA_value = post['TradeSha']
            if self.check_RSA(AES_value, RSA_value):
                provider = request.env['payment.acquirer'].search([('provider', '=', 'spgateway')])
                hashKEY = provider.sp_HashKey
                hashIV = provider.sp_HashIV
                decode_data = self.aes_cbc_decrypt(hashKEY.encode('utf-8'), hashIV.encode('utf-8'), AES_value)
                json_value = json.loads(decode_data)

                if json_value.get('Status') == 'SUCCESS':
                    # Result加入狀態 = 成功
                    json_value['Result']['Status'] = 'SUCCESS'
                    json_value['Result']['Message'] = json_value['Message']
                    request.env['payment.transaction'].sudo().form_feedback(json_value['Result'], 'spgateway')
                    tw = pytz.timezone('Asia/Taipei')
                    now = datetime.datetime.now(tz=tw)
                    json_value['Result']['now'] = now.strftime("%Y-%m-%d %H:%M:%S")
                    return request.render("sale_order_to_invoice.convenience_store_code_template", json_value['Result'])
                else:
                    return '串接失敗，請洽技術人員'


    '''
    轉送用的網頁，將銷售訂單中按鈕所彈出的網頁，並以post的方式串接資料給智付通
    '''
    @http.route('/pay_with_spgateway', type='http', website=True, auth="public")
    def call_payment_by_button(self, **kwargs):

        base_url = request.env['ir.config_parameter'].sudo().get_param('web.base.url')
        # 從session取得order id
        order_id = int(request.session.get('payment_order_id'))
        # 從session取得installment id
        installment_id = int(request.session.get('payment_installment_id'))
        # 從session取得installment id
        Customize = request.session.get('payment_Customize')

        sale_order = request.env['sale.order'].sudo().browse(order_id)
        installment = request.env['installment'].sudo().browse(installment_id)
        # 驗證是否有找到該訂單
        if len(sale_order) != 1:
            return '驗證錯誤，沒有找到欲支付的銷售訂單!'
        # 驗證是否有找到該繳費方式
        if len(installment) != 1:
            return '驗證錯誤，沒有找到欲支付的繳費方式!'
        # 組合唯一的訂單參照
        reference = sale_order.name + installment.refence
        # 轉換字串成時間物件
        expiredate = datetime.datetime.strptime(installment.payment_date, '%Y-%m-%d')
        # 抓取必要的資料
        values = {
            'reference': reference,
            'billing_partner_email': 'erp@jptip.com.tw',
            'amount': int(installment.payment),
            'item_name': 'JPTIP繳費',
            'ExpireDate': datetime.datetime.strftime(expiredate, '%Y%m%d'),
            'CustomerURL': '%s' % urls.url_join(base_url, '/payment/spgateway/get_number'),
            'Customize': Customize
        }
        # 找到支付的銀行(智付通)
        acquirer = request.env['payment.acquirer'].sudo().search([('provider', '=', 'spgateway')], limit=1)
        # 產生需要post的資料
        res = acquirer.spgateway_form_generate_values(values)

        # 搜尋銷售訂單的"交易"
        tx = request.env['payment.transaction'].sudo().search([('reference', '=', reference)], limit=1)
        # 沒有的話就新建一筆
        if len(tx) == 0:
            tx = request.env['payment.transaction'].sudo().create({
                'amount': int(installment.payment),
                'acquirer_id': acquirer.id,
                'currency_id': sale_order.pricelist_id.currency_id.id,
                'partner_country_id': sale_order.partner_id.country_id.id,
                'reference': reference,
                'partner_id': sale_order.partner_id.id,
                'sale_order_id': sale_order.id,
                'installment_id': installment.id
            })
            # 將"交易"與銷售訂單關聯
            sale_order.payment_tx_id = tx.id

        return request.render("sale_order_to_invoice.pay_with_spgateway_template", res)
