<?php
namespace app\shared\logic\platform;
use app\shared\model\Tags;
use think\exception\ValidateException;
use app\BaseController;
class TagsForm extends  Base
{
    //获取数据
    public  function index(){
        $list=Tags::where(['acid'=>$this->acid,'is_delete'=>0])
        ->page($this->page)
        ->limit($this->limit)
        ->order('sort ASC')
        ->select()
        ->toArray();
        foreach ($list as $key => &$value) {
            $value['cover_url']=get_file_url($value['cover']);
        }
        $count=Tags::where(['acid'=>$this->acid,'is_delete'=>0])->count();
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]); 
    }
    //编辑
    public function edit(){
        $id=input('id');
        $form=Tags::where(['id'=>$id])->find();
        try {
            $data=request()->post();
            $rule = [
                'title|标题'=>'require',
                'sort|排序'=>'require|number',
            ];
            $this->validate($data,$rule);
        } catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        if(!$form){
            $form=new Tags();
            $form->acid=$this->acid;
        }
        $form->title=$data['title'];
        $form->sort=$data['sort'];
        $form->cover=input('cover');
        $form->save();
        return fetchJson([],'保存成功');
    }
    //快速编辑
    public function quickedit(){
        $id=input('id');
        $field=input('field');
        $edittext=input('edittext');
        $fieldArray=['sort'];
        $form=Tags::where(['acid'=>$this->acid,'id'=>$id])->find();
        if(!$form){
             return fetchJson([],'该数据未找到',1);
        }
        if(in_array($field,$fieldArray)){
            try {
               $form->save([
                   "{$field}"=>$edittext
               ]);
            } catch (ValidateException $e) {
                return fetchJson([],$e->getError(),1);
            } catch (\Exception $e) {
                return fetchJson([],$e->getMessage(),1);
            }
           return fetchJson([],'保存成功');
        }
        return fetchJson([],'该字段不能编辑',1);
    }
    //删除
    public function delete(){
         $id=input('id');
         Tags::where(['acid'=>$this->acid,'id'=>$id])->update(['is_delete'=>1]);
         return fetchJson([],'删除成功');
    }
}