<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\api\user;

use app\repository\user\AddressRepository;
use app\service\api\BaseApiService;
use think\Request;


/**
 * Address Service
 * @package app\service\api\user
 */
class AddressService extends BaseApiService
{
    private const MAX_ADDRESS_COUNT = 20;


    /**
     * 地址列表
     * @param Request $request 请求对象
     * @return array
     */
    public function list(Request $request): array
    {
        $uid = (int)($request->uid ?? 0);
        if ($uid <= 0) {
            return ['code' => 401, 'msg' => '', '_http_status' => 401];
        }
        $list = $this->repo()->listByUser($uid);
        return ['code' => 0, 'data' => $list];
    }


    /**
     * 地址详情
     * @param Request $request 请求对象
     * @return array
     */
    public function detail(Request $request): array
    {
        $uid = (int)($request->uid ?? 0);
        if ($uid <= 0) {
            return ['code' => 401, 'msg' => '', '_http_status' => 401];
        }
        $id = (int)($request->param('id', 0));
        if ($id <= 0) {
            return ['code' => 1, 'msg' => ''];
        }
        $address = $this->repo()->findById($id, $uid);
        if (!$address) {
            return ['code' => 1, 'msg' => ''];
        }
        return ['code' => 0, 'data' => $address->toArray()];
    }


    /**
     * 新增地址
     * @param Request $request 请求对象
     * @return array
     */
    public function create(Request $request): array
    {
        $uid = (int)($request->uid ?? 0);
        if ($uid <= 0) {
            return ['code' => 401, 'msg' => '', '_http_status' => 401];
        }

        $count = $this->repo()->countByUser($uid);
        if ($count >= self::MAX_ADDRESS_COUNT) {
            return ['code' => 1, 'msg' => ''];
        }

        $data = $this->buildData($request, $uid);

        if ($data['is_default']) {
            $this->repo()->unsetDefault($uid);
        } elseif ($count === 0) {
            $data['is_default'] = 1;
        }

        $address = $this->repo()->create($data);
        return ['code' => 0, 'msg' => '', 'data' => ['id' => (int)$address->id]];
    }


    /**
     * 更新地址
     * @param Request $request 请求对象
     * @return array
     */
    public function update(Request $request): array
    {
        $uid = (int)($request->uid ?? 0);
        if ($uid <= 0) {
            return ['code' => 401, 'msg' => '', '_http_status' => 401];
        }

        $id = (int)($request->param('id', 0));
        if ($id <= 0) {
            return ['code' => 1, 'msg' => ''];
        }

        $address = $this->repo()->findById($id, $uid);
        if (!$address) {
            return ['code' => 1, 'msg' => ''];
        }

        $data = $this->buildData($request, $uid);

        if ($data['is_default']) {
            $this->repo()->unsetDefault($uid);
        }

        $this->repo()->update($address, $data);
        return ['code' => 0, 'msg' => ''];
    }


    /**
     * 删除地址
     * @param Request $request 请求对象
     * @return array
     */
    public function delete(Request $request): array
    {
        $uid = (int)($request->uid ?? 0);
        if ($uid <= 0) {
            return ['code' => 401, 'msg' => '', '_http_status' => 401];
        }

        $id = (int)($request->param('id', 0));
        if ($id <= 0) {
            return ['code' => 1, 'msg' => ''];
        }

        $address = $this->repo()->findById($id, $uid);
        if (!$address) {
            return ['code' => 1, 'msg' => ''];
        }

        $this->repo()->delete($address);

        $remaining = $this->repo()->listByUser($uid);
        if (!empty($remaining) && (int)$address->is_default === 1) {
            $first = $remaining[0] ?? null;
            if ($first) {
                $firstModel = $this->repo()->findById((int)$first['id'], $uid);
                if ($firstModel) {
                    $this->repo()->update($firstModel, ['is_default' => 1]);
                }
            }
        }

        return ['code' => 0, 'msg' => ''];
    }


    /**
     * 从请求参数中构建地址数据数组
     * @param Request $request 请求对象
     * @param int $uid 用户ID
     * @return array 地址数据
     */
    private function buildData(Request $request, int $uid): array
    {
        $extends = $request->param('extends', []);
        if (is_string($extends)) {
            $decoded = json_decode($extends, true);
            $extends = is_array($decoded) ? $decoded : [];
        }

        return [
            'user_id'     => $uid,
            'name'        => trim((string)($request->param('name', ''))),
            'phone'       => trim((string)($request->param('phone', ''))),
            'province'    => trim((string)($request->param('province', ''))),
            'city'        => trim((string)($request->param('city', ''))),
            'district'    => trim((string)($request->param('district', ''))),
            'detail'      => trim((string)($request->param('detail', ''))),
            'postal_code' => trim((string)($request->param('postal_code', ''))),
            'is_default'  => (int)($request->param('is_default', 0)),
            'tag'         => trim((string)($request->param('tag', ''))),
            'extends'     => $extends,
        ];
    }

    /**
     * 获取地址仓储实例
     * @return AddressRepository
     */
    private function repo(): AddressRepository
    {
        return $this->app->make(AddressRepository::class);
    }
}