<?php

namespace app\api\controller;

use addons\epay\library\Service;
use think\Db;

/**
 * 钱包接口
 */
class Money extends Common
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * 充值
     */
    public function recharge() {
        $purpose = $this->request->request("purpose");// 充值用途 1=认证,2=有眼缘,3=购买会员, 4=充值钻石
        $type = $this->request->request("type","wechat");// 充值类型:wechat:微信支付,alipay:支付宝支付
        $method = "app";
        if(!in_array($purpose,[1,2,3,4]) || !in_array($type,['wechat','alipay'])) {
            $this->error(__('Invalid parameters'));
        }
//        if($type == 'wechat') $this->error(__('微信支付暂未开通!请选择支付宝支付!'));
        $user_id = $this->auth->id;
        $fate_user_id = 0;
        $vip_config_id = 0;

        switch ($purpose) {
            case 1:
                $title = "实名认证支付";
                $amount = config("site.auth");
                break;
            case 2:
                $fate_user_id = $this->request->request("fate_user_id",0); // 有眼缘用户ID
                if(!$fate_user_id) {
                    $this->error(__('Invalid parameters'));
                }
                $title = "有眼缘支付";
                $amount = config("site.fate");
                break;
            case 3:
                $vip_config_id = $this->request->request("vip_config_id",0);
                if(!$vip_config_id) {
                    $this->error(__('Invalid parameters'));
                }
                $title = "会员开通支付";
                // 获取会员配置信息
                if($vip_config_id <= 0) $this->error(__('Invalid parameters'));
                $vipConfigInfo = \app\admin\model\vip\Config::where(['id'=>$vip_config_id])->find();
                if (!$vipConfigInfo) {
                    $this->error('网络延迟,请稍后再试');
                }
                $amount = $vipConfigInfo['real_price'];
                break;
            case 4:
                $vip_config_id = $this->request->request("vip_config_id",0);
                if(!$vip_config_id) {
                    $this->error(__('Invalid parameters'));
                }
                $title = "钻石充值支付";
                // 获取会员配置信息
                if($vip_config_id <= 0) $this->error(__('Invalid parameters'));
                $vipConfigInfo = Db::name('diamond')->where(['id'=>$vip_config_id])->find();
                if (!$vipConfigInfo) {
                    $this->error('网络延迟,请稍后再试');
                }
                $amount = $vipConfigInfo['price'];
                break;
        }

        $out_trade_no = date("YmdHis").rand(100000,999999);

        $notifyurl = request()->root(true) . '/api/notify/notify/paytype/' . $type;
        $returnurl = request()->root(true) . '/addons/epay/api/returnx/type/' . $type;

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型错误");
        }
        $time = time();
        $money = $type == 'alipay' ? (float)bcadd($amount,0,2) : (float)bcadd($amount,0,2);

        // 生成订单
        $recharOrderMode = new \app\common\model\RecharOrder();
        $orderid = $recharOrderMode->execute("INSERT INTO `hx_rechar_order` (`user_id` , `order_no` , `vip_config_id`, `fate_user_id`, `money` ,`purpose`, `pay_type`, `createtime`) VALUES ($user_id , '$out_trade_no' , $vip_config_id, $fate_user_id, $money ,$purpose, '$type', $time)");
        if(!$orderid) $this->error("订单创建失败!");

        $params = [
            'type'         => $type,
            'orderid'      => $out_trade_no,
            'title'        => $title,
            'amount'       => $money,
            'method'       => $method,
            'notifyurl'    => $notifyurl,
            'returnurl'    => $returnurl,
        ];

        $result = Service::submitOrder($params);
        $this->success("参数获取成功!",$result);

    }



    /**
     * 提现
     */
    public function withdrow() {
        $money = $this->request->request("money");// 申请提现的金额
        $withdrawMax = config('site.withdrawMax'); // 最高提现金额
        $withdrawCount = config('site.withdrawCount'); // 每天提现次数
        $withdrawallogModel = new \app\common\model\UserWithdrawLog();
        if($money <= 0 || $money > $withdrawMax) {
            $this->error(__('提现金额范围:10-'.$withdrawMax));
        }
        if(intval($money) != $money) {
            $this->error(__('提现金额必须整数!'));
        }
        if($money%10 !== 0) {
            $this->error(__('提现金额必须为10的倍数!'));
        }
        // 获取今天的提现次数
        $starttime = strtotime(date("Y-m-d 00:00:00"));
        $endtime = strtotime(date("Y-m-d 23:59:59"));
        $where = [];
        $where["user_id"] = $this->auth->id;
        $where["status"] = ['in',[0,1]]; // 提现状态:-1=审核拒绝,0=待审核,1=审核通过
        $where["createtime"] = ["between","$starttime,$endtime"];
        $withdrawCountInfo = $withdrawallogModel->where($where)->count('id');
        if($withdrawCountInfo >= $withdrawCount) {
            $this->error(__('今日提现次数已达上线!'));
        }

        // 判断当前用户是否实名认证
        $userAuthInfo = \app\common\model\UserAuth::userIsAuth($this->auth->id);
        if($userAuthInfo['status'] == 0) $this->error($userAuthInfo['msg']);

        // 查询资金余额
        $userModel = new \app\common\model\User();
        $userInfo = $userModel->get($this->auth->id);
        if($money > $userInfo["money"]) {
            $this->error("资金余额不足!");
        }

        Db::startTrans();
        try{
            // 减去用户可用资金余额
            $res1 = $userModel->where(["id"=>$this->auth->id])->setDec("money",$money);
            // 增加用户冻结资金余额
            $res2 = $userModel->where(["id"=>$this->auth->id])->setInc("frozen",$money);
            // 新增用户提现记录申请
            $data = [];
            $data["user_id"] = $this->auth->id;
            $data["money"] = $money;
            $data["status"] = 0; // 提现状态:-1=审核拒绝,0=待审核,1=审核通过
            $data["createtime"] = time();
            $res3 = $withdrawallogModel->insert($data);
            if($res1 && $res2 && $res3) {
                Db::commit();
                $this->success("提现申请发送成功!");
            } else {
                $this->error("操作失败!");
            }
        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }


    /**
     * 获取用户提现记录
     */
    public function withdrowRecord() {
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;
        $res = \app\common\model\UserWithdrawLog::where(["user_id"=>$this->auth->id])->limit($pageStart,$pageNum)->order("createtime","desc")->select();
        if($res) {
            $statusTxt = array("-1"=>"审核拒绝","0"=>"待审核","1"=>"审核通过");
            foreach($res as $k => &$v) {
                $v["status"] = $statusTxt[$v["status"]];
                $v["money"] = $v["money"]>0?$v["money"]:0;
                $v["createtime"] = date("Y-m-d H:i:s",$v["createtime"]);
            }
        }
        $this->success("获取成功!",$res);
    }

    /**
     * 获取收入明细
     */
    public function getRebateList() {
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;

        $res = [];
        $res['money_count']= \app\common\model\User::where(["id"=>$this->auth->id])->value("money");
        $where = [];
        $where["user_id"] = $this->auth->id;
        $res['money_log'] = \app\common\model\UserProfitLog::where($where)->limit($pageStart,$pageNum)->order("createtime","desc")->select();
        if($res['money_log']) foreach($res['money_log'] as $k => &$v) {
            $v["createtime"] = date("Y-m-d H:i:s", $v["createtime"]);
        }
        $this->success("获取成功!",$res);
    }

    //获取钻石明细
    public function getdiamondlog() {
        $page = $this->request->request('page', 1, 'intval'); // 分页
        $pageNum = $this->request->request('pageNum', 10, 'intval'); // 分页

        $list = Db::name('user_diamond_log')->where(['user_id' => $this->auth->id])->order('id', 'desc')->page($page, $pageNum)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['createtime'] = date("Y-m-d H:i:s", $v["createtime"]);
            }
        }

        $this->success('获取钻石明细', $list);
    }

    //苹果内购充值钻石
    public function iospay() {
        $purpose = 4;//$this->request->request("purpose");// 充值用途 1=认证,2=有眼缘,3=购买会员, 4=充值钻石
//        $type = $this->request->request("type","wechat");// 充值类型:wechat:微信支付,alipay:支付宝支付
//        $method = "app";
//        if(!in_array($purpose,[1,2,3,4]) || !in_array($type,['wechat','alipay'])) {
//            $this->error(__('Invalid parameters'));
//        }
        if(!in_array($purpose,[1,2,3,4])) {
            $this->error(__('Invalid parameters'));
        }
//        if($type == 'wechat') $this->error(__('微信支付暂未开通!请选择支付宝支付!'));
        $user_id = $this->auth->id;
        $fate_user_id = 0;
        $vip_config_id = 0;

        switch ($purpose) {
            case 1:
                $title = "实名认证支付";
                $amount = config("site.auth");
                break;
            case 2:
                $fate_user_id = $this->request->request("fate_user_id",0); // 有眼缘用户ID
                if(!$fate_user_id) {
                    $this->error(__('Invalid parameters'));
                }
                $title = "有眼缘支付";
                $amount = config("site.fate");
                break;
            case 3:
                $vip_config_id = $this->request->request("vip_config_id",0);
                if(!$vip_config_id) {
                    $this->error(__('Invalid parameters'));
                }
                $title = "会员开通支付";
                // 获取会员配置信息
                if($vip_config_id <= 0) $this->error(__('Invalid parameters'));
                $vipConfigInfo = \app\admin\model\vip\Config::where(['id'=>$vip_config_id])->find();
                if (!$vipConfigInfo) {
                    $this->error('网络延迟,请稍后再试');
                }
                $amount = $vipConfigInfo['real_price'];
                break;
            case 4:
                $vip_config_id = $this->request->request("vip_config_id",0);
                if(!$vip_config_id) {
                    $this->error(__('Invalid parameters'));
                }
                $title = "钻石充值支付";
                // 获取会员配置信息
                if($vip_config_id <= 0) $this->error(__('Invalid parameters'));
                $vipConfigInfo = Db::name('diamond_ios')->where(['id'=>$vip_config_id])->find();
                if (!$vipConfigInfo) {
                    $this->error('网络延迟,请稍后再试');
                }
                $amount = $vipConfigInfo['price'];
                break;
        }

        $out_trade_no = date("YmdHis").rand(100000,999999);

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        $time = time();
        $money = $amount;
        $type = '苹果内购';

        // 生成订单
        $recharOrderMode = new \app\common\model\RecharOrder();
        $orderid = $recharOrderMode->execute("INSERT INTO `hx_rechar_order` (`user_id` , `order_no` , `vip_config_id`, `fate_user_id`, `money` ,`purpose`, `pay_type`, `createtime`) VALUES ($user_id , '$out_trade_no' , $vip_config_id, $fate_user_id, $money ,$purpose, '$type', $time)");
        if(!$orderid) $this->error("订单创建失败!");

        $this->success("参数获取成功!", $out_trade_no);
    }

    // 内购支付回调
    public function iosresult() {
        //苹果内购的验证收据
        $receipt_data = input('apple_receipt', '', 'trim');
        $order_no = input('order_no', '', 'trim');

        //error_log(print_r($receipt_data, 1), 3, './receipt_data.txt');
        if (!$receipt_data || !$order_no) {
            $this->error('缺少参数');
        }

        // 查找订单
        $Order = Db::name('rechar_order');
        $order_info = $Order->where(array('order_no' => $order_no))->find();
        if (!$order_info) {
            //error_log(print_r(11, 1), 3, './11.txt');
            $this->error('订单丢失');
        }
        if ($order_info['status'] == 1) {
            $this->success('购买成功');
        }
        //查询bundle_id
        $vipConfigInfo = Db::name('diamond_ios')->where(['id' => $order_info['vip_config_id']])->find();
        if (!$vipConfigInfo) {
            $this->error('数据丢失');
        }

        // 验证支付状态
        $result = $this->validate_apple_pay($receipt_data);
        if (!$result['status']) {
            // 验证不通过
            //error_log(print_r($result, 1), 3, './result.txt');
            $this->error($result['message']);
        }

        $count = count($result['data']['receipt']['in_app']);
        $use_count = $count - 1;
        //p($apple_id);p($result['data']['receipt']['in_app'][$use_count]['product_id']);die;
//        if ($result['data']['receipt']['in_app'][$use_count]['product_id'] != 'com.lnkj.authentication.3') {
        if ($result['data']['receipt']['in_app'][$use_count]['product_id'] != $vipConfigInfo['product_id']) {
            $this->error('非法请求,请立刻停止');
        }

        Db::startTrans();
        // 获取钻石配置信息
        $userInfo = Db::name('user')->where(['id' => $order_info['user_id']])->find();
        // 修改订单状态
        $res1 = $Order->update(["status"=>1,"updatetime"=>time()],["order_no"=>$order_no, 'status' => 0]);
        //修改用户钻石余额
        $diamond = $userInfo['diamond'] + $vipConfigInfo['number'];
        $res2 = Db::name('user')->where(['id' => $userInfo['id'], 'diamond' => $userInfo['diamond']])->setField('diamond', $diamond);
        // 添加钻石明细
        $diamond_log = Db::name('user_diamond_log')->where(['user_id' => $userInfo['id']])->order('id', 'desc')->find();
        if (!$diamond_log && $userInfo['diamond'] > 0) {
            $res3 = false;
        }
        if ($diamond_log && $diamond_log['after'] != $userInfo['diamond']) {
            $res3 = false;
        }
        if ($res3) {
            $data = [];
            $data['user_id'] = $userInfo['id'];
            $data['diamond'] = $vipConfigInfo['number'];
            $data['before'] = $userInfo['diamond'];
            $data['after'] = $diamond;
            $data['memo'] = '充值';
            $data['createtime'] = time();

            $res3 = Db::name('user_diamond_log')->insertGetId($data);
        }
        if($res1 && $res2 !== false && $res3) {
            Db::commit();
            $this->success('购买成功');
        } else {
            Db::rollback();
            $this->error('购买失败');
        }
    }

    /**
     * 验证AppStore内付
     * @param string $receipt_data 付款后凭证
     * @return array                验证是否成功
     */
    function validate_apple_pay($receipt_data = '') {
        // 验证参数
        if (strlen($receipt_data) < 20) {
            $result = array(
                'status' => false,
                'message' => '非法参数'
            );
            return $result;
        }
        // 请求验证
        $html = $this->curl($receipt_data);
        $data = json_decode($html, true);
//        p($data);die;

        if ($data['status'] == '21002') {
            $this->error('21002');
        }

        // 如果是沙盒数据 则验证沙盒模式 21008;正式数据 21007
//        if ($data['status'] == '21007') {
//            // 请求验证
//            $html = $this->curl($receipt_data, 1);
//            $data = json_decode($html, true);
//            $data['sandbox'] = '1';
//        }
        if (isset($_GET['debug'])) {
            exit(json_encode($data));
        }
//        if ($data['receipt']['bundle_id'] != 'com.liuniukeji.mayivideo') {
        if ($data['receipt']['bundle_id'] != 'com.nuoruiyang.fate') {
            $result = array(
                'status' => false,
                'message' => '非法请求',
                'data' => $data
            );
            return $result;
        }
        // 判断是否购买成功
        if (intval($data['status']) === 0) {
            $result = array(
                'status' => true,
                'message' => '购买成功',
                'data' => $data
            );
        } else {
            $result = array(
                'status' => false,
                'message' => '购买失败 status:' . $data['status']
            );
        }

        return $result;
    }

    /**
     * 21000 App Store不能读取你提供的JSON对象25
     * 21002 receipt-data域的数据有问题
     * 21003 receipt无法通过验证
     * 21004 提供的shared secret不匹配你账号中的shared secret
     * 21005 receipt服务器当前不可用
     * 21006 receipt合法,但是订阅已过期。服务器接收到这个状态码时,receipt数据仍然会解码并一起发送
     * 21007 receipt是Sandbox receipt,但却发送至生产系统的验证服务
     * 21008 receipt是生产receipt,但却发送至Sandbox环境的验证服务
     */
    function curl($receipt_data, $sandbox = 0) {
        //小票信息
        $POSTFIELDS = array("receipt-data" => $receipt_data);
        $POSTFIELDS = json_encode($POSTFIELDS);
//        $POSTFIELDS = '{' . '"receipt-data":' . '"' . $receipt_data . '"' .'}';
//        p($POSTFIELDS);die;
        //正式购买地址 沙盒购买地址
        $url_buy = "https://buy.itunes.apple.com/verifyReceipt";
        $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";

//        if ($sandbox > 0) {
        if (config('site.ios_pay_sandbox') > 0) {
            $url = $url_buy;
        } else {
            $url = $url_sandbox;
        }

        // 上架通过直接使用正式地址
//        $url = $url_sandbox;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);  //这两行一定要加,不加会报SSL 错误
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        curl_close($ch);

        if ($errno != 0) {
            return $errno;
        } else {
            return $response;
        }

    }

}