userId) ->where('deleted_at', 0) ->orderByDesc('is_default') ->orderByDesc('id') ->get() ->toArray(); } /** * 默认地址,下单表单回填 */ public function defaultOne(): array { $row = WxAddressModel::where('user_id', $this->userId) ->where('deleted_at', 0) ->orderByDesc('is_default') ->orderByDesc('id') ->first(); return $row ? $row->toArray() : []; } public function create(array $params): array { $payload = $this->pick($params); $now = time(); if ((int) ($payload['is_default'] ?? 0) === 1) { $this->clearDefault(); } $id = (int) WxAddressModel::insertGetId(array_merge($payload, [ 'user_id' => $this->userId, 'created_at' => $now, 'updated_at' => $now, ])); return WxAddressModel::where('id', $id)->first()->toArray(); } public function update($id, $params): mixed { $row = $this->owned((int) $id); $payload = $this->pick($params); if ((int) ($payload['is_default'] ?? 0) === 1) { $this->clearDefault(); } $payload['updated_at'] = time(); WxAddressModel::where('id', $row['id'])->update($payload); return WxAddressModel::where('id', $row['id'])->first()->toArray(); } public function delete($ids): mixed { $id = (int) (is_array($ids) ? ($ids[0] ?? 0) : $ids); $row = $this->owned($id); WxAddressModel::where('id', $row['id'])->update(['deleted_at' => time(), 'updated_at' => time()]); return true; } /** * 设为默认 */ public function detail($id): mixed { return $this->owned((int) $id); } public function setDefault(int $id): array { $row = $this->owned($id); $this->clearDefault(); WxAddressModel::where('id', $row['id'])->update(['is_default' => 1, 'updated_at' => time()]); return WxAddressModel::where('id', $row['id'])->first()->toArray(); } private function owned(int $id): array { $row = WxAddressModel::where('id', $id)->where('user_id', $this->userId)->where('deleted_at', 0)->first(); if (empty($row)) { $this->utils->errorThrow('地址不存在'); } return $row->toArray(); } private function clearDefault(): void { WxAddressModel::where('user_id', $this->userId)->where('deleted_at', 0) ->update(['is_default' => 0, 'updated_at' => time()]); } private function pick(array $params): array { $name = trim((string) ($params['name'] ?? '')); $phone = trim((string) ($params['phone'] ?? '')); $address = trim((string) ($params['address'] ?? '')); if ($name === '' || $phone === '' || $address === '') { $this->utils->errorThrow('请填写姓名、手机和地址'); } return [ 'name' => $name, 'phone' => $phone, 'address' => $address, 'is_default' => (int) ($params['is_default'] ?? 0) === 1 ? 1 : 0, ]; } }