<?php

namespace app\common\payment;

use think\facade\Db;

use app\common\payment\Ipayment;
use asc\line\LinePay as LinePayObj;

//實作金流串接介面
class LinePay implements Ipayment
{

    public function pay($order)
    {
        $product_list = [];
        foreach ($order['goods_list'] as $goods) {
            $product_list[] = [
                'name' => $goods['goods_name'],
                'quantity' => $goods['goods_number'],
                'price' => intval($goods['goods_price'])
            ];
        }

        $r_data = [
            'amount' => $order['order_amount'],
            'currency' => 'TWD',
            'orderId' => $order['order_sn'],
            'packages' => [
                [
                    'id' => $order['order_sn'],
                    'amount' => $order['goods_amount'],
                    'name' => 'SlashCard Store',
                    'products' => $product_list,
                ]
            ],
            'redirectUrls' => [
                'confirmUrl' => getUrl() . '/appapi/v1/payment/response/paycode/linepay/',
                'cancelUrl' => getUrl() . '/appapi/v1/payment/cancel/paycode/linepay/',
            ],
        ];
        $lp = new LinePayObj('1657811805', '53a912dfa167b5e767847c7e9fca4ea1');
        $result = $lp->request($r_data);

        if ($result['returnCode'] != '0000') {
            return ['code' => $result['returnCode']];
        }

        Db::name('order_info')
            ->where('order_sn', $order['order_sn'])
            ->update(['pay_token' => $result['info']['paymentAccessToken'], 'pay_data' => json_encode($result['info'])]);

        //更新訂單資料
        return ['code' => 200, 'method' => 'redirect', 'data' => $result['info']];
    }

    public function response($data)
    {
        $message = '';

        $amount  = Db::name('order_info')
            ->where('order_sn', $data['orderId'])
            ->value('order_amount');

        $r_data = [
            'amount' => $amount,
            'currency' => 'TWD',
        ];

        $lp = new LinePayObj('1657811805', '53a912dfa167b5e767847c7e9fca4ea1');
        $result = $lp->confirm($data['transactionId'], $r_data);

        if ($result['returnCode'] != '0000') {
            return [
                'code' => $result['returnCode'],
                'paycode' => 'linepay',
                'order_sn' => $data['orderId'],
            ];
        }

        //更新訂單付款狀態
        try {

            Db::name('order_info')
                ->where('order_sn', $data['orderId'])
                ->update([
                    'pay_status' => 2,
                    'pay_time' => time(),
                    'pay_token' => $data['transactionId'],
                ]);

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

            //更新訂單操縱紀錄
            $order_action = [
                'order_id' => $order['order_id'],
                'action_user' => 'Line',
                'order_status' => $order['order_status'],
                'shipping_status' => $order['shipping_status'],
                'pay_status' => '2',
                'action_note' => 'LinePay: ' . $data['transactionId'] . '，付款成功',
                'log_time' => time(),
            ];
            Db::name('order_action')->insert($order_action);


            $code = 200;
        } catch (\Exception $e) {
            $code = 500;
        }

        //判斷是否為超商取貨
        $shipping_code = Db::name('shipping')->where('shipping_id', $order['shipping_id'])->value('shipping_code');

        if ($shipping_code == 'ecpay') {
            $rtn = \app\common\shipping\Shipping::createShipping('ecpay', $order['order_sn']);
            if ($rtn['code']!=200) {
                $code = 501;
                $message = '付款成功,建立物流單失敗';
            } else {
                $code = 200;
            }
        }

        //判斷是否為SlashCard產品
        $is_main = Db::name('order_goods')
            ->where('order_id', $order['order_id'])
            ->where('goods_id', 1)
            ->find();

        if ($is_main) {
            $rtn = \app\service\Card::addUser([
                'order_sn' => $order['order_sn'],
                'user_id' => Db::name('users')->where('user_id', $order['user_id'])->value('sso_user_id'),
            ]);

            if (!$rtn['code'] != 200) {
                $code = 503;
                $message = '付款成功,建立卡片失敗';
            } else {
                $code = 200;
                Db::name('users')->where('user_id', $order['user_id'])->update(['is_validated' => 1]);
            }
        }

        $rtn = [
            'code' => $code,
            'paycode' => 'linepay',
            'order_sn' => $data['orderId'],
            'message' => $message,
        ];

        return $rtn;
    }

    public function callback($data)
    {
        return ['code' => 404];
    }
}
