<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use app\common\model\User as UserModel;
use app\admin\model\transaction\Record;
use app\admin\model\Order;
use app\admin\model\order\Detail;
use app\admin\model\Warehouse;
use EasyWeChat\Factory;



/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

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

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    public function getUserinfo(){
        $user = $this->auth->getUserinfo();
        //$user['mobile'] = substr_replace($user['mobile'], '****', 3, 4);
        $this->success('succ', $user);
    }
    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $code = $this->request->post('code');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $config = [
            'app_id' => 'wx5a2c9f7e82918b85',
            'secret' => 'd33c7f7a45150136da158cf8cc956a34',
            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $ret = $this->auth->login($account, $password);
        //更新用户新
        if ($ret) {
            $openid = "";
            if ($code) {
                $app = Factory::officialAccount($config);
                $user = $app->oauth->userFromCode($code);
                $user = $user->toArray();
                $openid = $user['token_response']['openid'] ?? "";
            }
            

            $userinfo = $this->auth->getUserinfo();
            $data = ['userinfo' => $userinfo];
            if ($openid) {
                UserModel::where("id", $userinfo['id'])->update(['openid' => $openid]);
            }
            
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('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);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $invite_mobile = $this->request->post('invite_mobile');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $extend = [];
        if ($invite_mobile) {
            $user = \app\common\model\User::getByMobile($invite_mobile);
            if ($user) {
                $extend['pid'] = $user->id;
            }
        }
        // $ret = Sms::check($mobile, $code, 'register');
        // if (!$ret) {
        //     $this->error(__('Captcha is incorrect'));
        // }
        $ret = $this->auth->register($username, $password, $email, $mobile, $extend);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }
    /**
     * 更新用户信息
     * [updateUserInfo description]
     * @return [type] [description]
     */
    public function updateUserInfo(){
        $params = $this->request->post();
        $user_id = $this->auth->id;
        $upData = [];
        if (isset($params['bank_realname']) && $params['bank_realname']) {
            $upData['bank_realname'] = $params['bank_realname'];
        }
        if (isset($params['bank_mobile']) && $params['bank_mobile']) {
            $upData['bank_mobile'] = $params['bank_mobile'];
        }
        if (isset($params['bank_no']) && $params['bank_no']) {
            $upData['bank_no'] = $params['bank_no'];
        }
        if (isset($params['bank_address']) && $params['bank_address']) {
            $upData['bank_address'] = $params['bank_address'];
        }
        //签名
        if (isset($params['sign_image']) && $params['sign_image']) {
            $upData['sign_image'] = $params['sign_image'];
            $upData['sign_status'] = 1;
        }
        //支付宝二维码
        if (isset($params['alipay_image']) && $params['alipay_image']) {
            $upData['alipay_image'] = $params['alipay_image'];
        }
        //微信二维码
        if (isset($params['wechat_image']) && $params['wechat_image']) {
            $upData['wechat_image'] = $params['wechat_image'];
        }
        if (isset($params['username']) && $params['username']) {
            $upData['username'] = $params['username'];
        }
        if (isset($params['nickname']) && $params['nickname']) {
            $upData['nickname'] = $params['nickname'];
        }
        if (isset($params['avatar']) && $params['avatar']) {
            $upData['avatar'] = $params['avatar'];
        }
        if (!$upData) {
            $this->success();
        }
        \app\common\model\User::where('id', $user_id)->update($upData);
        $this->success();
    }
    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 绑定邀请人
     * [bindInvitor description]
     * @return [type] [description]
     */
    public function bindInvitor(){
        $mobile = $this->request->post("mobile");
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }
        $ret = \app\common\model\User::where('id', $this->auth->id)->update(['pid' => $user->id]);
        if (!$ret) {
            $this->error(__('绑定失败'));
        }
        $this->success(__('绑定成功'));
    }
    /**
     * 我的佣金统计
     * [getUserCommissionStatistic description]
     * @return [type] [description]
     */
    public function getUserCommissionStatistic(){
        $user = $this->auth->getUserinfo();

        $data = [
            'total_commission_amount' => $user['total_commission_amount'],
            'available_commission_amount' => $user['available_commission_amount'],
            'today_commission_amount' => sprintf("%.2f", Record::whereTime('createtime', 'today')->whereIn('type',[0,1])->where('user_id', $this->auth->id)->sum('amount')) ,
            'seven_day_commission_amount' => sprintf("%.2f", Record::whereTime('createtime', '-7 days')->whereIn('type',[0,1])->where('user_id', $this->auth->id)->sum('amount')),
        ];
        $this->success("succ", $data);
    }
    /**
     * 用户邀请佣金
     * [getUserCommission description]
     * @return [type] [description]
     */
    public function getUserCommission(){
        $status = $this->request->post("status", 1);
        $user = $this->auth->getUserinfo();
        $data = [
            'total_commission_amount' => $user['total_commission_amount'],
            'distribute_order_num' => Record::where('user_id', $this->auth->id)->whereIn('type',[0,1])->group('item_id')->count(),
        ];
        $this->success("succ", $data);
    }
    /**
     * 用户邀请佣金
     * [getUserCommission description]
     * @return [type] [description]
     */
    public function getUserCommissionList(){
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $status = $this->request->post("status", 1);
        $list = Record::where('user_id', $this->auth->id)->whereIn('type',[0,1])->field('id,user_id,createtime,amount,child_id')->order('id', 'desc')->paginate($this->request->param('list_rows', $limit))->each(function ($item, $key){
            $user = UserModel::where('id', $item['child_id'])->field('username,nickname,avatar')->find();
            $item['jointime'] = date("Y-m-d H:i:s", $item['createtime']);
            $item['username'] = $user['username'] ?? "";
            $item['nickname'] = $user['nickname'] ?? "";
            $item['avatar'] = cdnurl($user['avatar'] ?? "", true);
            $item['total_commission_amount'] = $item['amount'];
            return $item;
        });
        $this->success("succ", $list);
    }
    /**
     * 用户粉丝统计
     * [getUserFansStatistic description]
     * @return [type] [description]
     */
    public function getUserFansStatistic(){

        $data = [
            'total_fans_num' => UserModel::where('pid', $this->auth->id)->count(),
            'today_fans_num' => UserModel::whereTime('jointime', 'today')->where('pid', $this->auth->id)->count(),
        ];
        $this->success("succ", $data);
    }
    /**
     * 用户粉丝列表
     * [getUserFansList description]
     * @return [type] [description]
     */
    public function getUserFansList(){
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $list = UserModel::where('pid', $this->auth->id)->field('id,username,nickname,avatar,jointime')->order('id', 'desc')->paginate($this->request->param('list_rows', $limit))->each(function ($item, $key){
            $item['jointime'] = date("Y-m-d H:i:s", $item['jointime']);
            $item['total_commission_amount'] = 0;
            return $item;
        });
        $this->success("succ", $list);
    }
    /**
     * 用户粉丝统计
     * [getUserFansStatistic description]
     * @return [type] [description]
     */
    public function getUserFansOrderStatistic(){
        $users = UserModel::where('pid', $this->auth->id)->select();
        $user_ids = array_column($users, "id");

        $data = [
            'total_fans_order_amount' => order::whereIn('buyer_id', $user_ids)->whereIn('status', [0,1,2,3,4,5])->count(),
            'today_fans_order_num' => order::whereIn('buyer_id', $user_ids)->whereIn('status', [0,1,2,3,4,5])->sum('order_amount'),
        ];
        $this->success("succ", $data);
    }
    /**
     * 用户粉丝列表
     * [getUserFansList description]
     * @return [type] [description]
     */
    public function getUserFansOrderList(){
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $users = UserModel::where('pid', $this->auth->id)->select();
        $user_ids = array_column($users, "id");

        $list = order::whereIn('buyer_id', $user_ids)->whereIn('status', [0,1,2,3,4,5])->order('id', 'desc')->paginate($this->request->param('list_rows', $limit))->each(function ($item, $key){
            $order_goods = Detail::where('order_id', $item['id'])->select();
            if ($order_goods) {
                foreach ($order_goods as $key => $value) {
                    $value['goods_image'] = cdnurl($value['goods_image'], true);
                }
            }
            
            $warehouse = Warehouse::where('id', $item['warehouse_id'])->find();
            $seller = UserModel::where('id', $item['seller_id'])->field("id,username,nickname,mobile")->find();
            $buyer = UserModel::where('id', $item['buyer_id'])->field("id,username,nickname,mobile")->find();
            $item['order_goods'] = $order_goods;
            $item['warehouse'] = $warehouse;
            $item['seller'] = $seller;
            $item['buyer'] = $buyer;
            $site = Config::get("site");
            $item['commission_amount'] = bcmul($item['order_amount'], $site['primary_distribution'] * 0.01, 2);
            return $item;
        });
        $this->success("succ", $list);
    }
    /**
     * 用户收益
     * [getUserProfit description]
     * @return [type] [description]
     */
    public function getUserProfitStatistic(){
        $user = $this->auth->getUserinfo();
        $data = [
            'total_profit_amount' => $user['profit_amount'],
            'today_profit_amount' => sprintf("%.2f", Record::whereTime('createtime', 'today')->whereIn('type',[2])->where('user_id', $this->auth->id)->sum('amount')) ,
        ];
        $this->success("succ", $data);
    }

    /**
     * 用户收益列表
     * [getUserProfitList description]
     * @return [type] [description]
     */
    public function getUserProfitList(){
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $status = $this->request->post("status", 1);
        $list = Record::where('user_id', $this->auth->id)->whereIn('type',[2])->field('id,user_id,createtime,amount,child_id')->order('id', 'desc')->paginate($this->request->param('list_rows', $limit))->each(function ($item, $key){
            $user = UserModel::where('id', $item['child_id'])->field('username,nickname,avatar')->find();
            $item['jointime'] = date("Y-m-d H:i:s", $item['createtime']);
            $item['username'] = $user['username'] ?? "";
            $item['nickname'] = $user['nickname'] ?? "";
            $item['avatar'] = cdnurl($user['avatar'] ?? "", true);
            $item['total_commission_amount'] = $item['amount'];
            return $item;
        });
        $this->success("succ", $list);
    }





}