<?php

/**
 * 统一的预创建订单请求对象
 * @version
 *          1.0.0 Created at 2017-12-21. by --gwang
 * @author gwang (mail@wanggangzero.cn)
 * @copyright ? 2017-12-21, SJZ LoyalSoft Corporation & gwang. All rights reserved.
 */
class PayRequest extends loyalsoft\Object_ext {

    const orderTab = 'tpl_order_tab';

    /**
     * @var string 充值回调透传参数(len=250)
     */
    public $callbackInfo;

    /**
     * 各平台取自己的配置信息
     * @var string 充值回调地址(len=100)
     */
    public $notifyUrl;

    /**
     * @var string 订单ID (len=30)
     */
    public $cpOrderId;

    /**
     * @var float 充值金额 (单位:元)
     */
    public $amount;

    /**
     * @var string 平台UID
     */
    public $accountId;
    public $zoneid;
    public $channel;
    public $product_id;
    public $product_name;
    public $product_price;
    public $product_count;

    /**
     * @var string 公会id
     */
    public $party_id;
    public $party_name;

    /**
     * @var string 签名算法, 目前固定为MD5
     */
    public $signType = "MD5";

    /**
     *
     * @var string MD5(签名内容+apiKey)
     */
    public $sign;

    /**
     * @var int 订单编号
     */
    private $order_id;

    /**
     *
     * @return array 订单写入数据库
     */
    public function InserDataBase() {
//        return false;                                                           # 2019.10.9 关闭充值
        $arr = get_object_vars($this);                                          # 转为数组
        $arr["uid"] = $arr["accountId"];                                        # 转换下变量名称
        $arr["amount"] = $arr["amount"] * 100;                                  # 拉起平台时传的单位是元,比如UC还有易接,而游戏后台存储的是分
        unset($arr["signType"]);                                                # 毙掉后台不需要的数据
        unset($arr["sign"]);
        unset($arr["accountId"]);
        unset($arr['order_id']);
        $n = loyalsoft\daoInst()->update(self::orderTab)
                ->data($arr)
                ->where('id')->eq($this->order_id)
                ->exec();
        return $n == 1;
    }

    /**
     * @return array 拉取签名参数数组
     */
    public function uc_GetData2Sign() {
        $sid = array('callbackInfo', 'amount', 'notifyUrl', 'cpOrderId', 'accountId');
        $arr = array();
        foreach (get_object_vars($this) as $key => $value) {
            if (in_array($key, $sid)) {
                $arr[$key] = $value;
            }
        }
        return $arr;
    }

    /**
     * @return array 普通返回值数组
     */
    public function retData() {
        $sid = array('callbackInfo', 'amount', 'product_price', 'product_count', 'notifyUrl', 'cpOrderId');
        $arr = array();
        foreach (get_object_vars($this) as $key => $value) {
            if (in_array($key, $sid)) {
                $arr[$key] = $value;
            }
        }
        return $arr;
    }

    /**
     * @return array 小七手游订单结构(未签名)
     */
    public function x7sy_retData() {
        $ret = array(
            'extends_info_data' => $this->callbackInfo, //                      // 透传参数
            'game_area' => $this->zoneid,
            'game_guid' => $this->accountId,
            'game_level' => 0,
            'game_orderid' => $this->cpOrderId,
            'game_price' => $this->product_price, //                            // 对方要求单位:元
            'game_role_id' => "no",
            'game_role_name' => "no",
            'notify_id' => "3788", //                                             // 如果只有一个可以设置为-1,但不可以设置为0
            'subject' => $this->product_name
        );
        return $ret;
    }

    /**
     * @return array 易接返回值数组
     */
    public function yijie_retData() {
        return $this->retData();
    }

    public function __construct($arg = null) {
        parent::__construct($arg);

        if (!$this->accountId || !$this->amount || !$this->channel || !$this->product_id) {
            \loyalsoft\CLog::pay('参数缺失');
            exit('{"err":1,"msg":"参数缺失!"}');
        }

        if ($this->amount) {
            $this->amount = number_format($this->amount, 2, '.', '');
            if ('soft' == $this->channel) {                                   # 2018年1月15号以前固定为1分钱测试
                $this->amount = number_format(0.01, 2, '.', '');
                $this->product_price = 0.01;
            } else  //
            if ($this->amount != loyalsoft\GameConfig::shop_getItem($this->product_id)->price) {
                var_dump($this->product_id);
                var_dump(loyalsoft\GameConfig::shop_getItem($this->product_id)->price);
                \loyalsoft\CLog::pay('金额不符' . $this->amount . " ");
                exit('{"err":1,"msg":"金额不符!"}');
            }
        }
        loyalsoft\daoInst()->insert(self::orderTab)
                ->data(array('order_ts' => loyalsoft\now()))
                ->exec();
        $this->order_id = loyalsoft\daoInst()->select('last_insert_id() as id')->fetch('id');   # 订单自增id
        $this->cpOrderId = \date('ymdHi') . substr(sprintf("%1$06d", $order_id), -6);           # 商户唯一id(6位数)
        $this->callbackInfo .= "," . $this->cpOrderId;                                          # 将cpOrderId追加到透传参数中
        $this->notifyUrl = self::get_notify_url();                                              # 自动提取支付回调地址
    }

    /**
     * PS. 仅限pay.php作为入口使用才行
     * @return string 获取支付回调地址,
     */
    public static function get_notify_url() {
        $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"];
        $nurl = substr($url, 0, strpos($url, "pay.php")) . "notify.php";
        return $nurl;                                                           # 回调地址
    }

}
