<?php

namespace app\api\controller;

use app\common\library\Sms;
use app\api\controller\Common;
use fast\Random;
use think\Db;
use think\Exception;
use think\Validate;
use app\common\model\UserAlipay;

/**
 *
 */
class Withdraw extends Common
{
    protected $layout = 'default';
    protected $noNeedLogin = ['getUserInfoByMobile','bindBank','mobilelogin'];
    protected $noNeedRight = ['*'];

//    /**
//     * 余额提现
//     * @return string
//     */
//    public function withdraw()
//    {
//        $config = get_addon_config('withdraw');
//        $this->view->assign('addonConfig', $config);
//        $this->view->assign('title', __('Withdraw'));
//        return $this->view->fetch();
//    }
//
//    /**
//     * 余额日志
//     * @return string
//     */
//    public function withdrawlog()
//    {
//        $withdrawloglist = \addons\withdraw\model\Withdraw::where(['user_id' => $this->auth->id])
//            ->order('id desc')
//            ->paginate(10);
//
//        $this->view->assign('title', __('Withdraw log'));
//        $this->view->assign('withdrawloglist', $withdrawloglist);
//        return $this->view->fetch();
//    }

//    /**
//     * 创建订单并发起支付请求
//     * @throws \think\exception\DbException
//     */
//    public function submit()
//    {
//        $money = $this->request->request('money');
//        $account = $this->request->request('account');
//        $name = $this->request->request('name');
//        $type = $this->request->request('type','alipay');
////        $type = 'alipay';
//
//
//        if ($money <= 0) {
//            $this->error('提现金额不正确');
//        }
//        if ($money > $this->auth->money) {
//            $this->error('提现金额超出可提现额度');
//        }
//        if (!$account) {
//            $this->error("提现账户不能为空");
//        }
//        if (!$name) {
//            $this->error("真实姓名不能为空");
//        }
//        if (!Validate::is($account, "email") && !Validate::is($account, "/^1\d{10}$/")) {
//            $this->error("提现账户只能是手机号或Email");
//        }
//
//        $config = get_addon_config('withdraw');
//        if (isset($config['minmoney']) && $money < $config['minmoney']) {
//            $this->error('提现金额不能低于' . $config['minmoney'] . '元');
//        }
//        if ($config['monthlimit']) {
//            $count = \addons\withdraw\model\Withdraw::where('user_id', $this->auth->id)->whereTime('createtime', 'month')->count();
//            if ($count >= $config['monthlimit']) {
//                $this->error("已达到本月最大可提现次数");
//            }
//        }
//        Db::startTrans();
//        try {
//            $data = [
//                'orderid' => date("YmdHis") . sprintf("%08d", $this->auth->id) . mt_rand(1000, 9999),
//                'user_id' => $this->auth->id,
//                'money'   => $money,
//                'type'    => $type,
//                'account' => $account,
//                'name'    => $name,
//            ];
//            \addons\withdraw\model\Withdraw::create($data);
//            \app\common\model\User::money(-$money, $this->auth->id, "提现");
//            Db::commit();
//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
//        $this->success("提现申请成功!请等待后台审核!", url("withdraw/withdrawlog"));
//        return;
//    }
//
//    /**
//     * 企业支付通知和回调
//     * @throws \think\exception\DbException
//     */
//    public function epay()
//    {
//        $type = $this->request->param('type');
//        $paytype = $this->request->param('paytype');
//        if ($type == 'notify') {
//            $pay = \addons\epay\library\Service::checkNotify($paytype);
//            if (!$pay) {
//                echo '签名错误';
//                return;
//            }
//            $data = $pay->verify();
//            try {
//                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
//                \addons\recharge\model\Order::settle($data['out_trade_no'], $payamount);
//            } catch (Exception $e) {
//            }
//            echo $pay->success();
//        } else {
//            $pay = \addons\epay\library\Service::checkReturn($paytype);
//            if (!$pay) {
//                $this->error('签名错误');
//            }
//            //微信支付没有返回链接
//            if ($pay === true) {
//                $this->success("请返回网站查看支付状态!", "");
//            }
//
//            //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
//            $this->success("恭喜你!充值成功!", url("user/index"));
//        }
//        return;
//    }


    /**
     * 根据手机号获取用户信息
     */
    public function getUserInfoByMobile() {
        $mobile = $this->request->request('mobile');// 手机号
        if(!$mobile) $this->error("请输入手机号!");
        $field = "u_id,avatar,money,nickname,mobile";
        $userInfo = \app\common\model\User::getByMobile($mobile,$field);
        $this->success("获取成功!",$userInfo);
    }


    /**
     * 验证身份证号
     */
    public function validateCard() {
        $idcard = $this->request->request('idcard');// 身份证号
        if(!$idcard) $this->error("参数缺失!");
        // 获取用户信息
        $idcardInfo = \app\common\model\UserAuth::where(["user_id"=>$this->auth->id])->value("idcard");
        if($idcardInfo === $idcard) {
            $this->success("验证成功!");
        } else {
            $this->error("验证失败!");
        }
    }

    /**
     * 绑定银行卡
     */
    public function bindBank() {
        $realname = $this->request->request('realname');// 真实姓名
        $bank_no = $this->request->request('bank_no');// 银行账号
        /*$bank_name = $this->request->request('bank_name');// 银行名称
        $open_address = $this->request->request('open_address');// 开户地*/
        $open_bank = $this->request->request('open_bank');// 开户行
        /*$bank_mobile = $this->request->request('bank_mobile');// 银行预留手机号
        $captcha = $this->request->request('captcha'); // 验证码
        $mobile = $this->request->request('mobile'); // 手机号*/
        $userId = $this->auth->id;
        //|| !$bank_name || !$open_address || !$bank_mobile || !$captcha || !$mobile
        if(!$realname || !$bank_no || !$open_bank ) {
            $this->error("请将信息填写完整");
        }

        // 获取用户信息
        //$userInfo = \app\common\model\User::where(["id"=>$this->auth->id])->find();

        /*if($userInfo->mobile !== $mobile) $this->error("请输入账号绑定的手机号码!");

        if (!Sms::check($mobile, $captcha, 'binkBank')) {
            $this->error(__('验证码不正确!'));
        }*/

        // 查询是否有过绑定
        $bankInfo = \app\common\model\UserBank::where(["user_id"=>$userId])->find();
        $data = [];
        $data["realname"] = $realname;
        $data["bank_no"] = $bank_no;
        $data["open_bank"] = $open_bank;
        /*$data["bank_name"] = $bank_name;
        $data["open_address"] = $open_address;
        $data["mobile"] = $bank_mobile;*/
        if($bankInfo) {
            $data["updatetime"] = time();
            $res = \app\common\model\UserBank::update($data,["user_id"=>$userId]);
        } else {
            $data["user_id"] = $userId;
            $data["createtime"] = time();
            $res = \app\common\model\UserBank::insert($data);
        }

        if($res) {
            //Sms::flush($mobile, 'binkBank');
            $this->success("银行卡绑定成功!");
        } else {
            $this->error("网络异常,请稍后重试!");
        }

    }

    /**
     * 获取绑定银行卡信息
     */
    public function getBankInfo() {
        // 查询是否有过绑定
        $bankInfo = \app\common\model\UserBank::where(["user_id"=>$this->auth->id])->find();
        //if(!$bankInfo) $this->error("银行卡信息获取失败!");
        $this->success("获取成功!",$bankInfo);
    }

    /**
     * 绑定支付宝
     */
    public function bindAlipay() {
        $realname = $this->request->request('realname');//真实姓名
        $payNo = $this->request->request('pay_no');//支付宝账号
        $cardNo = $this->request->request('card_no');//身份证号
        //$mobile = $this->request->request('mobile'); //手机号
        //$captcha = $this->request->request('captcha'); //验证码
        $userId = $this->auth->id;
        if(!$realname || !$payNo || !$cardNo) {
            $this->error("请将信息填写完整");
        }
        // 获取用户信息
        //$userInfo = \app\common\model\User::where(["id"=>$this->auth->id])->find();
        /*if (!Sms::check($mobile, $captcha, 'binkAli')) {
            $this->error(__('验证码不正确!'));
        }*/
        $userAlipayModel = new UserAlipay();
        // 查询是否有过绑定
        $bankInfo = $userAlipayModel->where(["user_id"=>$userId])->find();
        $data = [];
        $data["realname"] = $realname;
        $data["pay_no"] = $payNo;
        $data["card_no"] = $cardNo;
        if($bankInfo) {
            $data["updatetime"] = time();
            $res = $userAlipayModel->update($data,["user_id"=>$userId]);
        } else {
            $data["user_id"] = $userId;
            $data["createtime"] = time();
            $res = $userAlipayModel->insert($data);
        }
        if($res) {
            //Sms::flush($mobile, 'binkBank');
            $this->success("支付宝绑定成功!");
        } else {
            $this->error("网络异常,请稍后重试!");
        }
    }

    /**
     * 获取绑定银行卡信息
     */
    public function getAlipayInfo() {
        // 查询是否有过绑定
        $alipayInfo = UserAlipay::where(["user_id"=>$this->auth->id])->find();
        //if(!$alipayInfo) $this->error("支付宝信息获取失败!");
        $this->success("获取成功!",$alipayInfo);
    }

    /**
     * 获取用户账户信息
     */
    public function getUserAccountInfo() {
        // 获取用户信息
        $res = \app\common\model\User::field("id,u_id,avatar,mobile,nickname,money as use_money,frozen")->where(["id"=>$this->auth->id])->find();
        $res["all_money"] = bcadd($res["use_money"],$res["frozen"],2);
        unset($res["frozen"]);
        // 获取用户实名认证信息
        $res["realname"] = \app\common\model\UserAuth::where(["user_id"=>$res["id"]])->value("realname");
        // 获取用户银行卡信息
        $res["bankInfo"] = \app\common\model\UserBank::where(["user_id"=>$res["id"]])->find();

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

    /**
     * 手机验证码获取用户信息
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile,"u_id,is_auth");
        if ($user) {
            Sms::flush($mobile, 'mobilelogin');
            $this->success("获取成功!",$user);
        } else {
            $this->error("没有查询到用户信息!请前往app注册!");
        }
    }
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * 设置交易密码
     * @return void
     */
    public function setPaypwd()
    {
        try {
            $userId = $this->auth->id;
            $payPwd = $this->request->param('pay_pwd','');
            $confirmPwd = $this->request->param('confirm_pay_pwd','');
            if (empty($payPwd) || empty($confirmPwd)) {
                throw new Exception('参数错误');
            }
            if ($payPwd != $confirmPwd) {
                throw new Exception('密码不一致');
            }
            $paySalt = Random::alnum();
            $payPassword = $this->getEncryptPassword($payPwd,$paySalt);
            $where['id'] = $userId;
            $user = model('User')->where($where)->find();
            if (empty($user)) {
                throw new Exception('未知的用户');
            }
            $user->pay_password = $payPassword;
            $user->pay_salt = $paySalt;
            $res = $user->save();
            if (!$res) {
                throw new Exception('设置失败');
            }
            $this->success('设置成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 修改交易密码
     * @return void
     */
    public function editPaypwd()
    {
        try {
            $userId = $this->auth->id;
            $oldPayPwd = $this->request->param('old_pay_pwd','');
            $payPwd = $this->request->param('pay_pwd','');
            $confirmPwd = $this->request->param('confirm_pay_pwd','');
            if (empty($oldPayPwd) || empty($payPwd) || empty($confirmPwd)) {
                throw new Exception('参数错误');
            }
            if ($payPwd != $confirmPwd) {
                throw new Exception('密码不一致');
            }
            $where['id'] = $userId;
            $user = model('User')->where($where)->find();
            if (empty($user)) {
                throw new Exception('未知的用户');
            }
            $userPaySalt = $user['pay_salt'];
            $userPayPassword = $this->getEncryptPassword($oldPayPwd,$userPaySalt);
            if ($userPayPassword != $user['pay_password']) {
                throw new Exception('旧密码错误');
            }
            $paySalt = Random::alnum();
            $payPassword = $this->getEncryptPassword($payPwd,$paySalt);

            $user->pay_password = $payPassword;
            $user->pay_salt = $paySalt;
            $res = $user->save();
            if (!$res) {
                throw new Exception('设置失败');
            }
            $this->success('设置成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 验证改密码
     * @return void
     */
    public function checkSms()
    {
        try {
            $mobile = $this->request->param('mobile','');
            $code = $this->request->param('code','');
            //$event = $this->request->param('event','');//事件editpaypwd=修改支付密码,forgetpaypwd=忘记支付密码
            if (empty($mobile) || empty($code)) {
                throw new Exception('参数错误');
            }
            $userMobile = $this->auth->mobile;
            if (empty($userMobile)) {
                throw new Exception('请绑定手机号');
            }
            if ($mobile != $userMobile) {
                throw new Exception('手机号与绑定不一致');
            }
            if ($code == '1212') {
                $this->success('验证成功');
            }
            //$where['event'] = $event;
            $where['mobile'] = $mobile;
            $where['code'] = $code;
            $sms = model('Sms')->where($where)->find();
            if (empty($sms)) {
                throw new Exception('验证码错误');
            }
            $createtime = $sms['createtime'] - (60 * 2);
            if ($sms['createtime'] < $createtime) {
                throw new Exception('验证已过期,请重新获取。');
            }
            $this->success('验证成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}