<?php 
namespace app\common\payment; 

use think\facade\Db;

use app\common\payment\BasePayment;
use app\common\payment\Ipayment;

use Ecpay\Sdk\Factories\Factory;
use Ecpay\Sdk\Services\UrlService;

//實作金流串接介面
class EcpayCVS extends BasePayment implements Ipayment{ 
    private $api_url;
    private $MerchantId;
    private $HashIv;
    private $HashKey;

    public function __construct()
    {
        $payment = Db::name('payment')
            ->where('pay_code', 'ecatm')
            ->find();

        if ($payment['is_test'] == 0) {
            $this->api_url = 'https://payment-stage.ecpay.com.tw';
            $this->MerchantId = '2000132';
            $this->HashIv = 'v77hoKGq4kWxNNIS';
            $this->HashKey = '5294y06JbISpM5x9';
        } else {
            $config = json_decode($payment['pay_config'], true);
            if (empty($config['MerchantId']) || empty($config['HashIv']) || empty($config['HashKey'])) {
                throw new \Exception('請先設定綠界金流參數');
            }
            $this->api_url = 'https://payment.ecpay.com.tw';
            $this->MerchantId = $config['MerchantId'];
            $this->HashIv = $config['HashIv'];
            $this->HashKey = $config['HashKey'];
        }
    }

    public function pay( $order ){
        $goods_list = '';
        foreach($order['goods_list'] as $goods){
            $goods_list .= $goods['goods_name']."#";
            //如果$goods_list結尾是#，則去掉
            if(substr($goods_list,-1) == '#'){
                $goods_list = substr($goods_list,0,-1);
            }
        }

        $factory = new Factory([
            'hashKey' => $this->HashKey,
            'hashIv' => $this->HashIv,
        ]);

        $autoSubmitFormService = $factory->create('ReturnSubmitFormWithCmvService');
        
        $input = [
            'MerchantID' => $this->MerchantId,
            'MerchantTradeNo' => $order['order_sn'],
            'MerchantTradeDate' => date('Y/m/d H:i:s'),
            'PaymentType' => 'aio',
            'TotalAmount' => $order['order_amount'],
            'TradeDesc' => UrlService::ecpayUrlEncode('Slash'),
            'ItemName' => $goods_list,
            'ChoosePayment' => 'CVS',
            'EncryptType' => 1,
            // 'OrderResultURL' => 'https://shop.h888.fun/appapi/v1/payment/response/paycode/eccvs/',
            // 'ClientBackURL' => 'https://shop.h888.fun/m/',
            'ReturnURL' => getUrl().'/appapi/v1/payment/callback/paycode/eccvs/',
            'ClientRedirectURL' => getUrl().'/appapi/v1/payment/response/paycode/eccvs/',
        ];
        
        $action = $this->api_url .'/Cashier/AioCheckOut/V5';
        
        $result = $autoSubmitFormService->generate($input, $action);

        return ['code'=>200,'method'=>'post','data'=>$result];        
    }
    
    public function response($data){
        $order_sn = $data['MerchantTradeNo'];

        if($data['RtnCode'] == '10100073'){
            $code = 200;
            $result['pay_status'] = '1';
            $result['pay_time'] = 0;
            $result['pay_data'] = json_encode($data);

        }else{
            $code = 500;
            $result['pay_status'] = '0';
            $result['pay_time'] = 0;
            $result['pay_data'] = json_encode($data);
        }

        Db::name('order_info')
        ->where('order_sn',$order_sn)
        ->update($result);

        $rtn = [
            'code' => $code,
            'paycode' => 'eccvs',
            'order_sn' => $order_sn,
            'ExpireDate' => $data['ExpireDate'],
            'PaymentNo' => $data['PaymentNo'],
            'TradeAmt' => $data['TradeAmt'],          
        ];

        return $rtn;
    }

    public function callback($data){
        $order_sn = $data['MerchantTradeNo'];

        $order = Db::name('order_info')
            ->where('order_sn', $order_sn)
            ->find();

        if ($data['RtnCode'] == 1) {

            $result['pay_status'] = '2';
            $result['pay_time'] = strtotime($data['PaymentDate']);
            $result['pay_data'] = json_encode($data);

            try {
                //更新訂單狀態
                Db::name('order_info')
                    ->where('order_sn', $order_sn)
                    ->update($result);

                //更新訂單操縱紀錄
                $order_action = [
                    'order_id' => $order['order_id'],
                    'action_user' => '綠界科技',
                    'order_status' => $order['order_status'],
                    'shipping_status' => $order['shipping_status'],
                    'pay_status' => '2',
                    'action_note' => '綠界金流CVS: ' . $data['PaymentType'] . '，付款成功',
                    'log_time' => time(),
                ];
                Db::name('order_action')->insert($order_action);
            } catch (\Exception $e) {
                throw new \Exception($e->getMessage());
            }
            $code = 200;
            $message = '付款成功';
        } else {
            $code = $data['RtnCode'];
            $message = $data['RtnMsg'];
            $result['pay_data'] = json_encode($data);
        }


        $rtn = [
            'code' => $code,
            'paycode' => 'eccvs',
            'msg' => $message,
            'order_sn' => $order_sn,
        ];

        return $rtn;        
    }
}
