<?php

/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2022/10/28
 * Time: 14:17
 */

namespace app\api\controller;

use app\admin\model\Addr;
use app\admin\model\device\Chargedevice;
use app\admin\model\UserMoneyLog;
use app\admin\model\users\Agent;
use app\admin\model\users\Bankcard;
use app\admin\model\users\Users as UsersModel;
use app\admin\model\users\UsersAddr;
use app\admin\model\users\UserTranfer;
use app\admin\model\users\Withdraw;
use app\admin\model\users\Agent as AgentModel;
use app\api\model\PaymentLogModel;
use app\common\controller\Api;
use app\lib\utils\ErrorInfo;
use app\lib\utils\WXPay\WXPayConstants;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;
use app\common\library\Redis\RedisMaster;
use EasyWeChat\Factory;
use fast\Random;
use app\common\library\wechat\WxUser;
use think\Cache;
use think\Session;

class Users extends Api
{
    protected $noNeedLogin = ['wxlogin', 'create_code','createcode','querymerchantdetails'];
    protected $noNeedRight = ['*'];

    /*
     * 微信小程序授权登录
     *
     */
    public function wxLogin()
    {
        $data = $this->request->param();
        $login_config = [
            'app_id' => config('wx_appid'),
            'secret' => config('wx_apikey'),
        ];
        if (!$data['code'] && !$data['session_key']) {
            $this->error('授权失败');
        }
        if ($data['code'] && !$data['session_key']) {
            $session = $this->getOpenid($data['code']);
            //            Log:record('wx_openid:' . $session['openid'], 'debug');
            //            Log::record('session_key:' . $session['session_key'], 'debug');
            $this->miniProgram = Factory::miniProgram($login_config);
            if (!$session['session_key'] || !$session['openid'] || !$data['encryptedData'] || !$data['iv']) {
                $this->error('必要参数缺失');
            }
            $res = UsersModel::where(['unionid' => $session['unionid']])->find();
            $token = Random::uuid(); //用户token
            $redis = RedisMaster::gi();
            $redis->select(6);
            if ($res) {
                $prefix = 'user_token:' . $res['token'];
                $uid = $redis->get($prefix);
                if ($uid) {
                    $redis->delete($prefix);
                    $redis->setEx('user_token:' . $token, 86400 * 180, $uid);
                    Session::pull($prefix);
                    Session::set('user_token:' . $token, $uid, 86400 * 180);
                    Cache::pull($prefix);
                    Cache::set('user_token:' . $token, $uid, 86400 * 180);
                } else {
                    $redis->setEx('user_token:' . $token, 86400 * 180, $res['id']);
                    Cache::set('user_token:' . $token, $res['id'], 86400 * 180);
                    Session::set('user_token:' . $token, $res['id'], 86400 * 180);
                }
                UsersModel::where(['id' => $res['id']])->update(['user_type' => 'wechat', 'session_key' => $session['session_key'], 'wx_openid' => $session['openid'], 'token' => $token]);
                $userInfos = UsersModel::where(['id' => $res['id']])->find();
                $flag = true;
            } else {
                //解密获取用户信息
                $userInfo = $this->miniProgram->encryptor->decryptData($session['session_key'], $data['iv'], $data['encryptedData']);
                $session_key = $session['session_key'];
                $salt = Random::alnum();
                $users_arr = [
                    'nickname' => $userInfo['nickName'],
                    'sex' => $userInfo['gender'],
                    'city' => $userInfo['city'],
                    'province' => $userInfo['province'],
                    'avatar' => $userInfo['avatarUrl'],
                    'wx_openid' => $session['openid'],
                    'session_key' => $session_key,
                    'token' => $token,
                    'unionid' => $session['unionid'],
                    'logintime' => time(),
                    'jointime' => time(),
                    'loginip' => $this->request->ip(),
                    'salt' => $salt,
                    'random_number' =>$this->recursion(),
//                    'random_number' =>createRandomcode(),
                ];
                $users = UsersModel::create($users_arr);

                $redis->setEx('user_token:' . $token, 86400 * 180, $users->id);
                Cache::set('user_token:' . $token, $users->id, 86400 * 180);
                Session::set('user_token:' . $token, $users->id, 86400 * 180);
                $userInfos = $users->toArray();
                $flag = true;
            }
        } else { //直接登录
            $userInfos = UsersModel::where(['session_key' => $data['session_key']])->find();
            if ($userInfos) {
                $flag = true;
            }
        }

        if (isset($flag) && $flag) {
            $this->success('登录成功', [
                'userInfo' => $userInfos,
            ]);
        } else {
            $this->error('登录失败');
        }
    }

    /**
     * 获取头像昵称
     */
    public function getAvatar()
    {
        $nickname = $this->request->post('nickname', '');
        $avatar = $this->request->post('avatar', '');
        $uid = $this->auth->id;
        $userinfo = UsersModel::where(['id' => $uid])->find();
        if ($nickname) {
            if ($userinfo['nickname'] == '微信用户' || !$userinfo['nickname'] || $nickname != $userinfo['nickname']) {
                UsersModel::where(['id' => $uid])->update(['nickname' => $nickname]);
            }
        }
        if ($avatar) {
            if ($avatar != $userinfo['avatar'] || !$userinfo['avatar']) {
                UsersModel::where(['id' => $uid])->update(['avatar' => $avatar]);
            }
        }
        $this->success('', '获取成功');
    }

    /**
     * 获取用户基本信息
     */
    public function getUserInfo()
    {
        $uid = $this->auth->id;
        if (!$uid) {
            $this->error('用户不存在');
        }
        $userinfo = UsersModel::where(['id' => $uid])->find();
        if (!$userinfo) {
            $this->error('获取用户信息失败');
        }
        $userinfo['invite_device_num'] = \app\admin\model\order\Order::where(['share_id' => $uid, 'sale_status' => 2])->sum('num'); //推广设备数
        $userinfo['recharge_amount'] = Config::get('site.recharge_gift_pack');
        //股东身份判断，有股权或股票时视为股东
        $userinfo['shareholder'] = 0;
        if ($userinfo['equity'] > 0) {
            $userinfo['shareholder'] = 1;
        }
        $userinfo['withdraw_rule1'] = '1、每日提现审核服务时间【10:00-15:00】';
        $userinfo['withdraw_rule2'] = '2、单个账户日提现金额不超过5000元，单笔提现金额不超过500元（整数提现）';
        $userinfo['withdraw_rule3'] = '3、单笔提现手续费1%';

        $this->success('获取用户信息成功', ['userinfo' => $userinfo, 'shareholder' => $userinfo['shareholder']]);
    }

    /**
     * 身份接口
     */
    public function getUserLevel()
    {
        $uid = $this->auth->id;
        if (!$uid) {
            $this->error('用户不存在');
        }
        $agentInfo = AgentModel::where(['agent_user_id' => $uid, 'status' => 1, 'level' => ['>', 0]])->find();
        if (!$agentInfo) {
            $agentInfo['level'] = 0;
            $this->success('获取用户信息成功', ['agentInfo' => $agentInfo]);
        }
        $this->success('获取用户信息成功', ['agentInfo' => $agentInfo]);
    }
    /**
     * 我的收入(包括单个设备的收入)
     */
    public function myIncome()
    {
        $charge_device_sn = $this->request->post('charge_device_sn', ''); //充电桩外壳编号
        $year = (int)$this->request->post('year', date('Y'));
        $uid = $this->auth->id;
        $userinfo = UsersModel::where(['id' => $uid])->find();
        if ($year < date('Y') &&  $year >= date('Y', $userinfo['jointime'])) {
            $month = 12;
        } else {
            $month = (int)date('m');
        }
        $data = [];
        $month_arr = [];
        for ($i = 0; $i <= $month - 1; $i++) {
            $data[$i]['recharge_money'] = $this->sumMoney($year, $i, $uid, 0) + $this->sumMoney($year, $i, $uid, 6); //月度充电总收入+固定分红收益
            $data[$i]['Advert_money'] = $this->sumMoney($year, $i, $uid, 4); //月度广告总收入
            $data[$i]['recharge_month_money'] = $this->sumMoney($year, $i, $uid, 2); //月度包月总收入
            $data[$i]['reward_month_money'] = \app\admin\model\order\Order::where(['user_id' => $uid, 'order_type' => ['in', [7, 8]], 'createtime' => ['between', [mktime(0, 0, 0, $i + 1, 1, $year), mktime(0, 0, 0, $i + 2, 1, $year)]]])->sum('need_pay'); //月度奖励
            $data[$i]['total_month_money'] = $this->sumMoney($year, $i, $uid) + $data[$i]['reward_month_money']; //月度总收入
            $data[$i]['month'] = ($i + 1) . '月收入'; //月份
            $month_arr[] = $i + 1;
        }
        array_multisort($month_arr, SORT_DESC, $data);
        //总奖励
        $reward_money = \app\admin\model\order\Order::where(['user_id' => $uid, 'order_type' => ['in', [7, 8]]])->sum('need_pay');
        //总收入
        $total_money = $this->sumMoney(0, 0, $uid, -1, $charge_device_sn) + $reward_money;
        $this->success('获取成功', ['data' => $data, 'total_money' => $total_money]);
    }

    protected function sumMoney($year, $i, $uid, $order_type = -1, $charge_device_sn = '')
    {
        $where = ['cd.user_id' => $uid];
        if ($charge_device_sn) {
            $where['o.device_sign'] = $charge_device_sn;
        }
        if ($year) {
            $start_time = mktime(0, 0, 0, $i + 1, 1, $year);
            $end_time = mktime(0, 0, 0, $i + 2, 1, $year);
            $where['o.createtime'] = ['between', [$start_time, $end_time]];
        }
        if ($order_type != -1) {
            $where['o.order_type'] = $order_type;
        }
        $order_money = Chargedevice::alias('cd')
            ->join('order o', 'cd.charge_device_sn = o.device_sign', 'left')
            ->where($where)
            ->sum('o.need_pay');
        return $order_money = sprintf("%.2f", $order_money);
    }

    /**
     * 提现
     */
    public function withdraw()
    {
        $user_id = $this->auth->id;
        $money = abs((int)($this->request->post("money", 0)) * 100); //提现金额（分）
        $withdraw_way = (int)$this->request->post("withdraw_way", 1); //提现方式:1=提现至零钱,2=提现至银行卡
        $bankcard_id = $this->request->post('bankcard_id', 0); //银行卡id
        $mobile = $this->request->post('mobile', 0); //手机号
        $realname = $this->request->post('realname', ''); //真实姓名
        //        $code = $this->request->param('code'); //手机验证码
        $switchCash = config('switchCash');
        if ($switchCash != 'on') {
            $this->error('提现入口暂时关闭');
        }

        if (!$realname) {
            $this->error('请填写真实姓名');
        }
        if ($money <= 0 || !is_integer($money)) {
            $this->error("输入金额有误");
        } else if ($money < 100) {
            $this->error("最低提现1元！");
        } else if ($money > 50000) {
            $this->error("单笔最高提现500元！");
        }
        if ($money > $this->auth->total_money * 100) {
            $this->error("输入金额不可大于钱包金额");
        }
        $withdrawcount = Withdraw::where(['user_id' => $user_id, 'status' => ['neq', -1]])->whereTime('start_time', 'today')->count();
        if ($withdrawcount >= 10) {
            $this->error("每天提现不能超过10次");
        }
        $data = [
            'cash_sn' => getOrdersn('withdraw'),
            'user_id' => $user_id,
            'name' => $realname,
            'tel' => $mobile,
            'money' => $money,
            'start_time' => time(),
            'withdraw_way' => $withdraw_way,

        ];
        if ($withdraw_way == 2) {
            $bankcard = Bankcard::where(['id' => $bankcard_id])->find();
            if (!$bankcard) {
                $this->error('银行卡不存在');
            }
            if ($money < 50 * 100) {
                $this->error('银行卡提现最低50元！');
            }
            $data['bank_name'] = $bankcard['bank_name'];
            $data['bank_num'] = $bankcard['bank_num'];
        }
        try {
            Db::startTrans();
            $res = Withdraw::create($data);
            $cut_money = sprintf("%.2f", $money / 100);
            UsersModel::where(['id' => $user_id])->setDec('total_money', $cut_money);
            $userinfo = UsersModel::where(['id' => $user_id])->find();
            if ($userinfo['total_money'] < 0) {
                Db::rollback();
                $this->error('不可再提现');
            }
            if ($res->toArray()) {
                Db::commit();
                $this->success('提现申请成功,待审核', ['data' => $res->toArray()]);
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('提现申请成失败' . $e->getMessage());
        }
    }

    /**
     * 添加银行卡
     * @param $code
     */
    public function addBankCard()
    {
        $name = $this->request->param('name', '');
        $bank_name = $this->request->param('bank_name', '');
        $bank_code = $this->request->param('bank_code', ''); //银行代码
        $wx_bank_code = $this->request->param('wx_bank_code', ''); //微信银行编码
        $bank_num = $this->request->param('bank_num', 0);
        $open_address = $this->request->param('open_address', '');
        if (!$name || !$bank_name || !$bank_num || !$open_address) {
            $this->error('缺少参数没填');
        }

        $usersinfo = UsersModel::where(['id' => $this->auth->id])->find();
        if ($usersinfo['realname'] != $name) {
            $this->error('真实名字不符');
        }
        $bankcard = Bankcard::where(['bank_num' => $bank_num])->find();
        if ($bankcard) {
            $this->error('此银行卡已存在');
        }
        $data = [
            'name' => $name,
            'bank_name' => $bank_name,
            'bank_code' => $bank_code,
            'wx_bank_code' => $wx_bank_code,
            'bank_num' => $bank_num,
            'open_address' => $open_address,
            'user_id' => $this->auth->id,
        ];
        $res = Bankcard::create($data);
        if (!$res->toArray()) {
            $this->error('银行卡添加失败');
        }
        $this->success('银行卡添加成功');
    }

    /**
     * 我的钱包
     */
    public function myMoney()
    {
        $page = $this->request->post('page', 1);
        $usersinfo = UsersModel::where(['id' => $this->auth->id])->find();
        $Withdraws = Withdraw::where(['user_id' => $this->auth->id])
            ->field('*,FROM_UNIXTIME(start_time,"%Y-%m-%d %H:%i") as start_time,cast(money/100 as decimal(10,2)) as money')
            ->page($page)
            ->limit($this->pageSize)
            ->select();
        foreach ($Withdraws as $key => $val) {
            switch ($val['status']) {
                case -1:
                    $val['state'] = '已拒绝';
                    break;
                case 0:
                    $val['state'] = '待审核';
                    break;
                case 1:
                    $val['state'] = '已通过';
                    break;
                case 2:
                    $val['state'] = '已核销';
                    break;
            }
        }
        $this->success('获取成功', ['total_money' => $usersinfo['total_money'], 'withdraws' => $Withdraws]);
    }

    /**
     * 我的转账记录
     */
    public function myTransfers()
    {
        $page = $this->request->post('page', 1);
        $usersinfo = UsersModel::where(['id' => $this->auth->id])->find();
        $Transfers = Db::name('user_money_log')
            ->alias('uml')
            ->join('users u','u.id = uml.transfer_user_id','left')
            ->join('users us','us.id = uml.user_id','left')
            ->where(['uml.user_id' => $this->auth->id, 'uml.type' => 3])
            ->field('uml.*,FROM_UNIXTIME(uml.createtime,"%Y-%m-%d %H:%i") as createtime,u.transfer_random_number,us.random_number')
            ->page($page)
            ->limit($this->pageSize)
            ->order('uml.createtime desc')
            ->select();
        $this->success('获取成功', ['total_money' => $usersinfo['total_money'], 'Transfers' => $Transfers]);
    }

    /**
     * 我的银行卡
     */
    public function myBank()
    {
        $Bankcards = Bankcard::where(['user_id' => $this->auth->id])->select();
        if (!$Bankcards) {
            $this->error('暂无银行卡');
        }
        $this->success('银行卡列表', ['Bankcards' => $Bankcards]);
    }

    /**
     * 删除银行卡
     */
    public function delBank()
    {
        $bankcard_id = $this->request->post('bankcard_id', 0);
        $res = Bankcard::where(['id' => $bankcard_id])->delete();
        if (!$res) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }


    /**
     * 选择银行卡
     */
    public function selectBank()
    {
        $banklist = Db::name('bank')->select();
        $this->success('银行卡列表', ['banklist' => $banklist]);
    }

    /**
     * 个人邀请码
     */
    public function getPersonalcode()
    {
        $user_id = $this->auth->id;
        if ($this->auth->type != 2) {
            $this->error('您还未是合伙人,暂不可邀请他人');
        }
        $data['type'] = 1; //二维码类型 1=邀请锁客
        $data['user_id'] = $user_id;
        //        $url = getDomain() . '/qrcode?user_id=' . $user_id . '&type=1';//type=1:个人邀请码
        $userinfo = UsersModel::where(['id' => $user_id])->find();
        if (!$userinfo['Personal_code']) {
            $url = createQrcode($data, $data['type']);
            UsersModel::where(['id' => $user_id])->update(['Personal_code' => $url]);
        } else {
            $url = $userinfo['Personal_code'];
        }
        $this->success('获取个人邀请码成功', ['url' => $url]);
    }

    /**
     * 个人推广记录(已被弃用)
     */
    public function getInvite_Record()
    {
        $page = $this->request->post('page', 1);
        $user_id = $this->auth->id;
        $agents = Agent::where(['parent_user_id' => $user_id, 'status' => 1])
            ->field('*,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i") as createtime')
            ->field("REPLACE(mobile, SUBSTR(mobile,4,4), '****') as mobile")
            ->page($page)
            ->limit($this->pageSize)
            ->select();
        if (!$agents) {
            $this->error('暂无推广记录');
        }
        $charge_device_sn = [];
        $charge_device_num = 0;
        foreach ($agents as $key => $val) {
            $devices = Chargedevice::where(['user_id' => $val['agent_user_id']])->select();
            foreach ($devices as $k => $v) {
                array_push($charge_device_sn, $v['charge_device_sn']);
            }
            $charge_device_num += Chargedevice::where(['user_id' => $val['agent_user_id']])->count();
            $val['charge_device_sns'] = implode(',', $charge_device_sn);
        }
        $invite_count = Agent::where(['parent_user_id' => $user_id, 'status' => 1])->count();
        $this->success('获取成功', ['agents' => $agents, 'invite_count' => $invite_count, 'charge_device_num' => $charge_device_num]);
    }

    /**
     * 个人推广记录
     */
    public function getInviteRecord()
    {
        $page = $this->request->post('page', 1);
        $order_type = $this->request->post('order_type', 7); //7=服务中心奖,8=推广奖励
        $orderlist = \app\admin\model\order\Order::where(['order_type' => $order_type, 'user_id' => $this->auth->id])
            ->field('need_pay,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i") as createtime')
            ->page($page)
            ->limit($this->pageSize)
            ->order('createtime desc')
            ->select();
        foreach ($orderlist as $key => $val) {
            if ($order_type == 7) {
                $orderlist[$key]['title'] = '服务中心奖记录';
            } else {
                $orderlist[$key]['title'] = '推荐奖励记录';
            }
        }
        $extend_money_sum = \app\admin\model\order\Order::where(['order_type' => 8, 'user_id' => $this->auth->id])->sum('need_pay'); //推广奖励总额
        $service_money_sum = \app\admin\model\order\Order::where(['order_type' => 7, 'user_id' => $this->auth->id])->sum('need_pay'); //服务中心奖励总额
        $total_money = $extend_money_sum + $service_money_sum; //累计总金额
        $this->success('获取成功', ['orderlist' => $orderlist, 'extend_money_sum' => sprintf('%.2f', $extend_money_sum), 'service_money_sum' => sprintf('%.2f', $service_money_sum), 'total_money' => sprintf('%.2f', $total_money)]);
    }

    /**
     * @param
     * 钱包支付
     */
    public function moneyPay()
    {
        $log_id = $this->request->post('log_id', 0);
        $amount = $this->request->post('amount', 0);
        $pay_log = PaymentLogModel::where(['id' => $log_id, 'status' => 1])->find();
        if (!$pay_log) {
            $this->error('该支付记录不存在');
        }

        $userinfo = UsersModel::where(['id' => $this->auth->id])->find();
        if ($pay_log['pay_way'] == 'money' && $amount > $userinfo['total_money']) {
            $this->error('钱包余额不足');
        }
        $ret = PaymentLogModel::checkPayMoney($pay_log, $amount);
        if (!$ret) {
            $this->error('支付金额不对');
        }
        $order = \app\admin\model\order\Order::where(['id' => $pay_log['order_id']])->find();
        Db::startTrans();
        try {
            //            PaymentLogModel::where(['order_sn' => $pay_log['order_sn']])->update(['status' => 2]); //支付完成
            //            OrderModel::where(['id' => $pay_log['order_id']])->update(['status' => 2]); //订单状态变为待接单
            $intro = '您认购下单钱包余额消费' . $amount;
            if ($pay_log['pay_way'] == 'money') {
                self::addMoney($pay_log['user_id'], -$pay_log['need_pay'], $userinfo['total_money'], sprintf('%.2f', $userinfo['total_money'] - $pay_log['need_pay']), $intro, $pay_log['order_id'], 5, 0);
                $message = [];
                $message['out_trade_no'] = $pay_log['order_sn'];
                PaymentLogModel::dealCallBack($message); //订单回调
                /*$user_money_log = [
                    'user_id' =>$pay_log['user_id'],
                    'money' =>$pay_log['need_pay'],
                    'before' =>$userinfo['total_money'],
                    'after' =>sprintf('%.2f',$userinfo['total_money']-$pay_log['need_pay']),
                    'memo' =>$intro,
                    'order_id' =>$pay_log['order_id'],
                    'heatos' =>-1,
                ];
                Db::name('user_money_log')->create($user_money_log);
                UsersModel::where(['id' =>$pay_log['user_id']])->setDec('total_money',$pay_log['need_pay']);*/
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('钱包余额支付失败！' . $e->getMessage());
        }
        $this->success('钱包余额支付成功');
    }


    /**
     * @param
     * 钱包转账
     */
    public function transferMoney()
    {
        $uid = $this->auth->id;
        $user_id = $this->request->param("user_id", 0); //收款用户ID
        $random_number = $this->request->param("random_number", 0); //收款用户ID
        $money = $this->request->param('money', 0);
        if ($money <= 0) { //检测余额小于0，用户余额是不是不足，超过最大限制，最小限制，检测用户转账间隔时间
            $this->error("您输入的金额不合法！");
        }
        if ($uid == $user_id) {
            $this->error("不能给自己转账！");
        }

        Db::startTrans();
        try {
            $userinfo = UsersModel::where(['id' => $this->auth->id])->find();
            if ($money > $userinfo['total_money']) {
                $this->error("转账金额有误！");
            }
//            $transferuserinfo = UsersModel::where(['id' => $user_id])->find();
            $transferuserinfo = UsersModel::where(['random_number' => $random_number])->find();
            $user_id = $transferuserinfo['id'];
            $user_after = sprintf('%.2f', $userinfo['total_money'] - $money);
            $user_intro = '您给' . $transferuserinfo['nickname'] . '转账了' . $money . '元';
            self::addMoney($uid, -$money, $userinfo['total_money'], $user_after, $user_intro, 0, 3, $user_id); //转账人减少相应金额
            $transferuser_after = sprintf('%.2f', $userinfo['total_money'] - $money);
            $transferuser_intro = $userinfo['nickname'] . '给您转账了' . $money . '元';
            self::addMoney($user_id, $money, $transferuserinfo['total_money'], $transferuser_after, $transferuser_intro, 0, 3, $uid); //被转账人增加相应金额
            $UserTranfer_intro = $userinfo['nickname'] . '给' . $transferuserinfo['nickname'] . '转账了' . $money . '元';
            UserTranfer::insertData($user_id, $uid, $money, $UserTranfer_intro); //转账记录
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('钱包余额转账失败！' . $e->getMessage());
        }
        $this->success('钱包余额转账成功');
    }

    /**
     * 增加减钱包余额
     */
    public static function addMoney($user_id, $amount, $total_money, $after, $intro, $order_id, $type, $transfer_user_id)
    {
        $user_money_log = [
            'user_id' => $user_id,
            'money' => $amount,
            'before' => $total_money,
            'after' => $after,
            'memo' => $intro,
            'type' => $type,
            'order_id' => $order_id,
            'heatos' => $amount > 0 ? 1 : -1,
            'transfer_user_id' => $transfer_user_id,
            'createtime' => time(),
        ];
        Db::name('user_money_log')->insert($user_money_log);
        if ($amount > 0) {
            UsersModel::where(['id' => $user_id])->setInc('total_money', $amount);
        } else {
            UsersModel::where(['id' => $user_id])->setDec('total_money', abs($amount));
        }
    }

    /**
     * 获取微信的openid等唯一标识
     */
    public function getOpenid($code)
    {
        if (!$code) {
            $this->error(__('Invalid parameters'));
        }
        // 微信登录 (获取session_key)
        $WxUser = new WxUser(config('wx_appid'), config('wx_apikey'));
        if (!$session = $WxUser->sessionKey($code))
            $this->error('请再次点击绑定', '', 1002);
        //缓存session_key
        cache($session['openid'] . '_wc', $session['session_key']);
        //根据openid获取用户的信息
        //返回openid给小程序
        //$data = ['openid'=>$session['openid']];
        return $session;
    }
    public function create_code()
    {
        $user_id = $this->request->param('user_id', 0);
        $data['type'] = 1; //二维码类型 1=邀请锁客
        $data['user_id'] = $user_id;
        $userinfo = UsersModel::where(['id' => $user_id])->find();
        if (!$userinfo['Personal_code']) {
            $url = createQrcode($data, $data['type']);
            UsersModel::where(['id' => $user_id])->update(['Personal_code' => $url]);
        }
    }

    /**
     * 地址列表
     */
    public function getAddrList()
    {
        $useraddr = UsersAddr::where(['user_id' => $this->auth->id, 'status' => 0])->select();
        if (!$useraddr) {
            $this->error('暂无地址，快去新增吧');
        }
        foreach ($useraddr as $key => $val) {
            $province = Addr::where(['ID' => $val['province_id']])->field('Name')->find();
            $city = Addr::where(['ID' => $val['city_id']])->field('Name')->find();
            $area = Addr::where(['ID' => $val['area_id']])->field('Name')->find();
            $useraddr[$key]['province'] = $province['Name'];
            $useraddr[$key]['city'] = $city['Name'];
            $useraddr[$key]['area'] = isset($area['Name']) ? $area['Name'] :'';
        }
        $this->success('获取地址列表成功', ['user_addr' => $useraddr]);
    }

    /**
     * 添加地址
     */
    public function createAddr()
    {
        $province_id = $this->request->post('province_id', 0);
        $city_id = $this->request->post('city_id', 0);
        $area_id = $this->request->post('area_id', 0);
        $address = $this->request->post('address', '');
        $mobile = $this->request->post('mobile', '');
        $is_default = $this->request->post('is_default', 0);
        $name = $this->request->post('name', '');
        if ($is_default == 1) {
            UsersAddr::where(['user_id' => $this->auth->id, 'is_default' => 1])->update(['is_default' => 0]);
        }
        $user_addr = [
            'user_id' => $this->auth->id,
            'name' => $name,
            'mobile' => $mobile,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'area_id' => $area_id,
            'is_default' => $is_default,
            'address' => $address,
        ];
        $res = UsersAddr::create($user_addr);
        $this->success('获取用户列表成功', ['user_addr' => $res->toArray()]);
    }

    /**
     * 编辑地址
     */
    public function editAddr()
    {
        $params = $this->request->param();
        if (!$params['addr_id']) {
            $this->error('暂无此地址，编辑失败');
        }
        $user_addr = [
            'province_id' => $params['province_id'],
            'city_id' => $params['city_id'],
            'area_id' => $params['area_id'],
            'is_default' => $params['is_default'],
            'name' => $params['name'],
            'mobile' => $params['mobile'],
            'address' => $params['address'],
        ];
        if (isset($params['is_default']) && $params['is_default'] == 1) {
            UsersAddr::where(['user_id' => $this->auth->id, 'is_default' => 1])->update(['is_default' => 0]);
        }
        $res = UsersAddr::where(['id' => $params['addr_id']])->update($user_addr);
        $this->success('修改成功', ['user_addr' => $res]);
    }
    /**
     * 删除地址
     */
    public function delAddr()
    {
        $addr_id = $this->request->post('addr_id', 0);
        if (!$addr_id) {
            $this->error('暂无此地址，删除失败');
        }
        $res = UsersAddr::where(['id' => $addr_id])->update(['status' => 1]);
        $this->success('删除成功');
    }

    /**
     * 获取手机号
     */
    public function getUsersMobile()
    {
        $code = $this->request->post("code");
        if (empty($code)) {
            $this->error("参数错误");
        }
        $error = new ErrorInfo();
        $phonenumber = WXPayConstants::getuserphonenumber($code, $error);
        if ($error->code < 0) {
            $this->error($error->msg);
        }
        if (!$this->auth->mobile) {
            $res = UsersModel::where(['id' => $this->auth->id])->update(['mobile' => $phonenumber]);
        }
        $this->success("获取成功", $phonenumber);
    }

    /**
     * 我的账单(包括购物金和余额等记录)
     */
    public function myBill()
    {
        $page = $this->request->param('page', 1);
        $type = $this->request->param('type', 9); //9购物金 13股权股票变更
        $heatos = $this->request->param('heatos', 0); //1正数收入，-1负数支出
        $where = [];
        $where['user_id'] = $this->auth->id;
        $where['type'] = $type;

        if ($heatos != 0) {
            $where['heatos'] = $heatos;
        }
        $userdetailmoneys = UserMoneyLog::where($where)
            ->page($page)
            ->limit($this->pageSize)
            ->order('createtime desc')
            ->select();
        //        $userinfo = UsersModel::where(['id' => $this->auth->id])->field('money,commission,agent_money,coupon_money')->find();
        if (empty($userdetailmoneys)) {
            $this->error('暂无账单明细');
        }
        foreach ($userdetailmoneys as $key => $val) {
            switch ($val['heatos']) {
                case 1:
                    $val['money'] = '+' . $val['money'];
                    break;
            }
        }
        $this->success('获取账单明细成功', ['userdetailmoneys' => $userdetailmoneys]);
    }
    /**
     * 股权查询接口
     */
    public function userEquity()
    {
        $userInfo = UsersModel::alias('user')
            ->join('agent', 'user.id=agent.agent_user_id', 'left')
            ->field("user.id,user.realname,agent.identity_number,
                    user.equity,user.equity_code,
                    FROM_UNIXTIME(user.signtime,'%Y-%m-%d %T') as signtime")
            ->where(['user.id' => $this->auth->id])->find();
        if (!$userInfo) {
            $this->error('获取用户信息失败');
        }
        if (!$userInfo['equity']) {
            $this->error('当前用户没有获得股权');
        }
        $companyInfo['address'] = "江西省南昌市南昌县莲塘镇澄湖西路295号";
        $companyInfo['established_time'] = "2021-07-14";
        $companyInfo['business_license'] = "91360106MA3AEF9220";
        $companyInfo['registered_capital'] = "3000万";
        $companyInfo['description'] = "公司在上市后赠送同等金额原始股;本股权证书经公司正式授权井加盖公章，即可有效。特此为证。";
        $companyInfo['official_seal'] = "";
        $companyInfo['chairman_seal'] = "";
        $this->success('获取股权信息成功', ['equityInfo' => $userInfo, 'companyInfo' => $companyInfo]);
    }

    /**
     * 批量随机编号
     */
    public function createCode(){
        $info = UsersModel::order('id desc')->field('id')->find();
        $lastid = $info['id'];
        for ($x = 1; $x <= $lastid; $x++){
            $random_number = $this->recursion();
            /* $random_number = createRandomcode();
             $info = UsersModel::where(['random_number' =>$random_number])->find();
             if($info){
                 $random_number = createRandomcode();
             }*/
            UsersModel::where(['id' =>$x])->update(['random_number' =>$random_number]);
        }
        $this->success('生成成功');
    }

    /**
     * @return string
     * 递归查询
     */
    private function recursion(){
        $random_number = createRandomcode();
        $info = UsersModel::where(['random_number' =>$random_number])->find();
        if($info){
            $this->recursion();
        }
        return $random_number;
    }

    /**
     * 商家明细单号查询
     */
    public function queryMerchantDetails(){
        $data=Withdraw::where(['status'=>1,'out_batch_no'=>['NEQ','NULL'],'detail_status'=>null])->select();
        foreach ($data as $key=>$val){
            $jsonMap=new ErrorInfo();
            $result=WXPayConstants::detailsQuery($val['out_batch_no'],$val['cash_sn'],$jsonMap);
            if ($jsonMap->code < 0) {
                Withdraw::where(['id'=>$val['id']])->update(['status'=>0,'reason'=>$jsonMap->msg,'detail_status'=>$jsonMap->fail_reason]);
            }else{
                Withdraw::where(['id'=>$val['id']])->update(['detail_status'=>"SUCCESS"]);
            }
        }
    }
}
