<?php

namespace app\api\controller\Product;

use app\BaseController;
use app\common\model\Product\Product as ModelProduct;
use app\common\model\Product\ProductType as ModelProductType;
use app\Request;
use think\Validate;
use think\exception\ValidateException;
use think\facade\Filesystem;
use app\common\arw\adjfut\src\Excel;
use app\common\arw\adjfut\src\UploadFile;
use app\common\exception\Tool;
use think\facade\Db;
use think\facade\Env;


class Product extends BaseController
{
    /**
     * 获取产品列表接口
     *
     * @param Request request
     * @date 2023-03-25
     * @example
     * @author xjh
     * @since 1.0.0
     */
    public function getProductList(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'product_type_id|产品系列' => 'require',
        ]);

        $product_type = ModelProductType::where('product_type_id', $params['product_type_id'])->find();
        if (!$product_type) throwErrorMsg('产品系列不存在!');

        $con = [
            ['product_type_guid', '=', $product_type->product_type_guid]
        ];

        $query = ModelProduct::where($con)
            ->field([
                'product_id',
                'product_guid',
                'product_type_guid',
                'product_name',
                'product_img',
                'product_price',
            ])
            ->withAttr('product_img', function ($value, $data) {
                return  explode(',', $data['product_img'])[0];
            })
            ->order('product_id', 'desc');

        return msg("获取产品列表成功!", $query);
    }

    /**
     * 获取产品详情接口
     *
     * @param Request request
     * @date 2023-04-03
     * @example
     * @author xjh
     * @since 1.0.0
     */
    public function getProductInfo(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'product_id|产品id' => 'require',
        ]);

        $find = ModelProduct::where('product_id', $params['product_id'])
            ->field([
                'product_id',
                'product_guid',
                'product_type_guid',
                'product_name',
                'product_img',
                'product_price',
                'product_params',
                'product_details',
            ])
            ->find();
        if (!$find) throwErrorMsg('该产品不存在！');

        $last_next_id = Tool::getLastNextId(
            new ModelProduct,
            ['product_id', $find->product_id],
            'all',
            [['product_type_guid', '=', $find->product_type_guid]]
        );

        return msg(
            "获取产品详情成功!",
            [
                'data' => $find,
                'last_id' => $last_next_id[0],
                'next_id' => $last_next_id[1],
            ]
        );
    }
}
