<?php

namespace app\mobile\controller;

use app\common\model\VoteApplyModel;
use app\common\model\VoteModel;
use app\mobile\MobileBaseController;

class Vote extends MobileBaseController
{
    public function listVote()
    {
        $list = VoteModel::where('status',VoteModel::STATUS_SHOW)
            ->limit(input('limit', 10))
            ->order('id','desc')
            ->page(input('page', 1))
            ->select();

        ajax_success($list);
    }

    public function detail()
    {
        $id = input('id/d', 0);
        empty($id) && jump('该活动不存在');

        $info = VoteModel::find($id);
        empty($info) && jump('该活动不存在');

        $info['status'] != VoteModel::STATUS_SHOW && jump('该活动不存在');

        $user_id     = get_user_id();
        $apply       = VoteApplyModel::where('vote_id', $id)->where('user_id', $user_id)->find();
        $is_apply    = 'false';
        $option_name = '';
        if (!empty($apply)) {
            $is_apply    = 'true';
            $option_name = $apply['option_name'];
        }

        return view('', [
            'info'        => $info,
            'is_apply'    => $is_apply,
            'option_name' => $option_name,
        ]);
    }

    public function apply()
    {
        $id = input('id/d', 0);
        empty($id) && ajax_return(1, '该活动不存在');

        $vote = VoteModel::find($id);
        empty($vote) && ajax_return(1, '该活动不存在');
        $vote['status'] != VoteModel::STATUS_SHOW && jump('该活动不存在');

        $option_name = input('option_name', '');
        if (!in_array($option_name, $vote['option'])) {
            ajax_return(1, '该选项不存在，请重新选择');
        }

        $time = time();
        if ($time < strtotime($vote['start_time'])) {
            ajax_return(1, '活动未开始');
        }
        if ($time > strtotime($vote['end_time'])) {
            ajax_return(1, '活动已结束');
        }

        if (request()->ip() != '192.168.1.1') {
            ajax_return(1, '请连接RCG的WIFI进行投票');
        }

        $user_id = get_user_id();
        $check   = VoteApplyModel::where('vote_id', $id)->where('user_id', $user_id)->find();
        if (!empty($check)) {
            ajax_return(1, '请勿重复提交！');
        }

        VoteApplyModel::create([
            'vote_id'     => $id,
            'user_id'     => $user_id,
            'option_name' => $option_name,
        ]);

        ajax_return();
    }
}
