# -*- coding: utf-8 -*-

from odoo import models, fields, api
from ecpay_invoice.ecpay_main import *
from odoo.exceptions import UserError


class InvalidInvoice(models.TransientModel):
    _name = 'invalid.invoice'

    reason = fields.Char(string='作廢原因', required=True)

    # 準備基本電子發票商家參數
    def demo_invoice_init(self, ecpay_invoice):
        # 判斷設定是否為測試電子發票模式
        url = 'https://einvoice.ecpay.com.tw/Invoice/IssueInvalid'
        ecpay_demo_mode = self.env['ir.config_parameter'].sudo().get_param('ecpay_invoice_tw.ecpay_demo_mode')
        if ecpay_demo_mode:
            url = 'https://einvoice-stage.ecpay.com.tw/Invoice/IssueInvalid'

        ecpay_invoice.Invoice_Method = 'INVOICE_VOID'
        ecpay_invoice.Invoice_Url = url
        ecpay_invoice.MerchantID = self.env['ir.config_parameter'].sudo().get_param('ecpay_invoice_tw.ecpay_MerchantID')
        ecpay_invoice.HashKey = self.env['ir.config_parameter'].sudo().get_param('ecpay_invoice_tw.ecpay_HashKey')
        ecpay_invoice.HashIV = self.env['ir.config_parameter'].sudo().get_param('ecpay_invoice_tw.ecpay_HashIV')

    def run_invoice_invalid(self):
        # 建立物件
        invoice = EcpayInvoice()

        # 初始化物件
        self.demo_invoice_init(invoice)


        # 取得當前Odoo發票
        target_invoice = self.env['account.invoice'].browse(self.env.context.get('active_ids', []))

        # 檢查是否有開立電子發票
        if target_invoice.ecpay_invoice_id:
            if target_invoice.ecpay_invoice_id.IIS_Invalid_Status == '1':
                raise UserError('該電子發票：%s 已作廢!!' % target_invoice.ecpay_invoice_id.name)
        else:
            raise UserError('找不到電子發票!!')

        # 設定電子發票作廢需要參數
        invoice.Send['InvoiceNumber'] = target_invoice.ecpay_invoice_id.name
        invoice.Send['Reason'] = self.reason

        # 送出資訊
        aReturn_Info = invoice.Check_Out()


        # 判定是否成功作廢
        if aReturn_Info['RtnCode'] != '1':
            raise UserError('作廢電子發票失敗!!錯誤訊息：' + aReturn_Info['RtnMsg'])

        # 更新儲存在Odoo中的電子發票資訊
        target_invoice.ecpay_invoice_id.get_ecpay_invoice_info()

        # 更新發票狀態
        target_invoice.uniform_state = 'invalid'
