<?php
/**
 * +------------------------------------------------------------
 * | 微信支付 finance/controller/Wechat.php
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\finance\controller;

use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use think\Validate;

class Wechat extends Module
{
    private $config;
    private $wechat;
    private $validate = [
        'msg' => [
            'out_trade_no.require' => '订单号不能为空',
            'body.require' => '商品描述不能为空',
            'total_fee.require' => '订单金额不能为空'
        ],
        'rule' => [
            'out_trade_no' => 'require',
            'body' => 'require',
            'total_fee' => 'require'
        ],
        'data' => []
    ];

    function initialize()
    {
        parent::initialize();
        $this->config = config('')['finance']['wechat'];
    }

    function _init_data($data = [])
    {
        $this->data = $data;
        $this->wechat = Pay::wechat($this->config);
        $this->validate['data'] = [
            'out_trade_no' => empty($data['id']) ? '' : $data['id'],
            'body' => empty($data['memo']) ? ('支付订单' . (empty($data['id']) ? '' : ':' . $data['id'])) : $data['memo'],
            'total_fee' => empty($data['money']) ? 0 : ($data['money'] * 100)
        ];
        return $this;
    }

    public function notify()
    {
        $pay = Pay::wechat($this->config);
        try {
            $data = $pay->verify();
            //Log::debug('Wechat notify', $data->all());
            $attr = [
                'money' => $data['total_fee'],
                'out_trade_no' => $data['out_trade_no'],
                'trade_no' => $data['transaction_id']
            ];
            try {
                $result = action('finance/api/check_pay_result', [$attr, 'notify']);
            } catch (\Exception $e) {
                $result = ['code' => 0, 'msg' => $e->getMessage()];
            }
            if ($result['code'] == 1) {
                return $pay->success()->send();
            } else {
                //验证失败
            }
        } catch (Exception $e) {
            $e->getMessage();
        }
    }

    /**
     * 扫码支付
     */
    function scan()
    {
        $check = $this->check();
        if ($check === true) {
            $result = $this->wechat->scan($this->validate['data']);
            if ($result['result_code'] == 'SUCCESS') {
                return ['code' => 1, 'msg' => '', 'data' => urlencode($result->code_url), 'order' => $this->validate['data']['out_trade_no']];
            } else {
                return ['code' => 0, 'msg' => 'return_msg'];
            }
        } else {
            return ['code' => 0, 'msg' => $check];
        }
    }

    /**
     * 手机网站支付
     */
    function h5()
    {
        $check = $this->check();
        if ($check === true) {
            $result = $this->wechat->wap($this->validate['data']);
            return ['code' => 1, 'msg' => '', 'data' => $result->getContent()];
        } else {
            return ['code' => 0, 'msg' => $check];
        }
    }

    /**
     * 公众号支付
     */
    function mp()
    {
        if (!empty($this->data['extend']) && !is_array($this->data['extend'])) {
            $this->data['extend'] = json_decode($this->data['extend'], 1);
        }
        if (!empty($this->data['user_id'])) {
            $openid = db('user_oauth')->where('user_id', '=', $this->data['user_id'])->value('openid');
            if (!empty($openid)) {
                $this->validate['data']['openid'] = $openid;
                $result = $this->wechat->mp($this->validate['data']);
                return ['code' => 1, 'msg' => '', 'data' => $result->toArray()];
            }
            return ['code' => 0, 'msg' => 'openid不能为空'];
        }
        return ['code'=>1000,'msg'=>'请登录'];
    }

    /**
     * 小程序支付
     */
    function mini()
    {
        if (!empty($this->data['extend']) && !is_array($this->data['extend'])) {
            $this->data['extend'] = json_decode($this->data['extend'], 1);
        }
        if (!empty($this->data['user_id'])) {
            $openid = db('user_oauth')->where('user_id', '=', $this->data['user_id'])->value('openid');
            if (!empty($openid)) {
                $this->validate['data']['openid'] = $openid;
                $result = $this->wechat->miniapp($this->validate['data']);
                return ['code' => 1, 'msg' => '', 'data' => $result->toArray()];
            }
            return ['code' => 0, 'msg' => 'openid不能为空'];
        }
        return ['code'=>1000,'msg'=>'请登录'];
    }

    function check()
    {
        $validate = new Validate($this->validate['rule'], $this->validate['msg']);
        $result = $validate->check($this->validate['data']);
        if ($result === true) {
            return true;
        } else {
            return $validate->getError();
        }
    }

}
