<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/23
 */

namespace crmeb\services;

use app\models\merchant\MerchantMiniprogram;
use app\models\store\StoreOrder;
use app\models\user\UserRecharge;
use crmeb\exceptions\AdminException;
use crmeb\repositories\PaymentRepositories;
use crmeb\services\subscribe\ProgramSubscribe;
use EasyWeChat\Core\Exceptions\FaultException;
use EasyWeChat\Encryption\EncryptionException;
use EasyWeChat\Foundation\Application;
use EasyWeChat\MiniProgram\MiniProgram;
use EasyWeChat\MiniProgram\QRCode\QRCode;
use EasyWeChat\Notice\Notice;
use EasyWeChat\Payment\Order;
use EasyWeChat\Payment\Payment;
use EasyWeChat\Support\Collection;
use Psr\Http\Message\StreamInterface;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Route as Url;
use crmeb\interfaces\ProviderInterface;
use crmeb\utils\Hook;

/**微信小程序接口
 * Class WechatMinService
 * @package service
 */
class MiniProgramService implements ProviderInterface
{
    private static $instance = null;

    public function register($config)
    {
        return ['mini_program', new self()];
    }

    /**
     * @param bool $mer_id
     * @return array
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function options($mer_id = false)
    {
        if ($mer_id) {
            $mini = MerchantMiniprogram::where('mer_id', $mer_id)->find();

            $config = [];
            $config['mini_program'] = [
                'app_id' => $mini ? $mini['appid'] : '',
                'token' => config('third.token'),
                'component_appid' => config('third.appId'),
                'aes_key' => config('third.encodingAesKey'),
            ];
            $config['payment'] = [
                'app_id' => trim($mini ? $mini['appid'] : ''),
                'merchant_id' => trim($mini ? $mini['mch_id'] : ''),
                'key' => trim($mini ? $mini['mch_key'] : ''),
                'cert_path' => realpath('.' . ($mini ? $mini['cert_path'] : '')),
                'key_path' => realpath('.' . ($mini ? $mini['key_path'] : '')),
                'notify_url' => SystemConfigService::get('site_url', '', true, $mer_id) . '/api/routine/notify/' . $mer_id,
                // 'profit_sharing' => 'Y'
            ];
        } else {
            $wechat = SystemConfigService::more(['site_url', 'routine_appId', 'routine_appsecret']);
            $payment = SystemConfigService::more(['pay_routine_mchid', 'pay_routine_key', 'pay_routine_client_cert', 'pay_routine_client_key', 'pay_weixin_open']);
            $config = [];
            $config['mini_program'] = [
                'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
                'secret' => isset($wechat['routine_appsecret']) ? trim($wechat['routine_appsecret']) : '',
                'token' => isset($wechat['wechat_token']) ? trim($wechat['wechat_token']) : '',
                'aes_key' => isset($wechat['wechat_encodingaeskey']) ? trim($wechat['wechat_encodingaeskey']) : ''
            ];
            $config['payment'] = [
                'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
                'merchant_id' => trim($payment['pay_routine_mchid']),
                'key' => trim($payment['pay_routine_key']),
                'cert_path' => realpath('.' . $payment['pay_routine_client_cert']),
                'key_path' => realpath('.' . $payment['pay_routine_client_key']),
                'notify_url' => $wechat['site_url'] . '/api/routine/notify/0',
                // 'profit_sharing' => 'Y'
            ];
        }
        return $config;
    }

    /**
     * @param bool $cache
     * @param bool $mer_id
     * @return Application|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function application($cache = false, $mer_id = false)
    {
        (self::$instance === null || $cache === true) && (self::$instance = new Application(self::options($mer_id)));
        return self::$instance;
    }

    /**
     * 小程序接口
     * @param bool $mer_id
     * @return MiniProgram
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function miniprogram($mer_id = false)
    {
        return self::application(false, $mer_id)->mini_program;
    }

    /**
     * 获得用户信息 根据code 获取session_key
     * @param $code
     * @param bool $mer_id
     * @return Collection $userInfo
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function getUserInfo($code, $mer_id = false)
    {
        if ($mer_id) {
            $userInfo = self::miniprogram($mer_id)->sns->getSessionKeyThird($code);
        } else {
            $userInfo = self::miniprogram()->sns->getSessionKey($code);
        }
        return $userInfo;
    }


    /**
     * 加密数据解密
     * @param $sessionKey
     * @param $iv
     * @param $encryptData
     * @return array $userInfo
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     * @throws EncryptionException
     */
    public static function encryptor($sessionKey, $iv, $encryptData)
    {
        return self::miniprogram()->encryptor->decryptData($sessionKey, $iv, $encryptData);
    }

    /**
     * 上传临时素材接口
     * @return \EasyWeChat\Material\Temporary
     */
    public static function materialTemporaryService()
    {
        return self::miniprogram()->material_temporary;
    }

    /**
     * 客服消息接口
     * @param null $to
     * @param null $message
     */
    public static function staffService()
    {
        return self::miniprogram()->staff;
    }

    /**
     * 微信小程序二维码生成接口
     * @param bool $mer_id
     * @return QRCode
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function qrcodeService($mer_id = false)
    {
        return self::miniprogram($mer_id)->qrcode;
    }

    /**微信小程序二维码生成接口不限量永久
     * @param $scene
     * @param null $page
     * @param int $width
     * @param bool $autoColor
     * @param array $lineColor
     * @param bool $mer_id
     * @return StreamInterface
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function appCodeUnlimitService($scene, $page = null, $width = 430, $autoColor = false, $lineColor = ['r' => 0, 'g' => 0, 'b' => 0], $mer_id = false)
    {
        return self::qrcodeService($mer_id)->appCodeUnlimit($scene, $page, $width, $autoColor, $lineColor);
    }


    /**
     * 模板消息接口
     * @return Notice
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function noticeService()
    {
        return self::miniprogram()->notice;
    }

    /**
     * 订阅模板消息接口
     * @return ProgramSubscribe
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function SubscribenoticeService()
    {
        return self::miniprogram()->now_notice;
    }

    /**
     * 发送订阅消息
     * @param string $touser 接收者（用户）的 openid
     * @param string $templateId 所需下发的订阅模板id
     * @param array $data 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
     * @param string $link 击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
     * @return Collection|null
     * @throws \EasyWeChat\Core\Exceptions\HttpException
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public static function sendSubscribeTemlate(string $touser, string $templateId, array $data, string $link = '')
    {
        return self::SubscribenoticeService()->to($touser)->template($templateId)->andData($data)->withUrl($link)->send();
    }

    /**
     * 支付
     * @param bool $mer_id
     * @return Payment
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function paymentService($mer_id = false)
    {
        /*var_dump(self::application(false, $mer_id)->payment);
        exit;*/
        return self::application(false, $mer_id)->payment;
    }

    /**
     * 生成支付订单对象
     * @param $openid
     * @param $out_trade_no
     * @param $total_fee
     * @param $attach
     * @param $body
     * @param string $detail
     * @param string $trade_type
     * @param array $options
     * @return Order
     */
    protected static function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
    {
        $total_fee = bcmul($total_fee, 100, 0);
        $order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
        if ($order['detail'] == '') unset($order['detail']);
        return new Order($order);
    }

    /**
     * 获得下单ID
     * @param $openid
     * @param $out_trade_no
     * @param $total_fee
     * @param $attach
     * @param $body
     * @param string $detail
     * @param string $trade_type
     * @param array $options
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     * @throws \Exception
     */
    public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [], $mer_id = false)
    {
        $order = self::paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
        $result = self::paymentService($mer_id)->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            try {
                PaymentRepositories::wechatPaymentPrepareProgram($order, $result->prepay_id);
            } catch (\Exception $e) {
            }
            return $result->prepay_id;
        } else {
            if ($result->return_code == 'FAIL') {
                exception('微信支付错误返回：' . $result->return_msg);
            } else if (isset($result->err_code)) {
                exception('微信支付错误返回：' . $result->err_code_des);
            } else {
                exception('没有获取微信支付的预支付ID，请重新发起支付!');
            }
            exit;
        }

    }

    /**
     * 获得jsSdk支付参数
     * @param $openid
     * @param $out_trade_no
     * @param $total_fee
     * @param $attach
     * @param $body
     * @param string $detail
     * @param string $trade_type
     * @param array $options
     * @param bool $mer_id
     * @return array|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [], $mer_id = false)
    {
        return self::paymentService($mer_id)->configForJSSDKPayment(self::paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options, $mer_id));
    }

    /**
     * 使用商户订单号退款
     * @param $orderNo
     * @param $refundNo
     * @param $totalFee
     * @param null $refundFee
     * @param null $opUserId
     * @param string $refundReason
     * @param string $type
     * @param string $refundAccount
     * @param bool $mer_id
     * @return Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS', $mer_id = false)
    {
        $totalFee = floatval($totalFee);
        $refundFee = floatval($refundFee);
        return self::paymentService($mer_id)->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
    }

    /**
     * 单次分账
     * @param $orderNo
     * @param $sharingNo
     * @param $receivers
     * @param bool $mer_id
     * @return Collection
     * @throws \Exception
     */
    public static function profit_sharing($orderNo, $sharingNo, $receivers, $mer_id = false)
    {
        return self::paymentService($mer_id)->profit_sharing($orderNo, $sharingNo, $receivers);
    }

    /**
     * 添加分账接收方
     */
    public static function addReceiver($account, $mer_id = false)
    {
        $receiver = array(
            'type'=>'PERSONAL_OPENID',
            'account'=>$account, // openid
            'relation_type'=>'USER',
        );
        return self::paymentService($mer_id)->addReceiver($receiver);
    }

    /**
     * 多次分账
     */
    public static function multi_profit_sharing($orderNo, $sharingNo, $receivers, $mer_id = false)
    {
        return self::paymentService($mer_id)->multiProfitSharing($orderNo, $sharingNo, $receivers);
    }

    /**
     * 完结分账
     */
    public static function profit_sharing_finish($orderNo, $sharingNo, $mer_id = false)
    {
        return self::paymentService($mer_id)->profitSharingFinish($orderNo, $sharingNo);
    }

    /** 根据订单号退款
     * @param $orderNo
     * @param array $opt
     * @param bool $mer_id
     * @return bool
     */
    public static function payOrderRefund($orderNo, array $opt, $mer_id = false)
    {
        if (!isset($opt['pay_price'])) throw new AdminException('缺少pay_price');
        $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
        $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
        $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
        $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
        $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
        $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
        /*仅针对老资金流商户使用
        REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款（默认使用未结算资金退款）
        REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
        $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
        try {
            $res = (self::refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount, $mer_id));
            if ($res->result_code == 'FAIL') return false;
            if (isset($res->err_code)) return false;
        } catch (\Exception $e) {
            throw new AdminException($e->getMessage());
        }
        return true;
    }

    /**
     * 微信支付成功回调接口
     * @param bool $mer_id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     * @throws FaultException
     */
    public static function handleNotify($mer_id = false)
    {
        self::paymentService($mer_id)->handleNotify(function ($notify, $successful) {
            if ($successful && isset($notify->out_trade_no)) {
                if (isset($notify->attach) && $notify->attach) {
                    if (($count = strpos($notify->out_trade_no, '_')) !== false) {
                        $notify->out_trade_no = substr($notify->out_trade_no, $count + 1);
                    }
                    StoreOrder::edit(['transaction_id' => $notify->transaction_id], $notify->out_trade_no, 'order_id');
                    UserRecharge::edit(['transaction_id' => $notify->transaction_id], $notify->out_trade_no, 'order_id');
                    (new Hook(PaymentRepositories::class, 'wechat'))->listen($notify->attach, $notify->out_trade_no);
                }
                return false;
            }
        });
    }

    /**
     * 作为客服消息发送
     * @param $to
     * @param $message
     * @return bool
     */
    public static function staffTo($to, $message)
    {
        $staff = self::staffService();
        $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
        $res = $staff->to($to)->send();
        return $res;
    }


    /**
     * 获取直播列表
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getLiveInfo(int $page = 1, $limit = 10, $mer_id = '')
    {
        try {
            $res = self::miniprogram($mer_id)->wechat_live->getLiveInfo($page, $limit);
            if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['room_info']) && $res['room_info']) {
                return $res['room_info'];
            } else {
                return [];
            }
        } catch (\Throwable $e) {
            return [];
        }
    }

}