<?php

namespace app\admin\controller\life;

use app\admin\service\goods\GoodsService;
use app\admin\validate\goods\GoodsValidate;
use support\Request;
use support\Response;

class FarmGoodsController
{
    /**
     * @Desc 添加商品
     * @Author Gorden
     * @Date 2024/3/11 10:21
     *
     * @param Request $request
     * @return Response
     */
    public function insert(Request $request): Response
    {
        $validate = new GoodsValidate();
        if (!$validate->scene('add')->check($request->post())) {
            return json_fail($validate->getError());
        }

        return GoodsService::insert($request->post());
    }

    public function update(Request $request): Response
    {
        $validate = new GoodsValidate();
        if (!$validate->scene('update')->check($request->post())) {
            return json_fail($validate->getError());
        }

        return GoodsService::update($request->post());
    }

    /**
     * @Desc 修改商品状态
     * @Author Gorden
     * @Date 2024/2/28 10:35
     *
     * @param Request $request
     * @return Response
     */
    public function updateStatus(Request $request)
    {
        return $this->updateField($request->post('goods_id'), 'goods_status', $request->post('goods_status'));
    }

    /**
     * @Desc 执行插入数据
     * @Author Gorden
     * @Date 2024/2/28 10:10
     *
     * @param array $data
     * @return mixed|null
     */
    protected function doInsert(array $data)
    {
        $primary_key = $this->model->getKeyName();
        $model_class = get_class($this->model);
        $model = new $model_class;
        $data['goods_content'] = htmlspecialchars($data['goods_content']);
        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        $model->save();
        return $primary_key ? $model->$primary_key : null;
    }
}