Compare commits

..

5 Commits

Author SHA1 Message Date
96feda4364 feat: 重构律师列表卡片展示
- 简化筛选栏与列表快捷入口

- 为律师卡片增加 featured 布局和联系方式展示
2026-03-21 22:02:15 +08:00
63685f8644 feat: 调整律所首页信息区布局
- 精简首页头图展示并优化地址卡片样式

- 将专业领域提前到律所简介之前
2026-03-21 22:01:57 +08:00
f39fcd05aa feat: 优化名片分享海报与详情交互
- 为律师详情页增加分享海报生成与分享封面图

- 新增律所简介入口并调整个人简介为页面整体滚动
2026-03-21 22:01:33 +08:00
ac7eb6d85d fix: 修复开放接口鉴权与小程序联调配置
- 注册小程序租户过滤器并放宽 /api/open 路径匹配

- 移除全局异常吞没逻辑并修复律师列表筛选空值处理

- 统一小程序 develop、trial、release 环境接口域名
2026-03-21 11:18:04 +08:00
728847a8e3 fix: 修复地图坐标校验与解析
- 小程序兼容字符串坐标并自动纠正历史经纬度反向数据

- 后台机构资料页增加经纬度与地址联动校验

- org 模块保存机构资料时拦截非法坐标输入
2026-03-21 11:17:02 +08:00
24 changed files with 1202 additions and 339 deletions

View File

@@ -5,6 +5,7 @@ import com.easycard.common.auth.JwtTokenService;
import com.easycard.common.auth.LoginUser; import com.easycard.common.auth.LoginUser;
import com.easycard.common.tenant.TenantContext; import com.easycard.common.tenant.TenantContext;
import com.easycard.common.tenant.TenantContextHolder; import com.easycard.common.tenant.TenantContextHolder;
import com.easycard.module.tenant.web.MiniappTenantContextFilter;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain; import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
@@ -83,7 +84,8 @@ public class SecurityConfig {
@Bean @Bean
public SecurityFilterChain securityFilterChain( public SecurityFilterChain securityFilterChain(
HttpSecurity http, HttpSecurity http,
JwtAuthenticationFilter jwtAuthenticationFilter JwtAuthenticationFilter jwtAuthenticationFilter,
MiniappTenantContextFilter miniappTenantContextFilter
) throws Exception { ) throws Exception {
http http
.csrf(AbstractHttpConfigurer::disable) .csrf(AbstractHttpConfigurer::disable)
@@ -108,6 +110,7 @@ public class SecurityConfig {
response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write("{\"code\":\"UNAUTHORIZED\",\"message\":\"未登录或登录已失效\",\"data\":null}"); response.getWriter().write("{\"code\":\"UNAUTHORIZED\",\"message\":\"未登录或登录已失效\",\"data\":null}");
})) }))
.addFilterBefore(miniappTenantContextFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.cors(Customizer.withDefaults()); .cors(Customizer.withDefaults());
return http.build(); return http.build();
@@ -128,7 +131,10 @@ class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override @Override
protected boolean shouldNotFilter(HttpServletRequest request) { protected boolean shouldNotFilter(HttpServletRequest request) {
String uri = request.getRequestURI(); String uri = request.getRequestURI();
return uri.startsWith("/api/open/") || "/api/v1/auth/login".equals(uri); if (uri == null) {
return false;
}
return uri.contains("/api/open/") || uri.endsWith("/api/v1/auth/login");
} }
@Override @Override

View File

@@ -32,9 +32,4 @@ public class GlobalExceptionHandler {
public ApiResponse<Void> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException exception) { public ApiResponse<Void> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException exception) {
return ApiResponse.fail("FILE_TOO_LARGE", "上传图片不能超过 5MB"); return ApiResponse.fail("FILE_TOO_LARGE", "上传图片不能超过 5MB");
} }
@ExceptionHandler(Exception.class)
public ApiResponse<Void> handleException(Exception exception) {
return ApiResponse.fail("INTERNAL_SERVER_ERROR", exception.getMessage());
}
} }

View File

@@ -343,18 +343,21 @@ public class CardProfileService {
Map<Long, List<String>> specialtyMap = loadSpecialtyMap(cards.stream().map(CardProfileDO::getId).toList()); Map<Long, List<String>> specialtyMap = loadSpecialtyMap(cards.stream().map(CardProfileDO::getId).toList());
return cards.stream() return cards.stream()
.filter(card -> { .filter(card -> {
String deptName = deptMap.containsKey(card.getDeptId()) ? deptMap.get(card.getDeptId()).getDeptName() : ""; OrgDepartmentDO department = card.getDeptId() == null ? null : deptMap.get(card.getDeptId());
String deptName = department == null ? "" : department.getDeptName();
List<String> specialties = specialtyMap.getOrDefault(card.getId(), List.of()); List<String> specialties = specialtyMap.getOrDefault(card.getId(), List.of());
boolean keywordMatched = !StringUtils.hasText(keyword) boolean keywordMatched = !StringUtils.hasText(keyword)
|| card.getCardName().contains(keyword) || containsText(card.getCardName(), keyword)
|| deptName.contains(keyword) || containsText(deptName, keyword)
|| specialties.stream().anyMatch(item -> item.contains(keyword)); || specialties.stream().anyMatch(item -> containsText(item, keyword));
boolean officeMatched = !StringUtils.hasText(office) || office.equals(deptName); boolean officeMatched = !StringUtils.hasText(office) || office.equals(deptName);
boolean areaMatched = !StringUtils.hasText(practiceArea) || specialties.stream().anyMatch(item -> item.equals(practiceArea)); boolean areaMatched = !StringUtils.hasText(practiceArea)
|| specialties.stream().anyMatch(item -> equalsText(item, practiceArea));
return keywordMatched && officeMatched && areaMatched; return keywordMatched && officeMatched && areaMatched;
}) })
.map(card -> { .map(card -> {
String deptName = deptMap.containsKey(card.getDeptId()) ? deptMap.get(card.getDeptId()).getDeptName() : ""; OrgDepartmentDO department = card.getDeptId() == null ? null : deptMap.get(card.getDeptId());
String deptName = department == null ? "" : department.getDeptName();
return new OpenCardListItem( return new OpenCardListItem(
card.getId(), card.getId(),
card.getCardName(), card.getCardName(),
@@ -496,6 +499,14 @@ public class CardProfileService {
return AUTO_MANAGED_ROLE_CODE.equals(roleCode); return AUTO_MANAGED_ROLE_CODE.equals(roleCode);
} }
private boolean containsText(String source, String keyword) {
return source != null && keyword != null && source.contains(keyword);
}
private boolean equalsText(String left, String right) {
return left != null && left.equals(right);
}
private SysUserDO createHiddenLawyerUser(LoginUser loginUser, UpsertCardRequest request) { private SysUserDO createHiddenLawyerUser(LoginUser loginUser, UpsertCardRequest request) {
SysRoleDO role = getRequiredTenantRole(loginUser.tenantId(), AUTO_MANAGED_ROLE_CODE); SysRoleDO role = getRequiredTenantRole(loginUser.tenantId(), AUTO_MANAGED_ROLE_CODE);
SysUserDO user = new SysUserDO(); SysUserDO user = new SysUserDO();

View File

@@ -17,6 +17,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.List; import java.util.List;
@@ -58,6 +59,7 @@ public class TenantOrgService {
profile.setCreatedBy(loginUser.userId()); profile.setCreatedBy(loginUser.userId());
profile.setDeleted(0); profile.setDeleted(0);
} }
CoordinateValue coordinates = parseCoordinates(request.hqAddress(), request.hqLatitude(), request.hqLongitude());
profile.setFirmName(request.firmName()); profile.setFirmName(request.firmName());
profile.setFirmShortName(request.firmShortName()); profile.setFirmShortName(request.firmShortName());
profile.setEnglishName(request.englishName()); profile.setEnglishName(request.englishName());
@@ -68,8 +70,8 @@ public class TenantOrgService {
profile.setWebsiteUrl(request.websiteUrl()); profile.setWebsiteUrl(request.websiteUrl());
profile.setWechatOfficialAccount(request.wechatOfficialAccount()); profile.setWechatOfficialAccount(request.wechatOfficialAccount());
profile.setHqAddress(request.hqAddress()); profile.setHqAddress(request.hqAddress());
profile.setHqLatitude(toBigDecimal(request.hqLatitude())); profile.setHqLatitude(coordinates.latitude());
profile.setHqLongitude(toBigDecimal(request.hqLongitude())); profile.setHqLongitude(coordinates.longitude());
profile.setUpdatedBy(loginUser.userId()); profile.setUpdatedBy(loginUser.userId());
if (profile.getId() == null) { if (profile.getId() == null) {
orgFirmProfileMapper.insert(profile); orgFirmProfileMapper.insert(profile);
@@ -217,11 +219,51 @@ public class TenantOrgService {
); );
} }
private BigDecimal toBigDecimal(String value) { private CoordinateValue parseCoordinates(String address, String latitude, String longitude) {
if (value == null || value.isBlank()) { String latitudeText = normalizeCoordinate(latitude);
return null; String longitudeText = normalizeCoordinate(longitude);
boolean hasLatitude = StringUtils.hasText(latitudeText);
boolean hasLongitude = StringUtils.hasText(longitudeText);
if (!hasLatitude && !hasLongitude) {
return new CoordinateValue(null, null);
} }
if (!hasLatitude || !hasLongitude) {
throw new BusinessException("FIRM_COORDINATE_INVALID", "纬度和经度需同时填写");
}
if (!StringUtils.hasText(address)) {
throw new BusinessException("FIRM_ADDRESS_REQUIRED", "填写地图坐标时请同时填写详细地址");
}
BigDecimal latitudeValue = parseCoordinateValue(latitudeText, "纬度");
BigDecimal longitudeValue = parseCoordinateValue(longitudeText, "经度");
if (!isInRange(latitudeValue, -90, 90)) {
if (isInRange(latitudeValue, -180, 180) && isInRange(longitudeValue, -90, 90)) {
throw new BusinessException("FIRM_COORDINATE_INVALID", "纬度超出范围,请检查是否与经度填反");
}
throw new BusinessException("FIRM_COORDINATE_INVALID", "纬度范围应在 -90 到 90 之间");
}
if (!isInRange(longitudeValue, -180, 180)) {
throw new BusinessException("FIRM_COORDINATE_INVALID", "经度范围应在 -180 到 180 之间");
}
return new CoordinateValue(latitudeValue, longitudeValue);
}
private String normalizeCoordinate(String value) {
return value == null ? "" : value.trim();
}
private BigDecimal parseCoordinateValue(String value, String fieldLabel) {
try {
return new BigDecimal(value); return new BigDecimal(value);
} catch (NumberFormatException exception) {
throw new BusinessException("FIRM_COORDINATE_INVALID", fieldLabel + "必须是数字");
}
}
private boolean isInRange(BigDecimal value, int min, int max) {
return value.compareTo(BigDecimal.valueOf(min)) >= 0 && value.compareTo(BigDecimal.valueOf(max)) <= 0;
} }
private String resolveAssetUrl(Long assetId) { private String resolveAssetUrl(Long assetId) {
@@ -270,6 +312,9 @@ public class TenantOrgService {
) { ) {
} }
private record CoordinateValue(BigDecimal latitude, BigDecimal longitude) {
}
public record PracticeAreaView(Long id, String areaCode, String areaName, Integer displayOrder, String areaStatus) { public record PracticeAreaView(Long id, String areaCode, String areaName, Integer displayOrder, String areaStatus) {
} }

View File

@@ -33,7 +33,8 @@ public class MiniappTenantContextFilter extends OncePerRequestFilter {
@Override @Override
protected boolean shouldNotFilter(HttpServletRequest request) { protected boolean shouldNotFilter(HttpServletRequest request) {
return !request.getRequestURI().startsWith("/api/open/"); String uri = request.getRequestURI();
return uri == null || !uri.contains("/api/open/");
} }
@Override @Override

View File

@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue' import { computed, onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import type { UploadRequestOptions } from 'element-plus' import type { UploadRequestOptions } from 'element-plus'
import { Plus } from '@element-plus/icons-vue' import { Plus } from '@element-plus/icons-vue'
@@ -19,6 +20,7 @@ function generateDeptCode() {
const loading = ref(false) const loading = ref(false)
const saving = ref(false) const saving = ref(false)
const formRef = ref<FormInstance>()
const imageUploading = reactive({ const imageUploading = reactive({
logo: false, logo: false,
hero: false, hero: false,
@@ -72,6 +74,95 @@ const deptOptions = computed(() => departments.value.map(item => ({
value: item.id, value: item.id,
}))) })))
function normalizeText(value: string | null | undefined) {
return typeof value === 'string' ? value.trim() : ''
}
function parseCoordinate(value: string | null | undefined) {
const normalized = normalizeText(value)
if (!normalized) {
return null
}
const parsed = Number(normalized)
return Number.isFinite(parsed) ? parsed : null
}
function hasCoordinateInput() {
return Boolean(normalizeText(profile.hqLatitude) || normalizeText(profile.hqLongitude))
}
function getCoordinateValidationMessage() {
const latitudeText = normalizeText(profile.hqLatitude)
const longitudeText = normalizeText(profile.hqLongitude)
const hasLatitude = Boolean(latitudeText)
const hasLongitude = Boolean(longitudeText)
if (!hasLatitude && !hasLongitude) {
return ''
}
if (!hasLatitude || !hasLongitude) {
return '纬度和经度需同时填写'
}
const latitude = parseCoordinate(profile.hqLatitude)
if (latitude === null) {
return '纬度必须是数字'
}
const longitude = parseCoordinate(profile.hqLongitude)
if (longitude === null) {
return '经度必须是数字'
}
if (latitude < -90 || latitude > 90) {
if (latitude >= -180 && latitude <= 180 && longitude >= -90 && longitude <= 90) {
return '纬度超出范围,请检查是否与经度填反'
}
return '纬度范围应在 -90 到 90 之间'
}
if (longitude < -180 || longitude > 180) {
return '经度范围应在 -180 到 180 之间'
}
if (!normalizeText(profile.hqAddress)) {
return '填写地图坐标时请同时填写详细地址'
}
return ''
}
const profileRules: FormRules = {
firmName: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
hqAddress: [{
trigger: ['blur', 'change'],
validator: async () => {
if (hasCoordinateInput() && !normalizeText(profile.hqAddress)) {
throw new Error('填写地图坐标时请同时填写详细地址')
}
},
}],
hqLatitude: [{
trigger: ['blur', 'change'],
validator: async () => {
const message = getCoordinateValidationMessage()
if (message) {
throw new Error(message)
}
},
}],
hqLongitude: [{
trigger: ['blur', 'change'],
validator: async () => {
const message = getCoordinateValidationMessage()
if (message) {
throw new Error(message)
}
},
}],
}
async function loadData() { async function loadData() {
loading.value = true loading.value = true
try { try {
@@ -135,6 +226,11 @@ function handleHeroUpload(options: UploadRequestOptions) {
} }
async function saveProfile() { async function saveProfile() {
const valid = await formRef.value?.validate().then(() => true).catch(() => false)
if (!valid) {
return
}
saving.value = true saving.value = true
try { try {
const saved = await tenantApi.saveFirmProfile(profile) const saved = await tenantApi.saveFirmProfile(profile)
@@ -267,9 +363,15 @@ onMounted(() => {
</div> </div>
</div> </div>
<el-form label-position="top" class="card-form material-form"> <el-form
ref="formRef"
:model="profile"
:rules="profileRules"
label-position="top"
class="card-form material-form"
>
<div class="form-grid"> <div class="form-grid">
<el-form-item label="名称"> <el-form-item label="名称" prop="firmName">
<el-input v-model="profile.firmName" class="material-input" placeholder="完整的机构注册名称" /> <el-input v-model="profile.firmName" class="material-input" placeholder="完整的机构注册名称" />
</el-form-item> </el-form-item>
<el-form-item label="简称"> <el-form-item label="简称">
@@ -284,13 +386,13 @@ onMounted(() => {
<el-form-item label="官网地址"> <el-form-item label="官网地址">
<el-input v-model="profile.websiteUrl" class="material-input" /> <el-input v-model="profile.websiteUrl" class="material-input" />
</el-form-item> </el-form-item>
<el-form-item label="详细地址" class="form-grid__full"> <el-form-item label="详细地址" prop="hqAddress" class="form-grid__full">
<el-input v-model="profile.hqAddress" class="material-input" placeholder="完整的真实办公地址" /> <el-input v-model="profile.hqAddress" class="material-input" placeholder="完整的真实办公地址" />
</el-form-item> </el-form-item>
<el-form-item label="纬度 (LAT)"> <el-form-item label="纬度 (LAT)" prop="hqLatitude">
<el-input v-model="profile.hqLatitude" class="material-input" placeholder="例如31.230416" /> <el-input v-model="profile.hqLatitude" class="material-input" placeholder="例如31.230416" />
</el-form-item> </el-form-item>
<el-form-item label="经度 (LNG)"> <el-form-item label="经度 (LNG)" prop="hqLongitude">
<el-input v-model="profile.hqLongitude" class="material-input" placeholder="例如121.473701" /> <el-input v-model="profile.hqLongitude" class="material-input" placeholder="例如121.473701" />
</el-form-item> </el-form-item>
<el-form-item label="机构简介" class="form-grid__full"> <el-form-item label="机构简介" class="form-grid__full">

View File

@@ -8,8 +8,8 @@ interface OpenFirmResponse {
intro: string; intro: string;
hotlinePhone: string; hotlinePhone: string;
hqAddress: string; hqAddress: string;
hqLatitude: number; hqLatitude: number | string | null;
hqLongitude: number; hqLongitude: number | string | null;
officeCount: number; officeCount: number;
lawyerCount: number; lawyerCount: number;
officeList: string[]; officeList: string[];
@@ -42,11 +42,62 @@ interface OpenCardDetailResponse {
specialties: string[]; specialties: string[];
firmName: string; firmName: string;
firmAddress: string; firmAddress: string;
firmLatitude: number; firmLatitude: number | string | null;
firmLongitude: number; firmLongitude: number | string | null;
}
function parseCoordinate(value: number | string | null | undefined): number | null {
if (typeof value === 'number') {
return Number.isFinite(value) ? value : null;
}
if (typeof value !== 'string') {
return null;
}
const normalized = value.trim();
if (!normalized) {
return null;
}
const parsed = Number(normalized);
return Number.isFinite(parsed) ? parsed : null;
}
function isLatitude(value: number | null): value is number {
return value !== null && value >= -90 && value <= 90;
}
function isLongitude(value: number | null): value is number {
return value !== null && value >= -180 && value <= 180;
}
function normalizeCoordinates(latitude: number | string | null | undefined, longitude: number | string | null | undefined): {
latitude: number;
longitude: number;
} {
const parsedLatitude = parseCoordinate(latitude);
const parsedLongitude = parseCoordinate(longitude);
if (isLatitude(parsedLatitude) && isLongitude(parsedLongitude)) {
return {
latitude: parsedLatitude,
longitude: parsedLongitude,
};
}
if (isLatitude(parsedLongitude) && isLongitude(parsedLatitude)) {
return {
latitude: parsedLongitude,
longitude: parsedLatitude,
};
}
return {
latitude: 0,
longitude: 0,
};
} }
function toFirmInfo(payload: OpenFirmResponse): FirmInfo { function toFirmInfo(payload: OpenFirmResponse): FirmInfo {
const coordinates = normalizeCoordinates(payload.hqLatitude, payload.hqLongitude);
return { return {
id: payload.name || 'firm', id: payload.name || 'firm',
name: payload.name || '', name: payload.name || '',
@@ -54,8 +105,8 @@ function toFirmInfo(payload: OpenFirmResponse): FirmInfo {
intro: payload.intro || '', intro: payload.intro || '',
hotlinePhone: payload.hotlinePhone || '', hotlinePhone: payload.hotlinePhone || '',
hqAddress: payload.hqAddress || '', hqAddress: payload.hqAddress || '',
hqLatitude: payload.hqLatitude || 0, hqLatitude: coordinates.latitude,
hqLongitude: payload.hqLongitude || 0, hqLongitude: coordinates.longitude,
officeCount: payload.officeCount || 0, officeCount: payload.officeCount || 0,
lawyerCount: payload.lawyerCount || 0, lawyerCount: payload.lawyerCount || 0,
heroImage: payload.heroImage || '', heroImage: payload.heroImage || '',
@@ -114,6 +165,7 @@ export async function getLawyerDetail(cardId: string, sourceType = 'DIRECT', sha
const payload = await request<OpenCardDetailResponse>({ const payload = await request<OpenCardDetailResponse>({
url: `/api/open/cards/${encodeURIComponent(cardId)}?${queryParts.join('&')}`, url: `/api/open/cards/${encodeURIComponent(cardId)}?${queryParts.join('&')}`,
}); });
const coordinates = normalizeCoordinates(payload.firmLatitude, payload.firmLongitude);
return { return {
firm: { firm: {
@@ -123,8 +175,8 @@ export async function getLawyerDetail(cardId: string, sourceType = 'DIRECT', sha
intro: '', intro: '',
hotlinePhone: '', hotlinePhone: '',
hqAddress: payload.firmAddress || '', hqAddress: payload.firmAddress || '',
hqLatitude: payload.firmLatitude || 0, hqLatitude: coordinates.latitude,
hqLongitude: payload.firmLongitude || 0, hqLongitude: coordinates.longitude,
officeCount: 0, officeCount: 0,
lawyerCount: 0, lawyerCount: 0,
heroImage: '', heroImage: '',

View File

@@ -0,0 +1,8 @@
<svg width="96" height="96" viewBox="0 0 96 96" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M23 68L36 53L48 57L60 50L73 66L56 72L45 67L31 72L23 68Z" stroke="#1A1A1A" stroke-width="4.5" stroke-linejoin="round"/>
<path d="M36 53L31 72" stroke="#1A1A1A" stroke-width="4.5" stroke-linecap="round"/>
<path d="M48 57L45 67" stroke="#1A1A1A" stroke-width="4.5" stroke-linecap="round"/>
<path d="M60 50L56 72" stroke="#1A1A1A" stroke-width="4.5" stroke-linecap="round"/>
<path d="M48 18C38.0589 18 30 26.0589 30 36C30 49.5 48 62 48 62C48 62 66 49.5 66 36C66 26.0589 57.9411 18 48 18Z" fill="#1A1A1A"/>
<circle cx="48" cy="36" r="8" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 671 B

View File

@@ -1,4 +1,12 @@
<view class="action-dock"> <view class="action-dock">
<view class="action-item" data-action="home" bindtap="handleAction">
<text class="icon">所</text>
<text>律所简介</text>
</view>
<view class="action-item" data-action="location" bindtap="handleAction">
<text class="icon">导</text>
<text>律所导航</text>
</view>
<view class="action-item" data-action="save" bindtap="handleAction"> <view class="action-item" data-action="save" bindtap="handleAction">
<text class="icon">存</text> <text class="icon">存</text>
<text>收下名片</text> <text>收下名片</text>
@@ -7,8 +15,4 @@
<text class="icon">享</text> <text class="icon">享</text>
<text>分享名片</text> <text>分享名片</text>
</button> </button>
<view class="action-item" data-action="location" bindtap="handleAction">
<text class="icon">导</text>
<text>律所导航</text>
</view>
</view> </view>

View File

@@ -8,7 +8,7 @@
.filter-item { .filter-item {
height: 84rpx; height: 84rpx;
padding: 0 18rpx; padding: 0 22rpx;
border-radius: 14rpx; border-radius: 14rpx;
border: 1rpx solid var(--border-color); border: 1rpx solid var(--border-color);
/* Use variable */ /* Use variable */
@@ -24,13 +24,6 @@ picker {
min-width: 0; min-width: 0;
} }
.label {
font-size: 22rpx;
color: var(--text-tertiary);
/* Use variable */
flex-shrink: 0;
}
.value { .value {
flex: 1; flex: 1;
min-width: 0; min-width: 0;

View File

@@ -1,14 +1,12 @@
<view class="filter-wrap"> <view class="filter-wrap">
<picker mode="selector" range="{{officeOptions}}" bindchange="handleOfficeChange"> <picker mode="selector" range="{{officeOptions}}" bindchange="handleOfficeChange">
<view class="filter-item"> <view class="filter-item">
<text class="label">机构</text>
<text class="value">{{selectedOffice}}</text> <text class="value">{{selectedOffice}}</text>
<text class="arrow">▾</text> <text class="arrow">▾</text>
</view> </view>
</picker> </picker>
<picker mode="selector" range="{{areaOptions}}" bindchange="handleAreaChange"> <picker mode="selector" range="{{areaOptions}}" bindchange="handleAreaChange">
<view class="filter-item"> <view class="filter-item">
<text class="label">领域</text>
<text class="value">{{selectedArea}}</text> <text class="value">{{selectedArea}}</text>
<text class="arrow">▾</text> <text class="arrow">▾</text>
</view> </view>

View File

@@ -1,27 +1,47 @@
.lawyer-card { .lawyer-card {
display: flex; display: flex;
align-items: center; align-items: flex-start;
background: var(--bg-card); background: var(--bg-card);
border-radius: var(--border-radius-base); border-radius: 18rpx;
padding: var(--spacing-md); padding: var(--spacing-md);
box-shadow: var(--shadow-sm); box-shadow: var(--shadow-base);
position: relative; position: relative;
overflow: hidden; overflow: hidden;
transition: transform 0.1s; transition: transform 0.1s;
border: 1rpx solid rgba(142, 34, 48, 0.06);
} }
.lawyer-card:active { .lawyer-card:active {
transform: scale(0.98); transform: scale(0.98);
} }
.lawyer-card--featured {
padding: 28rpx;
border-radius: 20rpx;
background: linear-gradient(180deg, #fff 0%, #fffaf9 100%);
box-shadow: 0 10rpx 28rpx rgba(26, 26, 26, 0.08);
}
.lawyer-card--compact {
align-items: center;
}
.avatar { .avatar {
width: 100rpx; width: 104rpx;
height: 100rpx; height: 104rpx;
border-radius: 50%; border-radius: 28rpx;
border: 4rpx solid var(--bg-page); border: 4rpx solid #fff;
flex-shrink: 0; flex-shrink: 0;
margin-right: var(--spacing-sm); margin-right: 20rpx;
background: var(--bg-surface); background: var(--bg-surface);
box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.08);
}
.lawyer-card--featured .avatar {
width: 132rpx;
height: 132rpx;
border-radius: 32rpx;
margin-right: 24rpx;
} }
.content { .content {
@@ -29,69 +49,148 @@
min-width: 0; min-width: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: center; gap: 14rpx;
}
.top-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16rpx;
}
.identity-block {
flex: 1;
min-width: 0;
} }
.header-row { .header-row {
display: flex; display: flex;
align-items: center; align-items: center;
margin-bottom: 6rpx; flex-wrap: wrap;
gap: 10rpx;
} }
.name { .name {
font-size: 32rpx; font-size: 32rpx;
font-weight: 600; font-weight: 600;
color: var(--text-main); color: var(--text-main);
margin-right: 12rpx; line-height: 1.2;
}
.lawyer-card--featured .name {
font-size: 40rpx;
} }
.title { .title {
font-size: 22rpx; font-size: 22rpx;
color: var(--primary-color); color: var(--primary-color);
background: rgba(142, 34, 48, 0.08); background: rgba(142, 34, 48, 0.08);
/* Primary opacity */ padding: 6rpx 14rpx;
padding: 2rpx 10rpx; border-radius: 10rpx;
border-radius: 8rpx;
font-weight: 500; font-weight: 500;
line-height: 1;
} }
.office { .lawyer-card--featured .title {
font-size: 24rpx; font-size: 24rpx;
padding: 8rpx 16rpx;
background: rgba(142, 34, 48, 0.1);
}
.contact-row {
display: flex;
flex-wrap: wrap;
gap: 10rpx;
margin-top: 12rpx;
}
.contact-chip {
max-width: 100%;
font-size: 22rpx;
line-height: 1.2;
color: var(--text-secondary);
background: var(--bg-page);
border-radius: 999rpx;
padding: 8rpx 16rpx;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.lawyer-card--featured .contact-chip {
font-size: 24rpx;
padding: 10rpx 18rpx;
background: rgba(255, 255, 255, 0.86);
border: 1rpx solid rgba(142, 34, 48, 0.08);
}
.specialty-block {
display: flex;
flex-direction: column;
gap: 10rpx;
}
.specialty-label {
font-size: 22rpx;
color: var(--text-tertiary); color: var(--text-tertiary);
margin-bottom: 12rpx; line-height: 1;
} }
.tags-row { .tags-row {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 8rpx; gap: 10rpx;
} }
.tag { .tag {
font-size: 20rpx; font-size: 22rpx;
color: var(--text-secondary); color: var(--text-secondary);
background: var(--bg-page); background: var(--bg-page);
padding: 4rpx 12rpx; padding: 8rpx 14rpx;
border-radius: 6rpx; border-radius: 999rpx;
line-height: 1.2;
}
.lawyer-card--featured .tag {
font-size: 22rpx;
color: var(--primary-dark);
background: rgba(142, 34, 48, 0.06);
padding: 8rpx 14rpx;
} }
.tag-more { .tag-more {
font-size: 20rpx; font-size: 22rpx;
color: var(--text-tertiary); color: var(--primary-color);
padding: 4rpx 0; background: rgba(142, 34, 48, 0.08);
padding: 8rpx 14rpx;
border-radius: 999rpx;
line-height: 1.2;
} }
.action-col { .action-col {
margin-left: var(--spacing-md);
display: flex; display: flex;
align-items: center; align-items: center;
flex-shrink: 0;
padding-top: 2rpx;
} }
.consult-btn { .consult-btn {
font-size: 24rpx; font-size: 24rpx;
color: var(--primary-color); color: var(--primary-color);
background: #fff;
border: 1rpx solid var(--primary-color); border: 1rpx solid var(--primary-color);
padding: 6rpx 20rpx; padding: 10rpx 22rpx;
border-radius: 24rpx; border-radius: 999rpx;
font-weight: 500; font-weight: 500;
line-height: 1;
}
.lawyer-card--featured .consult-btn {
font-size: 26rpx;
padding: 14rpx 28rpx;
color: #fff;
background: var(--primary-color);
border: none;
box-shadow: 0 8rpx 18rpx rgba(142, 34, 48, 0.18);
} }

View File

@@ -1,24 +1,44 @@
Component({ Component({
data: { data: {
specialtiesText: '', isFeatured: false,
layoutClass: '',
visibleSpecialties: [] as string[],
moreSpecialtiesCount: 0,
contactItems: [] as string[],
}, },
properties: { properties: {
lawyer: { lawyer: {
type: Object, type: Object,
value: null, value: null,
}, },
showOffice: { layout: {
type: Boolean, type: String,
value: true, value: 'compact',
}, },
}, },
observers: { observers: {
lawyer(lawyer: { specialties?: string[] } | null) { 'lawyer, layout'(lawyer: {
specialties?: string[];
phone?: string;
email?: string;
} | null, layout: string) {
const specialties = const specialties =
lawyer && Array.isArray(lawyer.specialties) ? lawyer.specialties : []; lawyer && Array.isArray(lawyer.specialties) ? lawyer.specialties : [];
const isFeatured = layout === 'featured';
const visibleLimit = isFeatured ? 4 : 3;
const phone = lawyer && typeof lawyer.phone === 'string' ? lawyer.phone.trim() : '';
const email = lawyer && typeof lawyer.email === 'string' ? lawyer.email.trim() : '';
const phoneText = phone ? `电话:${phone}` : '';
const emailText = email ? `邮箱:${email}` : '';
const contactItems = isFeatured
? [phoneText, emailText].filter((item) => Boolean(item)).slice(0, 2)
: [];
this.setData({ this.setData({
specialties, // Expose array for wx:for isFeatured,
specialtiesText: specialties.join(' | '), layoutClass: isFeatured ? 'lawyer-card--featured' : 'lawyer-card--compact',
visibleSpecialties: specialties.slice(0, visibleLimit),
moreSpecialtiesCount: Math.max(0, specialties.length - visibleLimit),
contactItems,
}); });
}, },
}, },

View File

@@ -1,17 +1,16 @@
<view class="lawyer-card" bindtap="handleTap"> <view class="lawyer-card {{layoutClass}}" bindtap="handleTap">
<image class="avatar" src="{{lawyer.avatar}}" mode="aspectFill"></image> <image class="avatar" src="{{lawyer.avatar}}" mode="aspectFill"></image>
<view class="content"> <view class="content">
<view class="top-row">
<view class="identity-block">
<view class="header-row"> <view class="header-row">
<text class="name">{{lawyer.name}}</text> <text class="name">{{lawyer.name}}</text>
<text class="title">{{lawyer.title}}</text> <text class="title" wx:if="{{lawyer.title}}">{{lawyer.title}}</text>
</view> </view>
<text wx:if="{{showOffice}}" class="office">{{lawyer.office}}</text> <view class="contact-row" wx:if="{{contactItems.length}}">
<text class="contact-chip" wx:for="{{contactItems}}" wx:key="*this">{{item}}</text>
<view class="tags-row">
<text class="tag" wx:for="{{specialties}}" wx:key="*this" wx:if="{{index < 3}}">{{item}}</text>
<text class="tag-more" wx:if="{{specialties.length > 3}}">...</text>
</view> </view>
</view> </view>
@@ -19,3 +18,13 @@
<text class="consult-btn">咨询</text> <text class="consult-btn">咨询</text>
</view> </view>
</view> </view>
<view class="specialty-block">
<text class="specialty-label" wx:if="{{isFeatured && visibleSpecialties.length}}">业务方向</text>
<view class="tags-row">
<text class="tag" wx:for="{{visibleSpecialties}}" wx:key="*this">{{item}}</text>
<text class="tag-more" wx:if="{{moreSpecialtiesCount > 0}}">...</text>
</view>
</view>
</view>
</view>

View File

@@ -9,8 +9,8 @@ export interface TenantRuntimeConfig {
// develop 环境允许本地联调trial/release 请替换为已备案且已配置到小程序后台“服务器域名”的 HTTPS 域名。 // develop 环境允许本地联调trial/release 请替换为已备案且已配置到小程序后台“服务器域名”的 HTTPS 域名。
export const tenantRuntimeConfig: TenantRuntimeConfig = { export const tenantRuntimeConfig: TenantRuntimeConfig = {
apiBaseUrlByEnv: { apiBaseUrlByEnv: {
develop: 'http://127.0.0.1:8112', develop: 'https://easyflowtech.cn/card',
trial: 'https://trial-api.example.com', trial: 'https://easyflowtech.cn/card',
release: 'https://api.example.com', release: 'https://easyflowtech.cn/card',
}, },
}; };

View File

@@ -4,13 +4,8 @@
.hero-section { .hero-section {
position: relative; position: relative;
height: 520rpx; height: 440rpx;
width: 100%; width: 100%;
display: flex;
flex-direction: column;
justify-content: flex-end;
padding-bottom: 80rpx;
/* Space for overlap */
} }
.hero-bg { .hero-bg {
@@ -33,60 +28,10 @@
z-index: 1; z-index: 1;
} }
.hero-content {
position: relative;
z-index: 2;
padding: 0 var(--spacing-lg);
display: flex;
flex-direction: column;
margin-bottom: 72rpx;
}
.firm-stats {
display: inline-flex;
align-items: center;
width: fit-content;
padding: 14rpx 22rpx;
border-radius: 20rpx;
border: 1rpx solid rgba(255, 255, 255, 0.32);
background: linear-gradient(120deg, rgba(10, 21, 34, 0.62), rgba(19, 38, 56, 0.36));
box-shadow: 0 10rpx 28rpx rgba(7, 15, 27, 0.35), inset 0 1rpx 0 rgba(255, 255, 255, 0.24);
backdrop-filter: blur(10rpx);
-webkit-backdrop-filter: blur(10rpx);
}
.stat-item {
display: flex;
flex-direction: column;
min-width: 120rpx;
}
.stat-num {
font-size: 44rpx;
font-weight: 700;
color: #fff;
line-height: 1.2;
text-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.35);
}
.stat-label {
font-size: 24rpx;
color: rgba(242, 247, 252, 0.92);
margin-top: 4rpx;
text-shadow: 0 1rpx 8rpx rgba(0, 0, 0, 0.28);
}
.stat-divider {
width: 2rpx;
height: 40rpx;
background: linear-gradient(to bottom, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.52), rgba(255, 255, 255, 0.12));
margin: 0 24rpx;
}
.content-container { .content-container {
position: relative; position: relative;
z-index: 3; z-index: 3;
margin-top: -60rpx; margin-top: -32rpx;
background: var(--bg-page); background: var(--bg-page);
border-radius: 32rpx 32rpx 0 0; border-radius: 32rpx 32rpx 0 0;
padding: var(--spacing-lg) var(--spacing-md); padding: var(--spacing-lg) var(--spacing-md);
@@ -96,7 +41,7 @@
.address-card { .address-card {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; gap: var(--spacing-md);
padding: var(--spacing-md); padding: var(--spacing-md);
margin-bottom: var(--spacing-lg); margin-bottom: var(--spacing-lg);
background: #fff; background: #fff;
@@ -105,8 +50,10 @@
.address-info { .address-info {
display: flex; display: flex;
flex: 1;
flex-direction: column; flex-direction: column;
gap: 8rpx; gap: 8rpx;
min-width: 0;
} }
.address-label { .address-label {
@@ -118,11 +65,15 @@
font-size: 28rpx; font-size: 28rpx;
color: var(--text-main); color: var(--text-main);
font-weight: 500; font-weight: 500;
line-height: 1.5;
word-break: break-all;
} }
.address-icon { .address-icon {
font-size: 32rpx; width: 34rpx;
color: var(--text-tertiary); height: 34rpx;
flex-shrink: 0;
align-self: center;
} }
.section { .section {

View File

@@ -3,42 +3,21 @@
<app-header title="{{firm.name}}" back="{{false}}" background="rgba(255,255,255,0.9)"></app-header> <app-header title="{{firm.name}}" back="{{false}}" background="rgba(255,255,255,0.9)"></app-header>
<scroll-view class="page-content" scroll-y="true" type="list"> <scroll-view class="page-content" scroll-y="true" type="list">
<!-- Hero Section --> <!-- Hero Section -->
<view class="hero-section"> <view class="hero-section">
<image wx:if="{{firm.heroImage}}" class="hero-bg" mode="aspectFill" src="{{firm.heroImage}}"></image> <image wx:if="{{firm.heroImage}}" class="hero-bg" mode="aspectFill" src="{{firm.heroImage}}"></image>
<view wx:if="{{!firm.heroImage}}" class="hero-overlay"></view> <view wx:if="{{!firm.heroImage}}" class="hero-overlay"></view>
<view class="hero-content">
<view class="firm-stats">
<view class="stat-item">
<text class="stat-num">{{firm.officeCount}}</text>
<text class="stat-label">办公机构</text>
</view>
<view class="stat-divider"></view>
<view class="stat-item">
<text class="stat-num">{{firm.lawyerCount}}</text>
<text class="stat-label">专业律师</text>
</view>
</view>
</view>
</view> </view>
<!-- Content Container (Overlapping) --> <!-- Content Container (Overlapping) -->
<view class="content-container"> <view class="content-container">
<!-- Address Card --> <!-- Address Card -->
<view class="card address-card" bindtap="openLocation"> <view class="card address-card" bindtap="openLocation">
<view class="address-info"> <view class="address-info">
<text class="address-label">总部地址</text> <text class="address-label">总部地址</text>
<text class="address-text">{{firm.hqAddress}}</text> <text class="address-text">{{firm.hqAddress}}</text>
</view> </view>
<text class="address-icon">></text> <image class="address-icon" src="/assets/icons/navigate.svg" mode="aspectFit"></image>
</view>
<!-- Intro Section -->
<view class="section">
<view class="section-title">律所简介</view>
<text class="intro-text">{{firm.intro}}</text>
</view> </view>
<!-- Practice Areas --> <!-- Practice Areas -->
@@ -49,6 +28,12 @@
</view> </view>
</view> </view>
<!-- Intro Section -->
<view class="section">
<view class="section-title">律所简介</view>
<text class="intro-text">{{firm.intro}}</text>
</view>
<view class="safe-area-bottom" style="height: 120rpx;"></view> <view class="safe-area-bottom" style="height: 120rpx;"></view>
</view> </view>
</scroll-view> </scroll-view>

View File

@@ -175,12 +175,6 @@
white-space: pre-wrap; white-space: pre-wrap;
} }
.bio-scroll {
height: 360rpx;
box-sizing: border-box;
padding-right: 8rpx;
}
.firm-mini-card { .firm-mini-card {
background: #fff; background: #fff;
padding: var(--spacing-md); padding: var(--spacing-md);
@@ -232,6 +226,16 @@
height: 160rpx; height: 160rpx;
} }
.share-poster-canvas {
position: fixed;
left: -9999px;
top: -9999px;
width: 500px;
height: 400px;
opacity: 0;
pointer-events: none;
}
.not-found-action { .not-found-action {
padding: var(--spacing-lg); padding: var(--spacing-lg);
text-align: center; text-align: center;

View File

@@ -1,7 +1,38 @@
import { getLawyerDetail, recordCardShare } from '../../api/open'; import { getFirmProfile, getLawyerDetail, recordCardShare } from '../../api/open';
import type { FirmInfo } from '../../types/card'; import type { FirmInfo, Lawyer } from '../../types/card';
import type { Lawyer } from '../../types/card';
import { appendCardViewRecord } from '../../utils/history'; import { appendCardViewRecord } from '../../utils/history';
import { generateSharePoster, SHARE_POSTER_CANVAS_ID } from '../../utils/share-poster';
interface DetailPageData {
firm: FirmInfo;
lawyer: Lawyer | null;
notFound: boolean;
specialtiesText: string;
detailBgStyle: string;
loading: boolean;
sharePosterPath: string;
}
interface DetailPageCustom {
handleDockAction(event: WechatMiniprogram.CustomEvent<{ action: string }>): void;
saveContact(): void;
callPhone(): void;
navigateOffice(): void;
previewWechatQr(): void;
goFirmProfile(): void;
goLawyerList(): void;
getSharePosterCanvas(): Promise<WechatMiniprogram.Canvas>;
loadFirmForShare(): Promise<FirmInfo>;
prepareSharePoster(): void;
ensureSharePoster(): Promise<string>;
}
type DetailPageInstance = WechatMiniprogram.Page.Instance<DetailPageData, DetailPageCustom>;
const sharePosterPromiseMap = new WeakMap<DetailPageInstance, Promise<string>>();
const shareFirmPromiseMap = new WeakMap<DetailPageInstance, Promise<FirmInfo>>();
const shareCanvasPromiseMap = new WeakMap<DetailPageInstance, Promise<WechatMiniprogram.Canvas>>();
const pageReadyMap = new WeakMap<DetailPageInstance, boolean>();
function createEmptyFirm(): FirmInfo { function createEmptyFirm(): FirmInfo {
return { return {
@@ -29,29 +60,24 @@ function buildDetailBgStyle(coverImage?: string): string {
return `background-image: url("${cover}"); background-size: cover; background-position: center;`; return `background-image: url("${cover}"); background-size: cover; background-position: center;`;
} }
function shouldUseBioScroll(bio?: string): boolean { Page<DetailPageData, DetailPageCustom>({
const text = typeof bio === 'string' ? bio.trim() : '';
return text.length > 180;
}
Page({
data: { data: {
firm: createEmptyFirm(), firm: createEmptyFirm(),
lawyer: null as Lawyer | null, lawyer: null,
notFound: false, notFound: false,
specialtiesText: '', specialtiesText: '',
detailBgStyle: '', detailBgStyle: '',
bioScrollable: false,
loading: false, loading: false,
sharePosterPath: '',
}, },
async onLoad(options: Record<string, string | undefined>) { async onLoad(options) {
const lawyerId = typeof options.id === 'string' ? options.id : ''; const lawyerId = typeof options.id === 'string' ? options.id : '';
const sourceType = typeof options.sourceType === 'string' ? options.sourceType : 'DIRECT'; const sourceType = typeof options.sourceType === 'string' ? options.sourceType : 'DIRECT';
const shareFromCardId = typeof options.shareFromCardId === 'string' ? options.shareFromCardId : ''; const shareFromCardId = typeof options.shareFromCardId === 'string' ? options.shareFromCardId : '';
if (!lawyerId) { if (!lawyerId) {
this.setData({ notFound: true, specialtiesText: '', detailBgStyle: '', bioScrollable: false }); this.setData({ notFound: true, specialtiesText: '', detailBgStyle: '' });
return; return;
} }
@@ -64,13 +90,13 @@ Page({
notFound: false, notFound: false,
specialtiesText: payload.lawyer.specialties.join(''), specialtiesText: payload.lawyer.specialties.join(''),
detailBgStyle: buildDetailBgStyle(payload.lawyer.coverImage), detailBgStyle: buildDetailBgStyle(payload.lawyer.coverImage),
bioScrollable: shouldUseBioScroll(payload.lawyer.bio),
}); });
appendCardViewRecord(payload.lawyer); appendCardViewRecord(payload.lawyer);
wx.showShareMenu({ menus: ['shareAppMessage'] }); wx.showShareMenu({ menus: ['shareAppMessage'] });
this.prepareSharePoster();
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : '律师信息不存在'; const message = error instanceof Error ? error.message : '律师信息不存在';
this.setData({ notFound: true, specialtiesText: '', detailBgStyle: '', bioScrollable: false }); this.setData({ notFound: true, specialtiesText: '', detailBgStyle: '' });
wx.showToast({ wx.showToast({
title: message, title: message,
icon: 'none', icon: 'none',
@@ -80,9 +106,24 @@ Page({
} }
}, },
handleDockAction(event: WechatMiniprogram.CustomEvent<{ action: string }>) { onReady() {
pageReadyMap.set(this, true);
this.prepareSharePoster();
},
onUnload() {
pageReadyMap.delete(this);
sharePosterPromiseMap.delete(this);
shareFirmPromiseMap.delete(this);
shareCanvasPromiseMap.delete(this);
},
handleDockAction(event) {
const action = event.detail.action; const action = event.detail.action;
switch (action) { switch (action) {
case 'home':
this.goFirmProfile();
break;
case 'save': case 'save':
this.saveContact(); this.saveContact();
break; break;
@@ -137,6 +178,7 @@ Page({
wx.showToast({ title: '暂未配置地图位置', icon: 'none' }); wx.showToast({ title: '暂未配置地图位置', icon: 'none' });
return; return;
} }
wx.openLocation({ wx.openLocation({
latitude: this.data.firm.hqLatitude, latitude: this.data.firm.hqLatitude,
longitude: this.data.firm.hqLongitude, longitude: this.data.firm.hqLongitude,
@@ -155,21 +197,166 @@ Page({
wx.showToast({ title: '二维码未配置', icon: 'none' }); wx.showToast({ title: '二维码未配置', icon: 'none' });
return; return;
} }
wx.previewImage({ wx.previewImage({
current: url, current: url,
urls: [url], urls: [url],
}); });
}, },
goFirmProfile() {
wx.navigateTo({ url: '/pages/firm/index' });
},
goLawyerList() { goLawyerList() {
wx.navigateTo({ url: '/pages/lawyer-list/index' }); wx.navigateTo({ url: '/pages/lawyer-list/index' });
}, },
onShareAppMessage() { async getSharePosterCanvas() {
const cachedPromise = shareCanvasPromiseMap.get(this);
if (cachedPromise) {
return cachedPromise;
}
const canvasPromise = new Promise<WechatMiniprogram.Canvas>((resolve, reject) => {
const query = wx.createSelectorQuery();
query
.in(this)
.select(`#${SHARE_POSTER_CANVAS_ID}`)
.node((result) => {
const canvas = result && 'node' in result ? (result.node as WechatMiniprogram.Canvas | undefined) : undefined;
if (canvas) {
resolve(canvas);
return;
}
reject(new Error('分享海报画布未就绪'));
})
.exec();
}).then(
(canvas) => {
shareCanvasPromiseMap.delete(this);
return canvas;
},
(error: unknown) => {
shareCanvasPromiseMap.delete(this);
throw error;
}
);
shareCanvasPromiseMap.set(this, canvasPromise);
return canvasPromise;
},
async loadFirmForShare() {
const cachedPromise = shareFirmPromiseMap.get(this);
if (cachedPromise) {
return cachedPromise;
}
const currentFirm = this.data.firm;
if (currentFirm.logo) {
return currentFirm;
}
const firmPromise = getFirmProfile()
.then((firmProfile) => ({
...currentFirm,
...firmProfile,
name: firmProfile.name || currentFirm.name,
hqAddress: currentFirm.hqAddress || firmProfile.hqAddress,
}))
.catch(() => currentFirm);
const firmPromiseWithCleanup = firmPromise.then(
(result) => {
shareFirmPromiseMap.delete(this);
return result;
},
(error: unknown) => {
shareFirmPromiseMap.delete(this);
throw error;
}
);
shareFirmPromiseMap.set(this, firmPromiseWithCleanup);
return firmPromiseWithCleanup;
},
prepareSharePoster() {
if (!pageReadyMap.get(this) || !this.data.lawyer || this.data.notFound) {
return;
}
this.ensureSharePoster().catch(() => {
// 海报生成失败时使用默认头像兜底
});
},
async ensureSharePoster() {
if (this.data.sharePosterPath) {
return this.data.sharePosterPath;
}
const currentPromise = sharePosterPromiseMap.get(this);
if (currentPromise) {
return currentPromise;
}
const lawyer = this.data.lawyer; const lawyer = this.data.lawyer;
if (!lawyer) {
throw new Error('名片数据未就绪');
}
const posterPromise = this.loadFirmForShare()
.then((firm) =>
this.getSharePosterCanvas().then((canvas) =>
generateSharePoster({
canvas,
firm: {
name: firm.name,
logo: firm.logo,
hqAddress: firm.hqAddress,
},
lawyer: {
name: lawyer.name,
title: lawyer.title,
office: lawyer.office,
phone: lawyer.phone,
email: lawyer.email,
address: lawyer.address,
avatar: lawyer.avatar,
},
})
)
)
.then((posterPath) => {
if (posterPath) {
this.setData({ sharePosterPath: posterPath });
}
return posterPath;
});
const posterPromiseWithCleanup = posterPromise.then(
(result) => {
sharePosterPromiseMap.delete(this);
return result;
},
(error: unknown) => {
sharePosterPromiseMap.delete(this);
throw error;
}
);
sharePosterPromiseMap.set(this, posterPromiseWithCleanup);
return posterPromiseWithCleanup;
},
onShareAppMessage() {
const lawyer = this.data.lawyer;
const firmName = this.data.firm.name || '电子名片';
if (!lawyer) { if (!lawyer) {
return { return {
title: `${this.data.firm.name || '电子名片'}电子名片`, title: firmName,
path: '/pages/firm/index', path: '/pages/firm/index',
}; };
} }
@@ -179,10 +366,33 @@ Page({
// 分享埋点失败不阻断分享动作 // 分享埋点失败不阻断分享动作
}); });
const title = firmName;
const fallbackImage = lawyer.avatar;
if (this.data.sharePosterPath) {
return { return {
title: `${lawyer.name}律师电子名片`, title,
path: sharePath, path: sharePath,
imageUrl: lawyer.avatar, imageUrl: this.data.sharePosterPath,
};
}
const promise = this.ensureSharePoster()
.then((posterPath) => ({
title,
path: sharePath,
imageUrl: posterPath || fallbackImage,
}))
.catch(() => ({
title,
path: sharePath,
imageUrl: fallbackImage,
}));
return {
title,
path: sharePath,
imageUrl: fallbackImage,
promise,
}; };
}, },
}); });

View File

@@ -61,10 +61,7 @@
<!-- Bio --> <!-- Bio -->
<view class="section-card"> <view class="section-card">
<view class="section-header">个人简介</view> <view class="section-header">个人简介</view>
<scroll-view wx:if="{{bioScrollable}}" class="bio-scroll" scroll-y="true" show-scrollbar="true">
<view class="bio-text">{{lawyer.bio}}</view> <view class="bio-text">{{lawyer.bio}}</view>
</scroll-view>
<view wx:else class="bio-text">{{lawyer.bio}}</view>
</view> </view>
@@ -73,6 +70,15 @@
</view> </view>
</scroll-view> </scroll-view>
<canvas
id="sharePosterCanvas"
class="share-poster-canvas"
canvas-id="sharePosterCanvas"
disable-scroll="true"
type="2d"
style="width: 500px; height: 400px;"
></canvas>
<!-- Fixed Action Dock --> <!-- Fixed Action Dock -->
<action-dock bind:action="handleDockAction"></action-dock> <action-dock bind:action="handleDockAction"></action-dock>
</block> </block>

View File

@@ -44,73 +44,14 @@
color: var(--text-placeholder); color: var(--text-placeholder);
} }
.quick-actions {
display: flex;
gap: var(--spacing-md);
padding: 0 var(--spacing-md) var(--spacing-md);
}
.action-btn {
flex: 1;
height: 80rpx;
border-radius: var(--border-radius-base);
display: flex;
align-items: center;
justify-content: center;
font-size: 28rpx;
font-weight: 500;
transition: opacity 0.2s;
}
.action-btn:active {
opacity: 0.8;
}
.hotline-btn {
background: rgba(142, 34, 48, 0.06);
/* Burgundy tint */
color: var(--primary-color);
}
.map-btn {
background: #fff;
color: var(--text-secondary);
border: 1rpx solid var(--border-color);
}
.list-wrap { .list-wrap {
padding: 0 var(--spacing-md); padding: 0 var(--spacing-md);
} }
.card-item { .card-item {
margin-bottom: var(--spacing-md); margin-bottom: 20rpx;
background: #fff;
/* Ensure card background is white */
border-radius: var(--border-radius-base);
} }
.list-bottom-space { .list-bottom-space {
height: 120rpx; height: 120rpx;
} }
/* History Floating Action Button styling */
.history-fab {
position: fixed;
right: var(--spacing-md);
bottom: calc(var(--spacing-lg) + env(safe-area-inset-bottom));
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(10px);
padding: 16rpx 32rpx;
border-radius: 40rpx;
box-shadow: var(--shadow-lg);
display: flex;
align-items: center;
z-index: 20;
border: 1rpx solid var(--border-color);
}
.history-text {
font-size: 26rpx;
color: var(--text-main);
font-weight: 500;
}

View File

@@ -8,17 +8,12 @@ let searchDebounceTimer: number | null = null;
Page({ Page({
data: { data: {
firmName: '',
firmAddress: '',
firmLatitude: 0,
firmLongitude: 0,
keyword: '', keyword: '',
selectedOffice: ALL_OFFICES, selectedOffice: ALL_OFFICES,
selectedArea: ALL_AREAS, selectedArea: ALL_AREAS,
officeOptions: [ALL_OFFICES], officeOptions: [ALL_OFFICES],
areaOptions: [ALL_AREAS], areaOptions: [ALL_AREAS],
filteredLawyers: [] as Lawyer[], filteredLawyers: [] as Lawyer[],
hotlinePhone: '',
loading: false, loading: false,
}, },
@@ -31,11 +26,6 @@ Page({
try { try {
const firm = await getFirmProfile(); const firm = await getFirmProfile();
this.setData({ this.setData({
firmName: firm.name,
firmAddress: firm.hqAddress,
firmLatitude: firm.hqLatitude,
firmLongitude: firm.hqLongitude,
hotlinePhone: firm.hotlinePhone,
officeOptions: [ALL_OFFICES, ...firm.officeList], officeOptions: [ALL_OFFICES, ...firm.officeList],
areaOptions: [ALL_AREAS, ...firm.practiceAreas], areaOptions: [ALL_AREAS, ...firm.practiceAreas],
}); });
@@ -68,6 +58,14 @@ Page({
}, 250) as unknown as number; }, 250) as unknown as number;
}, },
onSearchConfirm() {
if (searchDebounceTimer !== null) {
clearTimeout(searchDebounceTimer);
searchDebounceTimer = null;
}
this.loadLawyers();
},
handleOfficeChange(event: WechatMiniprogram.CustomEvent<{ value: string }>) { handleOfficeChange(event: WechatMiniprogram.CustomEvent<{ value: string }>) {
this.setData({ selectedOffice: event.detail.value }); this.setData({ selectedOffice: event.detail.value });
this.loadLawyers(); this.loadLawyers();
@@ -104,44 +102,4 @@ Page({
url: `/pages/lawyer-detail/index?id=${lawyerId}`, url: `/pages/lawyer-detail/index?id=${lawyerId}`,
}); });
}, },
callHotline() {
if (!this.data.hotlinePhone) {
wx.showToast({
title: '暂无联系电话',
icon: 'none',
});
return;
}
wx.makePhoneCall({
phoneNumber: this.data.hotlinePhone,
fail: () => {
wx.showToast({ title: '拨号失败', icon: 'none' });
},
});
},
openOffice() {
if (!this.data.firmLatitude || !this.data.firmLongitude) {
wx.showToast({ title: '暂未配置地图位置', icon: 'none' });
return;
}
wx.openLocation({
latitude: this.data.firmLatitude,
longitude: this.data.firmLongitude,
name: this.data.firmName,
address: this.data.firmAddress,
scale: 18,
fail: () => {
wx.showToast({ title: '打开地图失败', icon: 'none' });
},
});
},
goHistory() {
wx.navigateTo({
url: '/pages/history/index',
});
},
}); });

View File

@@ -12,6 +12,8 @@
placeholder="搜索律师姓名、专业领域..." placeholder="搜索律师姓名、专业领域..."
value="{{keyword}}" value="{{keyword}}"
bindinput="onSearchInput" bindinput="onSearchInput"
bindconfirm="onSearchConfirm"
confirm-type="search"
/> />
</view> </view>
</view> </view>
@@ -26,21 +28,11 @@
></filter-bar> ></filter-bar>
</view> </view>
<view class="quick-actions">
<view class="action-btn hotline-btn" bindtap="callHotline">
<image class="action-icon" src="/assets/icons/phone.svg" mode="aspectFit" wx:if="{{false}}"></image> <!-- Placeholder for icon -->
<text>联系电话</text>
</view>
<view class="action-btn map-btn" bindtap="openOffice">
<text>总部导航</text>
</view>
</view>
<scroll-view class="page-content list-scroll" scroll-y="true" type="list"> <scroll-view class="page-content list-scroll" scroll-y="true" type="list">
<view class="list-wrap"> <view class="list-wrap">
<block wx:if="{{filteredLawyers.length}}"> <block wx:if="{{filteredLawyers.length}}">
<view class="card-item" wx:for="{{filteredLawyers}}" wx:key="id" wx:for-item="item"> <view class="card-item" wx:for="{{filteredLawyers}}" wx:key="id" wx:for-item="item">
<lawyer-card lawyer="{{item}}" bind:select="handleLawyerSelect"></lawyer-card> <lawyer-card lawyer="{{item}}" layout="featured" bind:select="handleLawyerSelect"></lawyer-card>
</view> </view>
</block> </block>
<block wx:else> <block wx:else>
@@ -49,8 +41,4 @@
<view class="list-bottom-space"></view> <view class="list-bottom-space"></view>
</view> </view>
</scroll-view> </scroll-view>
<view class="history-fab" bindtap="goHistory">
<text class="history-text">浏览记录</text>
</view>
</view> </view>

View File

@@ -0,0 +1,477 @@
import type { FirmInfo, Lawyer } from '../types/card';
const POSTER_WIDTH = 500;
const POSTER_HEIGHT = 400;
const EXPORT_SCALE = 2;
const EXPORT_WIDTH = POSTER_WIDTH * EXPORT_SCALE;
const EXPORT_HEIGHT = POSTER_HEIGHT * EXPORT_SCALE;
const BACKGROUND_COLOR = '#f4f0ee';
const PRIMARY_COLOR = '#8E2230';
const PRIMARY_DARK = '#5C0D15';
const TEXT_MAIN = '#1A1A1A';
type CanvasNode = WechatMiniprogram.Canvas;
type Canvas2DContext = any;
type CanvasImage = any;
export const SHARE_POSTER_CANVAS_ID = 'sharePosterCanvas';
export interface SharePosterPayload {
canvas: CanvasNode;
firm: Pick<FirmInfo, 'name' | 'logo' | 'hqAddress'>;
lawyer: Pick<Lawyer, 'name' | 'title' | 'office' | 'phone' | 'email' | 'address' | 'avatar'>;
}
interface PosterAssets {
avatarImage: CanvasImage | null;
logoImage: CanvasImage | null;
}
interface ContactRow {
kind: 'phone' | 'email' | 'address';
value: string;
maxLines: number;
}
interface MultilineTextOptions {
x: number;
y: number;
maxWidth: number;
lineHeight: number;
maxLines: number;
color: string;
font: string;
}
function normalizeText(value: string | undefined | null): string {
return typeof value === 'string' ? value.trim() : '';
}
function buildBrandInitial(name: string): string {
const normalizedName = normalizeText(name);
return normalizedName ? normalizedName.slice(0, 1) : '律';
}
function buildContactRows(payload: SharePosterPayload): ContactRow[] {
const rows: ContactRow[] = [];
const phone = normalizeText(payload.lawyer.phone);
const email = normalizeText(payload.lawyer.email);
const address = normalizeText(payload.lawyer.address) || normalizeText(payload.firm.hqAddress);
if (phone) {
rows.push({ kind: 'phone', value: phone, maxLines: 1 });
}
if (email) {
rows.push({ kind: 'email', value: email, maxLines: 1 });
}
if (address) {
rows.push({ kind: 'address', value: address, maxLines: 2 });
}
return rows;
}
function getImageInfo(src: string): Promise<string> {
const normalizedSrc = normalizeText(src);
if (!normalizedSrc) {
return Promise.resolve('');
}
return new Promise((resolve) => {
wx.getImageInfo({
src: normalizedSrc,
success: (result) => {
resolve(result.path || normalizedSrc);
},
fail: () => {
resolve('');
},
});
});
}
function loadCanvasImage(canvas: CanvasNode, src: string): Promise<CanvasImage | null> {
const normalizedSrc = normalizeText(src);
if (!normalizedSrc) {
return Promise.resolve(null);
}
return new Promise((resolve) => {
const image = canvas.createImage();
image.onload = () => resolve(image);
image.onerror = () => resolve(null);
image.src = normalizedSrc;
});
}
async function preloadAssets(payload: SharePosterPayload): Promise<PosterAssets> {
const [avatarPath, logoPath] = await Promise.all([
getImageInfo(payload.lawyer.avatar),
getImageInfo(payload.firm.logo),
]);
const [avatarImage, logoImage] = await Promise.all([
loadCanvasImage(payload.canvas, avatarPath),
loadCanvasImage(payload.canvas, logoPath),
]);
return {
avatarImage,
logoImage,
};
}
function createRoundedRectPath(
ctx: Canvas2DContext,
x: number,
y: number,
width: number,
height: number,
radius: number
) {
const safeRadius = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + safeRadius, y);
ctx.lineTo(x + width - safeRadius, y);
ctx.arcTo(x + width, y, x + width, y + safeRadius, safeRadius);
ctx.lineTo(x + width, y + height - safeRadius);
ctx.arcTo(x + width, y + height, x + width - safeRadius, y + height, safeRadius);
ctx.lineTo(x + safeRadius, y + height);
ctx.arcTo(x, y + height, x, y + height - safeRadius, safeRadius);
ctx.lineTo(x, y + safeRadius);
ctx.arcTo(x, y, x + safeRadius, y, safeRadius);
ctx.closePath();
}
function fillRoundedRect(
ctx: Canvas2DContext,
x: number,
y: number,
width: number,
height: number,
radius: number,
color: string
) {
createRoundedRectPath(ctx, x, y, width, height, radius);
ctx.fillStyle = color;
ctx.fill();
}
function clipRoundedImage(
ctx: Canvas2DContext,
image: CanvasImage,
x: number,
y: number,
width: number,
height: number,
radius: number
) {
ctx.save();
createRoundedRectPath(ctx, x, y, width, height, radius);
ctx.clip();
ctx.drawImage(image, x, y, width, height);
ctx.restore();
}
function drawPhoneIcon(ctx: Canvas2DContext, x: number, y: number) {
ctx.save();
ctx.strokeStyle = PRIMARY_DARK;
ctx.lineWidth = 1.8;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(x + 5, y + 8);
ctx.quadraticCurveTo(x + 4, y + 10, x + 6, y + 13);
ctx.lineTo(x + 9, y + 16);
ctx.quadraticCurveTo(x + 11, y + 18, x + 13, y + 17);
ctx.lineTo(x + 15, y + 15);
ctx.quadraticCurveTo(x + 16.5, y + 13.5, x + 15.5, y + 12);
ctx.lineTo(x + 13.5, y + 10);
ctx.quadraticCurveTo(x + 12, y + 8.5, x + 10.5, y + 9.5);
ctx.lineTo(x + 9.5, y + 10.5);
ctx.quadraticCurveTo(x + 8.5, y + 11.5, x + 7.5, y + 10.5);
ctx.lineTo(x + 6.5, y + 9.5);
ctx.quadraticCurveTo(x + 5.5, y + 8.5, x + 6.5, y + 7.5);
ctx.lineTo(x + 7.5, y + 6.5);
ctx.quadraticCurveTo(x + 8.5, y + 5, x + 7, y + 3.5);
ctx.lineTo(x + 5, y + 1.5);
ctx.quadraticCurveTo(x + 3.5, y, x + 2.5, y + 2);
ctx.lineTo(x + 1.5, y + 4);
ctx.quadraticCurveTo(x + 0.5, y + 6, x + 2.5, y + 7.5);
ctx.stroke();
ctx.restore();
}
function drawEmailIcon(ctx: Canvas2DContext, x: number, y: number) {
ctx.save();
ctx.strokeStyle = PRIMARY_DARK;
ctx.lineWidth = 1.6;
ctx.lineJoin = 'round';
createRoundedRectPath(ctx, x + 1, y + 3, 18, 14, 4);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x + 3.5, y + 5.5);
ctx.lineTo(x + 10, y + 11);
ctx.lineTo(x + 16.5, y + 5.5);
ctx.stroke();
ctx.restore();
}
function drawAddressIcon(ctx: Canvas2DContext, x: number, y: number) {
ctx.save();
ctx.strokeStyle = PRIMARY_DARK;
ctx.lineWidth = 1.6;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(x + 10, y + 18);
ctx.bezierCurveTo(x + 15, y + 12.5, x + 17, y + 9.5, x + 17, y + 7);
ctx.arc(x + 10, y + 7, 7, 0, Math.PI, true);
ctx.bezierCurveTo(x + 3, y + 9.5, x + 5, y + 12.5, x + 10, y + 18);
ctx.stroke();
ctx.beginPath();
ctx.arc(x + 10, y + 7, 2.3, 0, Math.PI * 2);
ctx.stroke();
ctx.restore();
}
function drawContactIcon(ctx: Canvas2DContext, kind: ContactRow['kind'], x: number, y: number) {
fillRoundedRect(ctx, x, y, 28, 28, 14, 'rgba(142,34,48,0.07)');
if (kind === 'phone') {
drawPhoneIcon(ctx, x + 6, y + 5);
return;
}
if (kind === 'email') {
drawEmailIcon(ctx, x + 4, y + 4);
return;
}
drawAddressIcon(ctx, x + 4, y + 4);
}
function buildWrappedLines(
ctx: Canvas2DContext,
text: string,
maxWidth: number,
maxLines: number
): { lines: string[]; truncated: boolean } {
const normalizedText = normalizeText(text);
if (!normalizedText) {
return { lines: [], truncated: false };
}
const paragraphs = normalizedText.split(/\n+/).filter(Boolean);
const lines: string[] = [];
let truncated = false;
for (let paragraphIndex = 0; paragraphIndex < paragraphs.length; paragraphIndex += 1) {
const paragraph = paragraphs[paragraphIndex];
let currentLine = '';
for (let index = 0; index < paragraph.length; index += 1) {
const nextLine = `${currentLine}${paragraph[index]}`;
if (ctx.measureText(nextLine).width <= maxWidth) {
currentLine = nextLine;
continue;
}
if (currentLine) {
lines.push(currentLine);
}
currentLine = paragraph[index];
if (lines.length >= maxLines) {
truncated = true;
break;
}
}
if (lines.length >= maxLines) {
truncated = true;
break;
}
if (currentLine) {
lines.push(currentLine);
}
}
const finalLines = lines.slice(0, maxLines);
if (truncated && finalLines.length > 0) {
let lastLine = finalLines[finalLines.length - 1];
while (lastLine && ctx.measureText(`${lastLine}...`).width > maxWidth) {
lastLine = lastLine.slice(0, -1);
}
finalLines[finalLines.length - 1] = `${lastLine}...`;
}
return { lines: finalLines, truncated };
}
function drawMultilineText(
ctx: Canvas2DContext,
text: string,
options: MultilineTextOptions
): number {
const normalizedText = normalizeText(text);
if (!normalizedText) {
return 0;
}
ctx.fillStyle = options.color;
ctx.font = options.font;
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
const { lines: finalLines } = buildWrappedLines(ctx, normalizedText, options.maxWidth, options.maxLines);
finalLines.forEach((line, index) => {
ctx.fillText(line, options.x, options.y + index * options.lineHeight);
});
return finalLines.length * options.lineHeight;
}
function drawBackground(ctx: Canvas2DContext) {
const gradient = ctx.createLinearGradient(0, 0, POSTER_WIDTH, POSTER_HEIGHT);
gradient.addColorStop(0, '#fbf8f6');
gradient.addColorStop(1, BACKGROUND_COLOR);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, POSTER_WIDTH, POSTER_HEIGHT);
ctx.save();
ctx.globalAlpha = 0.14;
const ribbonGradient = ctx.createLinearGradient(80, 0, 360, 240);
ribbonGradient.addColorStop(0, '#c9929b');
ribbonGradient.addColorStop(1, '#8E2230');
ctx.fillStyle = ribbonGradient;
ctx.beginPath();
ctx.moveTo(220, 0);
ctx.lineTo(POSTER_WIDTH, 0);
ctx.lineTo(POSTER_WIDTH, 180);
ctx.lineTo(340, 280);
ctx.closePath();
ctx.fill();
ctx.restore();
ctx.save();
ctx.globalAlpha = 0.08;
ctx.fillStyle = PRIMARY_DARK;
ctx.beginPath();
ctx.moveTo(0, 220);
ctx.lineTo(110, 150);
ctx.lineTo(180, 190);
ctx.lineTo(0, 340);
ctx.closePath();
ctx.fill();
ctx.restore();
}
function drawHeaderSection(ctx: Canvas2DContext, payload: SharePosterPayload, assets: PosterAssets): number {
const avatarX = 46;
const avatarY = 62;
const avatarSize = 108;
if (assets.avatarImage) {
clipRoundedImage(ctx, assets.avatarImage, avatarX, avatarY, avatarSize, avatarSize, 20);
} else {
fillRoundedRect(ctx, avatarX, avatarY, avatarSize, avatarSize, 20, 'rgba(142,34,48,0.12)');
ctx.fillStyle = PRIMARY_COLOR;
ctx.font = '600 28px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(buildBrandInitial(payload.lawyer.name), avatarX + avatarSize / 2, avatarY + avatarSize / 2);
}
const infoX = 176;
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillStyle = TEXT_MAIN;
ctx.font = '600 35px sans-serif';
ctx.fillText(payload.lawyer.name || '未命名律师', infoX, 80);
ctx.fillStyle = PRIMARY_COLOR;
ctx.font = '600 20px sans-serif';
ctx.fillText(payload.lawyer.title || '律师', infoX, 128);
return 226;
}
function drawContactRows(ctx: Canvas2DContext, rows: ContactRow[], startY: number): number {
let currentY = startY;
rows.forEach((row, index) => {
ctx.save();
if (index > 0) {
ctx.strokeStyle = 'rgba(142,34,48,0.08)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(96, currentY - 12);
ctx.lineTo(430, currentY - 12);
ctx.stroke();
}
drawContactIcon(ctx, row.kind, 52, currentY - 3);
const usedHeight = drawMultilineText(ctx, row.value, {
x: 98,
y: currentY - 1,
maxWidth: 334,
lineHeight: row.maxLines > 1 ? 24 : 22,
maxLines: row.maxLines,
color: TEXT_MAIN,
font: row.maxLines > 1 ? '500 16px sans-serif' : '600 18px sans-serif',
});
currentY += Math.max(usedHeight, 30) + 18;
ctx.restore();
});
return currentY;
}
function drawPoster(ctx: Canvas2DContext, payload: SharePosterPayload, assets: PosterAssets) {
drawBackground(ctx);
const contactRows = buildContactRows(payload);
const contactStartY = 234;
drawHeaderSection(ctx, payload, assets);
drawContactRows(ctx, contactRows, contactStartY);
}
function configureCanvas(canvas: CanvasNode): Canvas2DContext {
const context = canvas.getContext('2d') as Canvas2DContext;
canvas.width = EXPORT_WIDTH;
canvas.height = EXPORT_HEIGHT;
if (typeof context.setTransform === 'function') {
context.setTransform(1, 0, 0, 1, 0, 0);
}
context.clearRect(0, 0, EXPORT_WIDTH, EXPORT_HEIGHT);
context.scale(EXPORT_SCALE, EXPORT_SCALE);
return context;
}
function exportCanvas(canvas: CanvasNode): Promise<string> {
return new Promise((resolve, reject) => {
wx.canvasToTempFilePath({
canvas,
x: 0,
y: 0,
width: POSTER_WIDTH,
height: POSTER_HEIGHT,
destWidth: EXPORT_WIDTH,
destHeight: EXPORT_HEIGHT,
fileType: 'jpg',
quality: 0.92,
success: (result) => {
resolve(result.tempFilePath);
},
fail: () => {
reject(new Error('分享海报导出失败'));
},
});
});
}
export async function generateSharePoster(payload: SharePosterPayload): Promise<string> {
const ctx = configureCanvas(payload.canvas);
const assets = await preloadAssets(payload);
drawPoster(ctx, payload, assets);
return exportCanvas(payload.canvas);
}