<?php


namespace app\admin\controller\bbfxshop\luckywheel;

use app\admin\controller\bbfxshop\Base;
use think\Db;


class Lottery extends Base
{
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Luckywheel;
    }
    
    public function getList(){
        $params = $this->param();
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):10;
        $code = $params["code"];
        $where = array("a.uniacid"=>UNIACID);
        if(!empty($code)){
            $where['a.code'] = $code;
        }
        
        $list = Db::name("bbfx_luckywheel_lottery_record")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where($where)->field("a.*,b.nickname,b.avatar")->order('id desc')->limit(($pindex - 1) * $psize,$psize)->select();
        $total = Db::name("bbfx_luckywheel_lottery_record")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where($where)->count();
        
        foreach ($list as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
            $val['prize'] = iunserializer($val['prize']);
            $val['prize']['image'] = cdnurl($val['prize']['image']);
            $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            if($val['prize']['type'] == 3){
                $reward = iunserializer($val['prize']['reward']);
                
                $coupon = Db::name("bbfx_coupon")->where(['uniacid'=>UNIACID,'status'=>1,'id'=>['in',$reward]])->field("id,name")->select();
                
                if(!empty($coupon)){
                    $coupon_name = array_column($coupon,"name");
                    
                    $val['prize']['reward'] = implode("，",$coupon_name);
                }
                else{
                    $val['prize']['reward'] = "优惠券ID：".implode("，",$reward);
                }
            }
        }
        unset($val);
        
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function duihuan(){
        $id = $this->param("id/d");
        $item = Db::name("bbfx_luckywheel_lottery_record")->where(['id'=>$id])->find();
        if(empty($item)){
            __error("中奖记录不存在");
        }
        
        if($item['status'] == 1){
            __error("奖励已兑换");
        }
        
        $res = Db::name("bbfx_luckywheel_lottery_record")->where(['id'=>$item['id']])->update(['status'=>1]);
        if($res){
            
            Db::name("bbfx_luckywheel_lottery_record")->where(['id'=>$item['id']])->update(['dhtime'=>time()]);
            
            __success("兑换成功");
        }
        else{
            __error("兑换失败");
        }
        
    }
    
    public function delete(){
        $this->commonDelete("bbfx_luckywheel_lottery_record");
    }
}