<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海口快推科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2019-1-7
 */

namespace app\common\model;

use think\Db;
use think\Cache;
use think\Config;
use think\Cookie;

/**
 * 商城订单支付处理模型
 */
load_trait('controller/Jump');
class ShopOrderPayHandle
{
    use \traits\controller\Jump;

    private $sendTerminal = '';

    // 构造函数
    public function __construct()
    {
        // 统一接收参数处理
        $this->times = getTime();
        $this->post = input('post.');
        $this->usersData = [];
        $this->orderData = [];
        $this->usersConfig = [];
        $this->provider = input('provider/s', '');
        $this->sendTerminal = input('param.sendTerminal/s', 'openSource');
        $this->sendTerminal = !empty($this->sendTerminal) ? trim($this->sendTerminal) : '';
    }

    // 返回订单选择的支付渠道
    public function returnOrderPayChannel($post = [], $usersData = [], $orderData = [], $usersConfig = [], $stockWarningEmail = [], $stockWarningMobile = [])
    {
        $resultData = [];

        // 参数定义
        $this->post = !empty($post) ? $post : $this->post;
        $this->usersData = !empty($usersData) ? $usersData : $this->usersData;
        $this->orderData = !empty($orderData) ? $orderData : $this->orderData;
        $this->usersConfig = !empty($usersConfig) ? $usersConfig : $this->usersConfig;
        $order_id = !empty($this->orderData['order_id']) ? intval($this->orderData['order_id']) : 0;
        $order_code = !empty($this->orderData['order_code']) ? trim($this->orderData['order_code']) : 0;
        $order_amount = !empty($this->orderData['order_amount']) ? floatval($this->orderData['order_amount']) : 0;

        // 微信支付 -- 官方
        if (1 === intval($this->post['pay_type']) && 1 === intval($this->usersConfig['pay_wechat_open'])) {
            // 手机端微信支付接口
            if ('h5' == $this->provider) {
                // 查询参数
                $openid = Db::name('users')->where('users_id', $this->post['users_id'])->value('open_id');

                // 调用手机端微信支付接口
                $payApiModel = new \app\user\model\PayApi;
                $weChatPay = $payApiModel->getWechatPay($openid, $order_code, $order_amount);
                if (!empty($weChatPay['postCode']) && 'error' === $weChatPay['postCode']) {
                    $this->error($weChatPay['return_msg']);
                } else if (!empty($weChatPay)) {
                    $resultData = [
                        'weChatPay' => $weChatPay,
                        'orderData' => [
                            'order_id' => $order_id,
                            'order_code' => $order_code
                        ]
                    ];
                }
            }
            // 手机端小程序支付接口
            else {
                // 调用手机端小程序支付接口
                $weChatPay = model('ShopPublicHandle')->getWechatAppletsPay($this->post['users_id'], $order_code, $order_amount);
                $resultData = [
                    'weChatPay' => $weChatPay,
                    'orderData' => [
                        'order_id' => $order_id,
                        'order_code' => $order_code
                    ]
                ];
            }
        }
        // 虎皮椒微信支付 -- 第三方
        else if (1 === intval($this->post['pay_type']) && 2 === intval($this->usersConfig['pay_wechat_open'])) {
            $this->orderData['transaction_type'] = 2;
            $controller = new \weapp\Hupijiaopay\controller\Hupijiaopay;
            $returnUrl = $_SERVER['HTTP_REFERER'] . '#/otherpages/mall/product_buy/index?id='.intval($order_id).'&code='.trim($order_code).'&pay_type=1&querystr='.trim($this->post['querystr']);
            $hupijiaoPay = $controller->UnifyGetPayAction([], $this->orderData, $returnUrl, false, 'wechat');
            $resultData = [
                'hupijiaoPay' => $hupijiaoPay['data'],
                'orderData' => [
                    'order_id' => $order_id,
                    'order_code' => $order_code
                ]
            ];
        }
        // 余额支付
        else if (2 === intval($this->post['pay_type'])) {
            // 更新订单为已余额支付完成
            $payDetails = [
                'unified_id'     => $order_id,
                'unified_number' => $order_code,
                'payment_amount' => $order_amount,
                'payment_type'   => '余额支付'
            ];
            $update = [
                'order_status'    => 1,
                'pay_name'        => 'balance',
                'wechat_pay_type' => '',
                'pay_details'     => serialize($payDetails),
                'pay_time'        => getTime(),
                'update_time'     => getTime()
            ];
            $resultID = Db::name('shop_order')->where('order_id', $order_id)->update($update);
            if (!empty($resultID)) {
                // 会员当前余额
                $usersMoney = Db::name('users')->where('users_id', $this->post['users_id'])->getField('users_money');
                // 扣除会员余额
                $resultID = Db::name('users')->where('users_id', $this->post['users_id'])->setDec('users_money', $order_amount);
                if (!empty($resultID)) {
                    // 订单支付成功后相关处理(扣除余额、订单记录、统计销售额、返回消息通知等...)
                    $orderData = !empty($update) ? array_merge($orderData, $update) : $orderData;
                    $resultData = $this->orderPaySuccessHandle($usersData, $orderData, $usersMoney, $stockWarningEmail, $stockWarningMobile);
                }
            }
        }
        // 抖音支付
        else if (9 === intval($post['pay_type'])) {
            $tikTokPay = model('TikTok')->getTikTokAppletsPay($order_id, $order_code, $order_amount, $this->usersConfig['order_unpay_close_time']);
            $resultData = [
                'tikTokPay' => $tikTokPay,
                'orderData' => [
                    'order_id'   => $order_id,
                    'order_code' => $order_code
                ]
            ];
        }
        // 百度支付
        else if (10 === intval($post['pay_type'])) {
            $baiduPay = model('BaiduPay')->getBaiDuAppletsPay($order_id, $order_code, $order_amount);
            $resultData = [
                'baiduPay' => $baiduPay,
                'orderData' => [
                    'order_id'   => $order_id,
                    'order_code' => $order_code
                ]
            ];
        }

        // 订单支付异常，没有可用的支付方式
        if (empty($resultData)) $this->error('订单支付异常，没有可用的支付方式');

        // 返回提示
        $this->success('正在支付', null, $resultData);

    }

    // 订单支付成功后相关处理(扣除余额、订单记录、统计销售额、返回消息通知等...)
    public function orderPaySuccessHandle($usersData = [], $orderData = [], $usersMoney = [], $stockWarningEmail = [], $stockWarningMobile = [])
    {
        $users_id = !empty($usersData['users_id']) ? intval($usersData['users_id']) : 0;
        $order_id = !empty($orderData['order_id']) ? intval($orderData['order_id']) : 0;
        $order_code = !empty($orderData['order_code']) ? trim($orderData['order_code']) : 0;
        $order_amount = !empty($orderData['order_amount']) ? floatval($orderData['order_amount']) : 0;
        if (!empty($orderData['pay_name']) && 'balance' == trim($orderData['pay_name'])) {
            // 添加会员余额记录
            $getParam = [
                'users_id' => $users_id,
                'users_money' => $usersMoney
            ];
            UsersMoneyAction($order_code, $getParam, $order_amount, '订单支付');
        }

        // 支付方式
        $payMethodArr = config('global.pay_method_arr');
        if (!empty($orderData['pay_name']) && isset($payMethodArr[$orderData['pay_name']])){
            $orderData['pay_method'] = $payMethodArr[$orderData['pay_name']];
            $actionNote = "会员使用{$orderData['pay_method']}完成支付";
        } else {
            $actionNote = '支付完成';
        }

        // 添加订单操作记录
        AddOrderAction($order_id, $users_id, 0, 1, 0, 1, '支付成功', $actionNote);

        // 统计销售额
        eyou_statistics_data(2);
        eyou_statistics_data(3, $order_amount);

        // 返回数据
        $orderData['goodsTitle'] = !empty($orderData['goodsTitle']) ? $orderData['goodsTitle'] : '';
        $resultData['orderData'] = $orderData;

        // 微信公众号消息推送
        $resultData['weChat'] = model('ShopPublicHandle')->getSendWeChatContent($usersData, $orderData, [30, 50]);

        // 手机短信消息推送
        $resultData['mobile'] = [];
        // 订单付款手机短信
        $orderPay = model('ShopPublicHandle')->getSendMobileContent($usersData, $orderData, [30, 50]);
        if (!empty($orderPay)) $resultData['mobile'] = [$orderPay];
        // 余额变动手机短信
        $usersMoney = model('ShopPublicHandle')->getSendMobileContent($usersData, $orderData, [35]);
        if (!empty($usersMoney)) $resultData['mobile'] = array_merge($resultData['mobile'], [$usersMoney]);
        // 商品库存预警手机短信
        if (!empty($stockWarningMobile)) $resultData['mobile'] = array_merge($resultData['mobile'], $stockWarningMobile);
        // 把发送的ID进行字符串处理
        $resultData['mobile'] = !empty($resultData['mobile']) ? implode(',', $resultData['mobile']) : false;

        // 邮箱消息推送
        $resultData['email'] = [];
        // 订单付款邮箱推送
        $orderPay = model('ShopPublicHandle')->getSendEamilContent($usersData, $orderData, [30, 50]);
        if (!empty($orderPay)) $resultData['email'] = [$orderPay];
        // 余额变动邮箱推送
        $usersMoney = model('ShopPublicHandle')->getSendEamilContent($usersData, $orderData, [35]);
        if (!empty($usersMoney)) $resultData['email'] = array_merge($resultData['email'], [$usersMoney]);
        // 商品库存预警邮箱推送
        if (!empty($stockWarningEmail)) $resultData['email'] = array_merge($resultData['email'], $stockWarningEmail);
        // 把发送的ID进行字符串处理
        $resultData['email'] = !empty($resultData['email']) ? implode(',', $resultData['email']) : false;

        // 返回数据
        return $resultData;
    }
}