<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 家族卡
 */
class Relation extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    //关系卡列表
    public function decorate_list(){
        $list = Db::name('decorate_relation')->select();
        $list = list_domain_image($list,['base_image']);

        $this->success(1,$list);
    }

    /**
     * 购买并加入我的背包
     */
    public function buy_one() {
        $number = input('number',1,'intval'); //数量
        if(!$number){
            $this->error();
        }

        $did = input('did',''); //装扮ID
        if (!$did) {
            $this->error();
        }
        // 判断用户金币余额是否充足
        $walletinfo = model('wallet')->getWallet($this->auth->id);

        // 获取购买装扮需要的价格
        $decorate = Db::name('decorate_relation')->where(['id'=>$did])->find();
        if(!$decorate) {
            $this->error("道具信息获取失败!");
        }
        $total_price = bcmul($decorate['price'],$number,0);
        if($walletinfo['jewel'] < $total_price) {
            $this->error("您的金币不足,请先充值!");
        }
        // 进行购买逻辑
        Db::startTrans();

        // 添加到背包
        for($i=1;$i<=$number;$i++){
            $data[] = [
                'user_id' => $this->auth->id,
                'decorate_id' => $decorate['id'],
                'is_using' => 0,
                'createtime' => time(),
                'updatetime' => time(),
            ];
        }

        $log_id = Db::name('user_decorate_relation')->insertAll($data);
        if(!$log_id){
            Db::rollback();
            $this->error('购买失败');
        }

        //扣钱
        $rs = model('wallet')->lockChangeAccountRemain($this->auth->id,$total_price,'-',0,'购买家族卡',32,'jewel');
        if($rs['status'] === false){
            Db::rollback();
            $this->error($rs['msg']);
        }


        Db::commit();
        $this->success("购买成功!");
    }


    //获取用户装扮
    public function my_decorate_list()
    {
        $uid = $this->auth->id;

        $map = [
            'a.user_id' => $uid,
            'a.is_using'=> 0,
        ];

        $list = Db::name('user_decorate_relation')
            ->alias('a')
            ->field('a.id,a.decorate_id,b.name,b.base_image,count(a.decorate_id) as number')
            ->join('decorate_relation b', 'a.decorate_id = b.id','LEFT')
            ->where($map)->group('a.decorate_id')->order('a.id desc')->autopage()->select();

        $list = list_domain_image($list,['base_image']);

        $this->success('success',$list);
    }
}