<?php

namespace app\controller\api;

use app\extra\basic\Base;
use app\extra\service\blue\AddressService;
use app\middleware\WxMiddleware;
use app\model\blue\BlueAddress;
use DI\Attribute\Inject;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Middleware;
use LinFly\Annotation\Route\Route;
use support\Request;
use support\Response;


#[Controller(prefix: "/wx_api/address"),Middleware(WxMiddleware::class)]
class Address extends Base
{


    protected array $noNeedLogin = [];

    #[Inject]
    protected BlueAddress $model;

    #[Inject]
    protected AddressService $service;


    /**
     * 地址列表
     * @param Request $request
     * @return Response
     */
    #[Route(path: "list",methods: "get")]
    public function getAddressList(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "size.default"      => 10,
                "page.default"      => 1,
            ],$request->method());
            $list = $this->service->getList(['openid' => $request->user['openid'],'pageSize' => $param['size'],'page' => $param['page']]);
            return success("ok",pageFormat($list));
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 编辑信息
     * @param Request $request
     * @return Response
     */
    #[Route(path: "save",methods: "post")]
    public function setListData(Request $request): Response
    {
        try {
            $param = $request->post();
            if (isset($param['id'])) {
                $factory = $this->model->where("id",$param['id'])->findOrEmpty();
                if ($factory->isEmpty()) return errorTrans("error.data");
            }
            $param['city_path'] = empty($param['city_path']) ? [] : json_encode($param['city_path']);
            $state = $this->model->setAutoData($param);
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     */
    #[Route(path: "del",methods: "post")]
    public function delData(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"        => "参数错误",
            ],"post");
            if (!is_array($param)) return error($param);
            $data = $this->model->where(['id' => $param['id'], 'openid' => $request->user['openid'] ])->findOrEmpty();
            if ($data->isEmpty()) return errorTrans("empty.data");
            $state = $data->delete();
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

}