<?php

namespace App\Repositories\Customers;

use App\Common\Enums\HtTab;
use App\Exceptions\Api\ApiException;
use App\Modules\Enums\ErrorCode;
use App\Modules\Models\Customer\Customer;
use App\Modules\Models\Machine\Machine;
use App\Modules\Models\Rent\Rent;
use App\Modules\Models\Spot\Spot;
use App\Modules\Repositories\BaseRepository;
use Yansongda\LaravelPay\Facades\Pay;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Illuminate\Support\Facades\Log;

/**
 * Class EloquentHistoryRepository.
 */
class WeChatRepository extends BaseRepository
{
    public function submitOrderToWeChat($type, $order_obj, $openid)
    {
        $order = [];
        switch ($type) {
            case 1:
                $order['out_trade_no'] = $order_obj->rent_no;
                $order['body'] = '灰兔智能租借押金';
                $order['total_fee'] = (int)($order_obj->deposit * $order_obj->number);
                $order['openid'] = $openid;
                $order['attach'] = json_encode(['type' => $type]);
                break;
            case 2:
                $order['out_trade_no'] = $order_obj->guide_no;
                $order['body'] = '微导览服务费';
                $order['total_fee'] = $order_obj->real_total;
                $order['openid'] = $openid;
                $order['attach'] = json_encode(['type' => $type]);
                break;
            default :
                break;
        }
        try {
//            $pay = Pay::wechat()->miniapp($order, ['notify_url' => 'https://api.playxx.cn/api/v1/customers/weGuidePayCallBack']);
//            $pay = Pay::wechat()->miniapp($order, ['notify_url' => config('wechat.payment.default.notify_url')]);
            $pay = Pay::wechat()->miniapp($order, ['notify_url' => 'https://api.ssw-htzn.com/api/v1/customers/weGuidePayCallBack']);
            Log::info("[Pay::wechat()->miniapp]" . $pay);
        } catch (GatewayException $e) {
            throw new ApiException(ErrorCode::WE_MINIAPP_PAY_FAIL, $e->getMessage());
        } catch (InvalidSignException $e) {
            throw new ApiException(ErrorCode::WE_MINIAPP_PAY_FAIL, $e->getMessage());
        } catch (InvalidConfigException $e) {
            throw new ApiException(ErrorCode::WE_MINIAPP_PAY_FAIL, $e->getMessage());
        }
        $res = [
            'timeStamp' => $pay->timeStamp,
            'nonceStr' => $pay->nonceStr,
            'package' => $pay->package,
            'paySign' => $pay->paySign,
            'order_no' => $order['out_trade_no'],
        ];
        $order_obj->prepay_id = (string)explode('=', $pay->package)[1];
        $order_obj->save();
        return $res;
    }

    public function rentRefund($rent_obj)
    {
        $order = [
            'out_refund_no' => $this->createRefoundNo(),
            'out_trade_no' => $rent_obj->rent_no,
            'total_fee' => $rent_obj->deposit * $rent_obj->number,
            'refund_fee' => $rent_obj->deposit * $rent_obj->number,
        ];
        $this->doRefund($order);
        return $order['out_refund_no'];
    }

    public function productOutFailRefund($rent_obj, $refund_no)
    {

        $data = [
            'out_refund_no' => $refund_no,
            'out_trade_no' => $rent_obj->rent_no,
            'total_fee' => $rent_obj->deposit * $rent_obj->number,
            'refund_fee' => $rent_obj->deposit,
        ];
        $this->doRefund($data);

    }

    /**
     * @param $data
     * @return bool
     * @throws ApiException
     */
    public function doRefund($data)
    {
        $order = [
            'out_refund_no' => $data['out_refund_no'],
            'out_trade_no' => $data['out_trade_no'],
            'total_fee' => $data['total_fee'],
            'refund_fee' => $data['refund_fee'],
            'type' => 'miniapp',
        ];
        try {
            Log::info("[doRefund] start >>>>");
            $re = Pay::wechat()->refund($order);
            Log::info("[doRefund] params:" . json_encode($re));
        } catch (GatewayException $e) {
            throw new ApiException(ErrorCode::WE_REfUND_FAIL, $e->getMessage());
        } catch (InvalidSignException $e) {
            throw new ApiException(ErrorCode::WE_REfUND_FAIL, $e->getMessage());
        }
        return true;
    }

    /**
     * 生成订单单号
     */
    function createRefoundNo()
    {
        return HtTab::RENT_REFUND . date('Ymd') . str_pad(mt_rand(1, 9999999999), 10, '0', STR_PAD_LEFT);
    }

    function getCustomer($id)
    {
        $customer = Customer::where('id', $id)->first();
        if ($customer == null) {
            throw new ApiException(ErrorCode::USER_NOT_EXIST, trans("api.error.user_not_exist"));
        }
        return $customer;
    }

    function rentSuccessMes($rent_obj)
    {
        $customer = $this->getCustomer($rent_obj->customer_id);
        $spot = Spot::where('id', $rent_obj->spot_id)->first();
        $app = app('wechat.mini_program');

        $app->template_message->send([
            'touser' => $customer->mini_program_open_id,
            'template_id' => 'ivyzt64NFH5t_0TJGq8s632yob7YPNHez-kApQNrLeg',
            'form_id' => $rent_obj->prepay_id,
            'data' => [
                'keyword1' => $rent_obj->pay_time,
                'keyword2' => $spot->spotname,
                'keyword3' => $rent_obj->rent_no,
                'keyword4' => HtTab::RENT_PRODUCTION_NAME,
                'keyword5' => round($rent_obj->deposit / 100, 2) . '/个',
                'keyword6' => round($rent_obj->deposit * $rent_obj->number / 100, 2) . '元',
                'keyword7' => feeMes($rent_obj->free_time, $rent_obj->one_day_price),
            ],
        ]);
    }

    function subscribeSuccessMes($rent_obj)
    {
        $customer = $this->getCustomer($rent_obj->customer_id);
        $spot = Spot::where('id', $rent_obj->spot_id)->first();
        $app = app('wechat.mini_program');
        $app->template_message->send([
            'touser' => $customer->mini_program_open_id,
            'template_id' => 'XtZN0uijQ1AqQ-p2dtZ60JURu3w3oRtTDfdMxm0ayF4',
            'form_id' => $rent_obj->prepay_id,
            'data' => [
                'keyword1' => HtTab::RENT_PRODUCTION_NAME,
                'keyword2' => $rent_obj->rent_no,
                'keyword3' => $spot->spotname,
                'keyword4' => round($rent_obj->deposit * $rent_obj->number / 100, 2) . '元(押金)',
                'keyword5' => $rent_obj->pay_time,
                'keyword6' => feeMes($rent_obj->free_time, $rent_obj->one_day_price),
                'keyword7' => $rent_obj->number,
            ],
        ]);
    }

    function rentFailMes($rent_obj)
    {
        $customer = $this->getCustomer($rent_obj->customer_id);
        $spot = Spot::where('id', $rent_obj->spot_id)->first();
        $app = app('wechat.mini_program');
        $app->template_message->send([
            'touser' => $customer->mini_program_open_id,
            'template_id' => 'iwn_y0-HhxTsEIZQghh6KaDEuXImeJsaQrCseapjBO4',
            'form_id' => $rent_obj->prepay_id,
            'data' => [
                'keyword1' => $rent_obj->rent_no,
                'keyword2' => $rent_obj->pay_time,
                'keyword3' => $spot->spotname,
                'keyword4' => '押金已按原微信支付路径退回',
            ],
        ]);
    }

    function subscribeFailMes($rent_obj)
    {
        $customer = $this->getCustomer($rent_obj->customer_id);
        $spot = Spot::where('id', $rent_obj->spot_id)->first();
        $app = app('wechat.mini_program');
        $app->template_message->send([
            'touser' => $customer->mini_program_open_id,
            'template_id' => '8eGgkk8Wxud8_pgkkYQWLELhBvB8-R68A1GQzXx6Iqk',
            'form_id' => $rent_obj->prepay_id,
            'data' => [
                'keyword1' => HtTab::RENT_PRODUCTION_NAME,
                'keyword2' => $rent_obj->rent_no,
                'keyword3' => $spot->spotname,
                'keyword4' => round($rent_obj->deposit * $rent_obj->number / 100, 2) . '元',
                'keyword5' => $rent_obj->pay_time,
                'keyword6' => '刚被预约完',
            ],
        ]);
    }

    function shipmentMes($rent_obj, $success_hatchs)
    {
        $customer = $this->getCustomer($rent_obj->customer_id);
        $spot = Spot::where('id', $rent_obj->spot_id)->first();
        $app = app('wechat.mini_program');
        $app->template_message->send([
            'touser' => $customer->mini_program_open_id,
            'template_id' => '1qugdEt19bGstbESUBsB8AORgVMAmpcT5DaomMqhPG0',
            'form_id' => $rent_obj->prepay_id,
            'data' => [
                'keyword1' => $rent_obj->rent_no,
                'keyword2' => $spot->spotname,
                'keyword3' => HtTab::RENT_PRODUCTION_NAME . '*' . count($success_hatchs),
            ],
        ]);
    }

    function returnAllMes($rent_obj)
    {
        if(!$rent_obj->is_over){
            return false;
        }
        $customer = $this->getCustomer($rent_obj->customer_id);
        $spot = Spot::where('id', $rent_obj->spot_id)->first();
        $app = app('wechat.mini_program');
        $app->template_message->send([
            'touser' => $customer->mini_program_open_id,
            'template_id' => 'J7OrbZULpeSi5Ldnao0Pf5v9MZDBLlwZCAZkcuwxUNo',
            'form_id' => $rent_obj->prepay_id,
            'data' => [
                'keyword1' => HtTab::RENT_PRODUCTION_NAME,
                'keyword2' => $rent_obj->rent_no,
                'keyword3' => $spot->spotname,
                'keyword4' => round($rent_obj->real_total / 100, 2) . '元',
                'keyword5' => feeMes($rent_obj->free_time, $rent_obj->one_day_price),
            ],
        ]);
        return true;
    }




}
