<?php
/**
 * Created by PhpStorm.
 * User: zilongs
 * Date: 20-9-23
 * Time: 上午11:36
 */

namespace App\Http\Controllers\Api\V1;

use App\Models\Order;
use App\Models\User;
use App\Models\UserBalanceLog;
use App\Models\UserCoupon;
use App\Models\UserMessage;
use EasyWeChat\Factory;
use Cache;

class UserController extends AuthController
{
    public function userInfo()
    {
        $user = $this->user;

        $user['is_set_pay_password'] = !empty($user['pay_password']) ? 1 : 0;
        unset($user['session_key'], $user['pay_password']);

        $user['coupon_num'] = UserCoupon::where('user_id', $user['id'])->where('status', 1)->where('expire_time', '>', time())->count();

        return out($user);
    }

    public function getPhoneNumber()
    {
        $req = request()->post();
        $this->validate(request(), [
            'iv' => 'required',
            'encryptData' => 'required',
        ]);
        $user = $this->user;

        $app = Factory::miniProgram(config('config.wechat_small_program'));

        try {
            $decryptedData = $app->encryptor->decryptData($user['session_key'], $req['iv'], $req['encryptData']);
        } catch (\Exception $e) {
            return out(null, 10001, '获取手机号失败', $e->getMessage());
        }

        return out($decryptedData);
    }

    public function updateUser()
    {
        $req = request()->post();
        $this->validate(request(), [
            'nickname' => 'max:100',
            'avatar' => 'url',
            'sex' => 'in:1,2',
            'birthday' => 'date',
            'latitude' => 'numeric',
            'longitude' => 'numeric',
        ]);
        $user = $this->user;

        User::where('id', $user['id'])->update($req);

        return out();
    }

    public function userBalanceLog()
    {
        $user = $this->user;
        $data = UserBalanceLog::where('user_id', $user['id'])->orderBy('id', 'desc')->paginate();
        return out($data);
    }

    public function familyDocterList()
    {
        $user = $this->user;

        $docter_ids = Order::where('user_id', $user['id'])->whereIn('order_status', [2, 3])->where('docter_id', '>', 0)->pluck('docter_id')->toArray();
        $docter_ids = array_values(array_unique($docter_ids));

        $data = Order::with(['docter.office', 'docter.qualification'])->select(['id', 'docter_id'])->whereIn('docter_id', $docter_ids)->groupBy('docter_id')->paginate();

        return out($data);
    }

    public function updatePayPassword()
    {
        $req = request()->post();
        $this->validate(request(), [
            'verify_code|验证码' => 'required|integer',
            'pay_password|支付密码' => 'required|integer'
        ]);
        $user = $this->user;

        $verify_code = Cache::get($user['phone'].'-3');
        if($verify_code != $req['verify_code']){
            if (env('APP_ENV') == 'online' || $req['verify_code'] != '111111') {
                return out(null, 10001, '验证码错误');
            }
        }
        Cache::delete($user['phone'].'-3');

        User::where('id', $user['id'])->update(['pay_password' => sha1(md5($req['pay_password']))]);

        UserMessage::saveMessage($user['id'], 11);

        return out();
    }

    public function userMessageList()
    {
        $user = $this->user;
        $data = UserMessage::where('user_id', $user['id'])->orderBy('id', 'desc')->paginate();
        UserMessage::where('user_id', $user['id'])->where('status', 1)->update(['status' => 2]);
        return out($data);
    }

    public function changeUserPhone()
    {
        $req = request()->post();
        $this->validate(request(), [
            'old_verify_code' => 'required|integer',
            'new_verify_code' => 'required|integer',
            'new_phone' => 'required'
        ]);
        $user = $this->user;

        $verify_code = Cache::get($user['phone'].'-4');
        if($verify_code != $req['old_verify_code']){
            if (env('APP_ENV') == 'online' || $req['old_verify_code'] != '111111') {
                return out(null, 10001, '老手机验证码错误');
            }
        }
        Cache::delete($user['phone'].'-4');

        $verify_code = Cache::get($req['new_phone'].'-5');
        if($verify_code != $req['new_verify_code']){
            if (env('APP_ENV') == 'online' || $req['new_verify_code'] != '111111') {
                return out(null, 10002, '新验证码错误');
            }
        }
        Cache::delete($req['new_phone'].'-5');

        if (User::where('phone', $req['new_phone'])->exists()) {
            return out(null, 30008, '新手机号已经被占用');
        }

        User::where('id', $user['id'])->update(['phone' => $req['new_phone']]);

        UserMessage::saveMessage($user['id'], 10);

        return out();
    }
}
