<?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);
    }

}