<?php
namespace app\shared\logic\store;
use app\shared\model\StoreRecharge;
use app\shared\model\StoreRechargeOrder;
use app\shared\model\StoreUserMoney;
use app\shared\model\User;
use think\exception\ValidateException;
use app\BaseController;
class RechargeForm extends  Base
{
    //用户列表
    public function userList(){
       $query=StoreUserMoney::alias('a')
            ->leftJoin([User::getTable()=>'b'],'a.user_id=b.id')
            ->where(['a.acid'=>$this->acid,'a.store_id'=>$this->store_id])
            ->field('a.*,b.account,b.nickname,b.avatar_url');
        $count=$query->count();
        $list=$query
            ->page($this->page)
            ->limit($this->limit)
            ->order('a.id DESC')
            ->select();
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]);
    }
    //获取数据
    public  function index(){
        $query=StoreRecharge::where(['acid'=>$this->acid,'is_delete'=>0,'store_id'=>$this->store_id]);
        $count=$query->count();
        $list=$query
        ->page($this->page)
        ->limit($this->limit)
        ->order('id DESC')
        ->select()
        ->toArray();
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]);
    }
    //编辑
    public function edit(){
        $id=input('id');
        $form=StoreRecharge::where(['id'=>$id])->find();
        try {
            $data=request()->post();
            $rule = [
                'price|金额'=>'require',
                'give_price|赠送金额'=>'require',
                'status|状态'=>'require|in:0,1',
            ];
            $this->validate($data,$rule);
        } catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        if(!$form){
            $form=new StoreRecharge();
            $form->acid=$this->acid;
            $form->store_id=$this->store_id;
        }
        $form->price=$data['price'];
        $form->give_price=$data['give_price'];
        $form->status=$data['status'];
        $form->save();
        return fetchJson([],'保存成功');
    }
    //删除
    public function delete(){
         $id=input('id');
         StoreRecharge::where(['acid'=>$this->acid,'id'=>$id])->update(['is_delete'=>1]);
         return fetchJson([],'删除成功');
    }
    //订单列表
    public function orderList(){
        $query=StoreRechargeOrder::alias('a')
            ->leftJoin([User::getTable()=>'b'],'a.user_id=b.id')
            ->where(['a.acid'=>$this->acid,'a.store_id'=>$this->store_id,'a.status'=>1])
            ->field('a.*,b.nickname,b.avatar_url');
        $count=$query->count();
        $list=$query
            ->page($this->page)
            ->limit($this->limit)
            ->order('a.id DESC')
            ->select();
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]);
    }
}