<?php

namespace app\controller\api;

use app\repository\CommonRepository;
use app\repository\OperationRepository;
use app\repository\OrderRepository;
use app\validate\CommonValidate;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class Common extends Base
{
    protected $noNeedLogin = [
        'slidePositions',
        'slides',
    ];

    /**
     * 发送短信验证码
     *
     * @OA\Post(
     *     path="/common/send-code",
     *     tags={"common"},
     *     operationId="sendCode",
     * )
     */
    public function sendCode(): Json
    {
        $input    = input('post.');
        $validate = new CommonValidate();
        if (!$validate->scene('send_sms')->check($input)) {
            return $this->json(4001, '参数错误');
        }
        if (!in_array($input['type'], ['register', 'login', 'binding'])) {
            return $this->json(4002, '参数错误');
        }

        CommonRepository::getInstance()->sendSms($input['phone'], $input['type']);
        return $this->json();
    }

    /**
     * 查看轮播图可视位置配置信息
     */
    public function slidePositions(): Json
    {
        $repo = OperationRepository::getInstance();
        $list = $repo->slidePositions();
        return $this->json(0, 'success', $list);
    }


    /**
     * 轮播图
     */
    public function slides(): Json
    {
        $size     = $this->request->param('size/d', 0);
        $position = trim($this->request->param('position/s', ''));
        if (empty($position)) {
            return $this->json();
        }

        try {
            $repo = OperationRepository::getInstance();
            $list = $repo->slideListByPosition($position, $size);
        } catch (\Exception $e) {
            $list = new Collection();
        }

        foreach ($list as &$item) {
            $item["src"] = resourceJoin($item["src"], $this->request->domain());
        }

        return $this->json(0, 'success', $list);
    }

    /**
     * 获取快递公司列表
     *
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function expressList(): Json
    {
        $list = OrderRepository::getInstance()->allExpress();
        return $this->json(0, 'success', $list);
    }

}