<?php
namespace app\shared\logic\user;
use app\shared\model\Collection;
use app\shared\model\TeaCircle;
use app\shared\model\House;
use app\shared\model\Store;
use app\shared\model\User;
use think\exception\ValidateException;
class CollectionForm extends  UserForm
{
  //收藏列表
  public function list(){
      $type=input('type');
      $query=Collection::alias('c')->where([
          'c.acid'=>$this->acid,
          'c.user_id'=>$this->user_id,
          'c.type'=>$type,
          'c.is_delete'=>0
      ]);
      $list=[];
      switch ($type) {
        case Collection::TYPE_STORE:
         $query->leftJoin([Store::getTable()=>'s'],'c.form_id=s.id')->field('c.*,s.name,s.logo cover');
          break;
        case Collection::TYPE_HOUSE:
         $query->leftJoin([House::getTable()=>'h'],'c.form_id=h.id')->field('c.*,h.name,h.cover');
          break;
        case Collection::TYPE_CQSC:
         $query->leftJoin([TeaCircle::getTable()=>'t'],'c.form_id=t.id')->field('c.*,t.title,t.images cover');
          break;
        default:
         $query->leftJoin([Store::getTable()=>'s'],'c.form_id=s.id')->field('c.*,s.name,s.logo cover');
          break;
      }
      $list=$query->page($this->page)->limit(10)->select();
      foreach ($list as &$value) {
        $value['cover_url']=get_file_url($value['cover']);
      }
      return fetchJson($list); 
  }
	//提交
	public function submit(){
      try {
          $data=request()->post();
          $rule = [
             'type|类型' => 'require|number',
             'form_id|来源' => 'require|number',
           ];
          $this->validate($data,$rule);
       }catch (ValidateException $e){
          return fetchJson([],$e->getError(),1);
       }
       $form=Collection::where([
          'acid'=>$this->acid,
          'user_id'=>$this->user_id,
          'type'=>$data['type'],
          'form_id'=>$data['form_id']
       ])->find();
       if(!$form){
            $form=new Collection();
            $form->acid=$this->acid;
            $form->user_id=$this->user_id;
            $form->type=$data['type'];
            $form->form_id=$data['form_id'];
            $form->is_delete=0;
            $form->save();
            return fetchJson([],'收藏成功');
       }
       if($form->is_delete==0){
          $form->is_delete=1;
          $msg='取消成功';
       }else{
          $form->is_delete=0;
          $msg='收藏成功';
       }
       $form->save();
       return fetchJson([],$msg);
	}
}