<template>
	<view class="contract-page">
		<view class="contract-list" v-if="contractList.length">
			<view
				class="contract-card"
				v-for="item in contractList"
				:key="item.id"
				@click="viewContract(item)"
			>
				<text class="contract-name">{{ item.contractName }}</text>
				<text class="contract-meta">签定时间：{{ item.signTime || '-' }}</text>
				<text class="contract-meta">签订人：{{ item.signerName || '-' }}</text>
			</view>
		</view>

		<view class="empty" v-else-if="!loading">
			{{ errorText || '暂无合同' }}
		</view>
	</view>
</template>

<script>
import { baseUrl } from '@/common/config.js'
import { getContractRecords } from '@/api/workbench.js'
import {
	getUserIdFromSessionStorage,
	normalizeContractRecords,
	resolveContractFileUrl,
} from './contractRecords.js'

export default {
	data() {
		return {
			contractList: [],
			loading: false,
			errorText: '',
		}
	},
	onShow() {
		this.loadList()
	},
	methods: {
		getBrowserStorageUserId() {
			// #ifdef H5
			if (typeof window !== 'undefined') {
				return (
					getUserIdFromSessionStorage(window.sessionStorage) ||
					getUserIdFromSessionStorage(window.localStorage)
				)
			}
			// #endif
			return ''
		},
		getUserId() {
			return this.getBrowserStorageUserId() || uni.getStorageSync('userId')
		},
		loadList() {
			this.contractList = MOCK_CONTRACT_LIST

			// 接口就绪后替换
			getContractRecords({
				userId: uni.getStorageSync('userId'),
			}).then(res => {
				console.log(res)
				if (res.data.code == 200) {
					this.contractList = res.data.data.file.map(item => ({
						signerName: res.data.data.signerName,
						signTime: res.data.data.signTime,
						merchantId: res.data.data.merchantId,
						contractName: item.contractName,
						fileUrl: item.fileUrl,
						id: item.id,
					}))
				}
			})
		},
		viewContract(item) {
			const str = uni.$u.queryParams({
				id: item.id,
				title: item.contractName,
				fileType: item.fileUrl.split('.').pop(),
				fileUrl: encodeURIComponent(item.fileUrl),
			})
			
			uni.navigateTo({ url: `/workbench/contract/detail${str}` })
		},
	},
}
</script>

<style lang="scss" scoped>
.contract-page {
	min-height: 100vh;
	background: #f5f5f5;
	padding: 16rpx;
	box-sizing: border-box;
}

.contract-list {
	display: flex;
	flex-direction: column;
}

.contract-card {
	background: #ffffff;
	border-radius: 8rpx;
	padding: 24rpx;
	margin-bottom: 16rpx;
	box-sizing: border-box;
}

.contract-name {
	display: block;
	font-size: 28rpx;
	color: #1d2129;
	font-weight: 600;
	line-height: 40rpx;
	margin-bottom: 18rpx;
}

.contract-meta {
	display: block;
	font-size: 24rpx;
	color: #4e5969;
	line-height: 38rpx;
}

.empty {
	text-align: center;
	padding-top: 72rpx;
	font-size: 28rpx;
	color: #999999;
}
</style>
