<?php
declare (strict_types = 1);

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use app\admin\traits\Actions;
use think\annotation\route\Group;
use think\annotation\route\Route;
use app\common\model\PackSpecs as PackSpecsModel;

#[Group("goods/pack_specs")]
class PackSpecs extends Backend
{
    use Actions;

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new PackSpecsModel();
    }


    /**
     * 查看
     */
    #[Route('GET,JSON', 'index')]
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if ($this->request->post('selectpage')) {
            return $this->selectpage();
        }
        [$where, $order, $limit, $with] = $this->buildparams();
        
        $list = $this->model
            ->withJoin($with, 'left')
            //如果没有使用operate filter过滤的情况下,推荐使用with关联，可以提高查询效率
            //->with($with)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    //添加
    #[Route("GET,POST","add")]
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->fetch();
        }
        $params = $this->request->post("row/a");
        if (empty($params)) {
            return $this->jsonError('提交的参数不能为空');
        }
        $result=$this->model->save($params);
        if ($result === false) {
            return $this->jsonError('没有新增任何数据');
        }
        return $this->jsonSuccess();
        
    }

    //修改
    #[Route("GET,POST","edit")]
    public function edit(mixed $row=null)
    {
        $ids = $this->request->get('ids');
        if(!$row || is_array($row)){
            $row = $this->model->find($ids);
        }
        if(count($this->volidateFields)>0){
            foreach ($this->volidateFields as $field=>$value){
                if($row[$field]!=$value){
                    return $this->jsonError(__('没有操作权限'));
                }
            }
        }
        if (false === $this->request->isPost()) {
            $this->assign('row', $row);
            return $this->fetch();
        }

        $params = $this->request->post("row/a");
        $params['updatetime']=time();
        if (empty($params)) {
            return $this->jsonError('提交的参数不能为空');
        }
        $result=$this->model->saveAll([$params]);
        if ($result === false) {
            return $this->jsonError('没有修改任何数据');
        }
        return $this->jsonSuccess();
        
    }

}
