<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\api\controller;
use think\facade\Db;

/**
 * 投票
 */
class Vote extends BaseShopController
{
    /**
     * 投票
     */
    public function add($vote_options_id)
    {
        $user_id = $this->userId;
        $res = \think\facade\Db::transaction(function() use ($vote_options_id,$user_id){
            
            $vote = \app\common\model\VoteOptions::find($vote_options_id);
            
            $vote_main = \app\common\model\Vote::find($vote['vote_id']);
            
            if($vote_main->type == 2){
                // 多选
                $res = \app\common\model\VoteLog::where([
                    ['vote_id','=',$vote->vote_id],
                    ['user_id','=',$user_id],
                    ['vote_options_id','=',$vote->id]
                ])->find();

            }else{
                // 单选
                $res = \app\common\model\VoteLog::where([
                    ['vote_id','=',$vote->vote_id],
                    ['user_id','=',$user_id],
                ])->find();

            }
            
            if($res){
                dd("请不要重复投票，前端做判断限制不能重复投票");
            }

            $vote->number += 1;
            $res = $vote->save();

            \app\common\model\VoteLog::create([
                'vote_options_id'=>$vote_options_id,
                'vote_id'=>$vote->vote_id,
                'user_id'=>$user_id
            ]);

            return $res;
        });
        
        if($res){
            return show(1,'投票成功');
        } 
        return show(0,'投票失败');
    }

}
