<?php
namespace app\shared\logic\platform;
use app\shared\model\Recharge;
use app\shared\model\RechargeOrder;
use app\shared\model\Card;
use app\shared\model\User;
use app\shared\model\Coupon;
use think\exception\ValidateException;
use app\BaseController;
class RechargeForm extends  Base
{
    //获取数据
    public  function index(){
        $query=Recharge::where(['acid'=>$this->acid,'is_delete'=>0]);
        $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=Recharge::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 Recharge();
            $form->acid=$this->acid;
        }
        $form->price=$data['price'];
        $form->give_price=$data['give_price'];
        $form->status=$data['status'];
        $form->card_ids=input('card_ids');
        $form->coupon_ids=input('coupon_ids');
        $form->save();
        return fetchJson([],'保存成功');
    }
    //删除
    public function delete(){
         $id=input('id');
         Recharge::where(['acid'=>$this->acid,'id'=>$id])->update(['is_delete'=>1]);
         return fetchJson([],'删除成功');
    }
    public function orderList(){
        $query=RechargeOrder::alias('a')
        ->leftJoin([User::getTable()=>'b'],'a.user_id=b.id')
        ->where(['a.acid'=>$this->acid,'a.is_pay'=>1])->field('a.*,b.nickname,b.avatar_url');
        $count=$query->count();
        $list=$query
        ->page($this->page)
        ->limit($this->limit)
        ->order('a.id DESC')
        ->select();
        foreach ($list as $key => &$value) {
             $value['card_list']=Card::where(['acid'=>$this->acid])->where('id','in',$value['card_ids'])->column('id,title,discount,cover');
             $value['coupon_list']=Coupon::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1])->where('id','in',$value['coupon_ids'])->column('id,name,price,full_price');
         }
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]);
    }
}