<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/9
 * Time: 15:07
 */
include PATH_MOD . 'msgtip.php';
class ModelPaymentVnpt
{

    private $_vnptList = [
        'vinaphone' => [
            'type' => 'VNP',
            'urlCode' => 'VINA'
        ],
        'mobifone' => [
            'type' => 'VMS',
            'urlCode' => 'MOBI'
        ],
        'viettel' => [
            'type' => 'VTT',
            'urlCode' => 'VIETTEL'
        ]
    ];

    protected $goodsTable;//商品表
    protected $summaryListTable;//订单汇总表
    public function __construct()
    {
        $this->goodsTable = otable::goods();
        $this->summaryListTable = otable::summarylist();
    }

    /**
     * 发起支付
     * @param $orderId
     * @param $type
     * @param $Seri
     * @param $passwd
     * @return  string
     */
    public function createPayment($orderId, $payOperator , $serial, $passwd)
    {
        $txtType = $this->_vnptList[$payOperator]['type'] ?? '';
        $txtUrlCode = $this->_vnptList[$payOperator]['urlCode'] ?? '';
        if(empty($txtType) || empty($txtUrlCode) || empty($serial) || empty($passwd) || empty($orderId)) {
            oo::logs()->debug3('param:  operator:'.$payOperator.' txttype:'.$txtType.'  urlCode:'.$txtUrlCode.'  card:'.$serial.'  passwd:'.$passwd.'  orderId:'.$orderId, 'vnptpayment_fail.php');
            return oo::res(-1);
        }

        $result = oo::vnpt()->cardCharging($orderId, $txtType, $txtUrlCode, $serial, $passwd);
        $response = $this->getResponseInfo($result);
        if(isset($response['code']) && $response['code'] === 0) {//充值成功
            $price = $response['amount'];
            $ret = $this->vnptDelivery($orderId, $price, $payOperator);
            if($ret) {
                return oo::res(1);
            }else {
                oo::logs()->debug3('errormsg:发货失败  orderId:'.$orderId.'  operator:'.$payOperator, 'vnptpayment_fail.php');
                return oo::res(-2);//发货失败
            }
        }else {
            $msg = $response['msg'];
            oo::logs()->debug3('errormsg:'.$msg.' orderId:'.$orderId.'  operator:'.$payOperator, 'vnptpayment_fail.php');
            $resultCode = $response['result_code'];

            if('06' == $resultCode) {
                $code = -3;//卡号卡密不对
            }else if('05' == $resultCode) {
                $code = -4;//卡已使用过
            }else if('07' == $resultCode) {
                $code = -5;//卡无效未激活或过期
            }else {
                $code = -6;
            }
            return oo::res($code);//充值失败
        }
    }




    /**
     * 当计费类型为充值卡,并且价格不匹配时,重新查找价格对应的商品, 找到后重新修改
     * 因为客户端下单时候,无法确认商品ID
     * @param int $orderId
     */
    protected function checkPriceAgain($price, $orderId = 0, $operator = 0, $uid = 0 ){
        if( $operator == 'test' ){
            $sql = " SELECT gid, gprice, gpriceThb FROM {$this->goodsTable} WHERE gchannel IN(9,10,11) ";
        }else{
            $gchannel = $operator;//支付商品渠道
            if( empty($gchannel) ){
                return false;
            }
            $gplatform = 1;
            //查询价格,和商品ID
            $sql = " SELECT gid, gprice, gpriceThb FROM {$this->goodsTable} WHERE gchannel = {$gchannel} AND gplatform = {$gplatform} AND gstatus = 1 ";
        }
        $goodsList = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        if( empty($goodsList) ){
            return false;
        }

        $sl_gid = $sl_pusd = 0;//新的商品ID和价格(美元)
        foreach ($goodsList as $info){
            if( $info['gpriceThb'] == $price ){
                $sl_gid = intval($info['gid']);
                $sl_pusd = $info['gprice'];
                break;
            }
        }
        if( $sl_gid == 0 ){
            return false;
        }

        //更新订单汇总表
        $sqlU = " UPDATE {$this->summaryListTable} SET sl_gid = {$sl_gid}, sl_pusd = '{$sl_pusd}' WHERE sl_orderid = {$orderId} LIMIT 1";
        oo::commonOprDb('common')->query($sqlU);

        //更新玩家订单表中的订单ID
        $paymentTable = otable::payment($uid);
        $sqlPayment = " UPDATE {$paymentTable} SET gid = {$sl_gid}, pusd = '{$sl_pusd}' WHERE uid = {$uid} AND order_id = {$orderId} LIMIT 1 ";
        oo::commonOprDb('common')->query($sqlPayment);

        return true;
    }

    /**
     * 验证发货
     * @param $orderId
     * @param $price
     * @param int $operator
     * @return bool
     */
    public function vnptDelivery($orderId, $price, $operator = 9)
    {

        $now = time();
        //验证订单是否正确
        $sqlSummarylist = " SELECT sl_gid, sl_uid, sl_status FROM {$this->summaryListTable} WHERE sl_orderid = {$orderId} LIMIT 1 ";
        $ret = oo::commonOprDb('common')->getOne($sqlSummarylist, MYSQLI_ASSOC);
        if (empty($ret)) {
            oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'orderIdError', 'time' => $now),'vnptpayment_fail.log');
            return false;
        }

        $uid = $ret['sl_uid'];
        //验证订单状态,是否已经支付过
        $status = intval($ret['sl_status']);
        if( $status == 2){
            oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'alreadyPayed', 'time' => $now),'vnptpayment_fail.log');
            return false;
        }

        //验证商品信息是否正确
        $gid = $ret['sl_gid'];
        $sqlGoodsInfo = " SELECT gpriceThb FROM {$this->goodsTable} WHERE gid = {$gid} LIMIT 1 ";
        $retGoods = oo::commonOprDb('common')->getOne($sqlGoodsInfo, MYSQLI_ASSOC);
        if (empty($retGoods)) {
            oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'getGoodsErr', 'sqlGoodsInfo' => $sqlGoodsInfo, 'time' => $now),'vnptpayment_fail.log');
            return false;
        }

        //验证价格是否匹配
        $gprice = intval($retGoods['gpriceThb']);
        if( $price != $gprice ){
            $checkPriceAgain = $this->checkPriceAgain($price, $orderId, $operator, $uid);
            if( !$checkPriceAgain ){
                oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'priceError', 'operator' => $operator, 'price' => $price, 'gprice' => $gprice, 'time' => $now),'vnptpayment_fail.log');
                return false;
            }
        }

        //验证通过后,可以发奖了
        $retReward = oo::commonOprModel('payment')->pubDelivery($uid, $orderId);
        return $retReward;
    }


    /**
     * 处理返回信息
     * @param $vnptResult
     * @return array
     */
    public function getResponseInfo($vnptResult){
        $respones = [];
        if(strpos($vnptResult,'RESULT:10') !== false){
            $respones['code']        = 0;  //充值成功
            $respones['result_code'] = '10';
            $respones['amount']      = intval(str_replace('RESULT:10@','',$vnptResult));
        }else{
            $respones['code']        = 1;  //充值失败
            $respones['result_code'] = trim(substr($vnptResult,7,2));
            $respones['amount']      = 0;
        }

        switch ($respones['result_code']){
            case '99':
                $respones['msg'] = msgtip::VNPT_IP_NOTALLOW;
                break;
            case '00':
                $respones['msg'] = msgtip::VNPT_SYSTEM_MAINTENANCE;
                break;
            case '01':
                $respones['msg'] = msgtip::VNPT_MD5KEY_ERROR;
                break;
            case '02':
                $respones['msg'] = msgtip::VNPT_CARD_SERVICENOTEXIT;
                break;
            case '03':
                $respones['msg'] = msgtip::VNPT_SERIALORPIN_WRONGFORMAT;
                break;
            case '04':
                $respones['msg'] = msgtip::VNPT_PARTNERID_NOTEXIT;
                break;
            case '05':
                $respones['msg'] = msgtip::VNPT_CARD_USEDBEFOR;
                break;
            case '06':
                $respones['msg'] = msgtip::VNPT_SERIALORPIN_ISINCORRECT;
                break;
            case '07':
                $respones['msg'] = msgtip::VNPT_SERIAL_INVALID;
                break;
            case '08':
                $respones['msg'] = msgtip::VNPT_CARD_EXIST;
                break;
            case '09':
                $respones['msg'] = msgtip::VNPT_CHANNEL_INACTIVE;
                break;
            case '10':
                $respones['msg'] = msgtip::K3_SUCCEED;
                break;
            case '11':
                $respones['msg'] = msgtip::DELAY_PENDING;
                break;
            case '12':
                $respones['msg'] = msgtip::VNPT_SERI_LENGTHERROR;
                break;
            default:
                $respones['msg'] = msgtip::VNPT_BADCARD_DATA;
                break;
        }
        return $respones;
    }


}