<?php

namespace App\Http\Controllers\QuickApp\User;


use App\Http\Controllers\QuickApp\BaseController;
use App\Http\Controllers\Wap\User\Transformers\SignRecordTransformer;
use App\Libs\AliSMS;
use App\Modules\Book\Services\BookService;
use App\Modules\Book\Services\BookUrgeUpdateService;
use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\User\Services\QappUserService;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\User\Services\UserService;
use App\Modules\User\Services\UserSignService;
use Illuminate\Http\Request;
use Redis;

class UserController extends BaseController
{
    /**
     * @apiDefine User 用户
     */


    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取用户信息
     * @api {GET} userinfo 获取用户信息
     * @apiHeader {String} [Authorization]  token
     * @apiGroup User
     * @apiName index
     * @apiSuccess {Number}  id 用户ID.
     * @apiSuccess {String}  openid 微信openid.
     * @apiSuccess {String}  unionid 微信unionid.
     * @apiSuccess {Number}  distribution_channel_id 分销渠道ID.
     * @apiSuccess {String}  province 省份.
     * @apiSuccess {String}  city 城市.
     * @apiSuccess {String}  country 国家.
     * @apiSuccess {String}  headimgurl 头像地址.
     * @apiSuccess {Number}  send_order_id 派单ID.
     * @apiSuccess {Number=0,1}  sex 性别.
     * @apiSuccess {String}  balance 书币余额.
     * @apiSuccess {Int}     is_vip 是否vip
     * @apiSuccess {String}  vip_days 364天.
     * @apiSuccess {String}  phone 手机号.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {
     *             "id": 56,
     *             "openid": "sdfs34ssdfdsf",
     *             "unionid": "SDFSD3343S",
     *             "distribution_channel_id": 1212,
     *             "province": "浙江省",
     *             "city": "杭州",
     *             "country": "中国",
     *             "headimgurl": "http://..",
     *             "send_order_id": 323,
     *             "balance": 8956,
     *             "register_time": "2017-12-12 12:12:12",
     *             "phone": "12312435",
     *         }
     *     }
     */
    public function index()
    {
        $data = $this->user_info;
        if (!$data->head_img) {
            $data->head_img = 'https://yueduyun.oss-cn-hangzhou.aliyuncs.com/xiaochengxu/img/defaulthead.png';
        }
        $data['is_vip'] = 0;
        $data['vip_days'] = 0;
        $data['phone'] = $this->phone;
        $year_record = YearOrderService::getRecord($this->uid);
        if ($year_record) {
            $data['is_vip'] = 1;
            $time = strtotime($year_record['end_time']) - time();
            if ($time >= 86400) {
                $data['vip_days'] = floor($time / 86400) . '天';
            } elseif ($time > 3600) {
                $data['vip_days'] = floor($time / 3600) . '小时';
            } elseif ($time > 60) {
                $data['vip_days'] = floor($time / 60) . '分钟';
            } else {
                $data['vip_days'] = $time . '秒';
            }
        }
        // $data['is_check'] = false;
        $data['is_check'] = !$this->phone;
        return response()->success($data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 用户签到
     * @api {GET} sign 用户签到
     * @apiHeader {String} [Authorization]  token
     * @apiGroup User
     * @apiName sign
     * @apiSuccess {Double}  fee 签到奖励
     * @apiSuccess {Number}  days 签到天数
     * @apiSuccess {Array}  day_list 签到列表
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {
     *               "fee": 30,
     *               "days": 1
     *               "day_list": []
     *             }
     *     }
     */
    public function sign()
    {
        $result = UserSignService::sign($this->uid, date('Y-m-d'));
        if ($result) {
            return response()->success($result);
        }
        return response()->error('QAPP_SYS_ERROR');
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 发送验证码
     * @api {POST} user/sendCode 发送验证码
     * @apiHeader {String} [Authorization]  token
     * @apiGroup User
     * @apiName sendCode
     * @apiParam {String}  phone 手机号
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    public function sendCode(Request $request)
    {
        $phone = $request->post('phone');
        $code = random_int(1000, 9999);
        Redis::setex('quser_code:' . $phone, 120, $code);
        AliSMS::send($phone, 'quickapp_user_bind_phone', ['code' => $code]);
        return response()->success();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 绑定手机号
     * @api {POST} user/bindPhone 绑定手机号
     * @apiHeader {String} [Authorization]  token
     * @apiGroup User
     * @apiName bindPhone
     * @apiParam {String}  phone 手机号
     * @apiParam {String}  code 验证码
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    public function bindPhone(Request $request)
    {
        $code = $request->post('code');
        $phone = $request->post('phone');
        $old = Redis::get('quser_code:' . $phone);
        if ($old && $old == $code) {
            try {
                Redis::del('quser_code:' . $phone);
                $result = QappUserService::bindPhoneStatic($this->uid, $phone);
                if (!$result) {
                    return response()->error('WAP_BIND_PHONE_EXIST');
                } else {
                    return response()->success();
                }
            } catch (\Exception $e) {
                return response()->error();
            }
        } else {
            return response()->error('WAP_SEND_CODE_ERROR');
        }
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 用户签到记录
     * @api {GET} user/sign_record 用户签到记录
     * @apiGroup User
     * @apiName signRecord
     * @apiParam {String}  date 查询日期每个月一号
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {sign_status}     data.sign_status .
     * @apiSuccess {sign_result}  data.sign_result .
     * @apiSuccess {sign_today}  data.sign_today .
     * @apiParam {page}  page
     * @apiSuccessExample {json} Success-Response:
     *
     *    {
     *       code: 0,
     *       msg: "",
     *       data: {
     *            "sign_status": true,
     *            "sign_result": {
     *            "list": [
     *       {
     *            "reward": 30,
     *            "sign_time": "2019-11-01 14:20:30"
     *              }
     *   ],
     *            "meta": {
     *            "total": 1,
     *            "per_page": 15,
     *            "current_page": 1,
     *            "last_page": 1,
     *            "next_page_url": "",
     *            "prev_page_url": ""
     *   }
     * },
     *            "sign_today": {
     *            "uid": 162261523,
     *            "price": 50,
     *            "day": "2019-11-01",
     *            "sign_time": "2019-11-01 09:04:43",
     *            "created_at": "2019-11-01 09:04:43",
     *            "updated_at": "2019-11-01 09:04:43",
     *            "reward": 50
     * }
     * }
     */
    public function signRecord(Request $request)
    {
        $month = $request->get('date', date('Y-m-01'));
        $page_size = $request->get('page_size', 15);
        $sign_result = paginationTransform(new SignRecordTransformer(), UserSignService::getUserSignRecord($this->uid, $month, $page_size));
        $sign_status = UserSignService::isSign($this->uid);
        $sign_today = [];
        if ($sign_status) {
            $sign_today = ReadRecordService::getByField($this->uid, 'sign_info');
            if ($sign_today) $sign_today = json_decode($sign_today, 1);
            isset($sign_today['sign_time']) && $sign_today['sign_time'] = date('Y-m-d H:i:s', $sign_today['sign_time']);
            isset($sign_today['sign_at']) && $sign_today['sign_time'] = $sign_today['sign_at'];
            isset($sign_today['price']) && $sign_today['reward'] = $sign_today['price'];
        }
        $result = [
            'sign_status' => $sign_status,
            'sign_result' => $sign_result,
            'sign_today' => $sign_today
        ];
        return response()->success($result);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 催更
     * @api {POST} user/urgeUpdate 催更
     * @apiHeader {String} [Authorization]  token
     * @apiGroup User
     * @apiName urgeUpdate
     * @apiParam {String}  bid 书号
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    public function urgeUpdate(Request $request)
    {
        $bid = $request->input('bid');
        if (empty($bid)) {
            return response()->error('PARAM_ERROR');
        }
        $bid = BookService::decodeBidStatic($bid);
        $result = BookUrgeUpdateService::UrgeRecord($this->uid, $bid);
        if ($result && !$result->id) {
            BookUrgeUpdateService::UrgeUpdate($this->uid, $bid, $result->updated_at);
        }
        return response()->success();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 更新派单ID
     * @api {GET} user/setSendOrder 更新派单ID
     * @apiHeader {String} [Authorization]  token
     * @apiGroup User
     * @apiName setSendOrder
     * @apiParam {Int}  send_order_id 派单ID
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     */
    public function setSendOrder(Request $request)
    {
        $send_order_id = $request->get('send_order_id', 0);
        if ($send_order_id) {
            UserService::setUserSendOrderStatic($this->uid, $send_order_id);
        }
        return response()->success();
    }
}
