<template>
	<view class="page">
		<!-- 驳回原因提示 -->
		<view v-if="info.status === 2 && info.reject_reason" class="reject-tip">
			<u-icon name="warning-fill" size="20" color="#fa8c16" />
			<text class="reject-text">驳回原因：{{ info.reject_reason }}</text>
		</view>

		<!-- 基本信息 -->
		<view class="section">
			<view class="section-title">
				<u-icon name="account-fill" size="18" color="#0e63e3" />
				<text>基本信息</text>
			</view>
			<view class="form-group">
				<text class="form-label">姓名</text>
				<view class="readonly-input">{{ info.name }}</view>
			</view>
			<view class="form-group">
				<text class="form-label">身份证号</text>
				<view class="readonly-input">{{ maskedIdCard }}</view>
			</view>
			<view class="form-group">
				<text class="form-label">手机号</text>
				<view class="readonly-input">{{ maskedPhone }}</view>
			</view>
			<view class="form-group" v-if="info.gender">
				<text class="form-label">性别</text>
				<view class="readonly-input">{{ info.gender }}</view>
			</view>
			<view class="form-group" v-else>
				<text class="form-label">性别</text>
				<view class="gender-row">
					<view class="gender-item" :class="{ active: form.gender === '男' }" @tap="form.gender = '男'">男</view>
					<view class="gender-item" :class="{ active: form.gender === '女' }" @tap="form.gender = '女'">女</view>
				</view>
			</view>
			<view class="form-group">
				<text class="form-label">联系地址</text>
				<view class="region-row" @tap="showRegionPicker = true">
					<text :class="['region-text', regionText ? '' : 'placeholder']">{{ regionText || '请选择省/市/区' }}</text>
					<text class="arrow">›</text>
				</view>
				<u-input v-model="form.address" placeholder="详细街道地址" border="surround"
					:customStyle="{ marginTop: '16rpx' }" />
			</view>
			<view class="form-group">
				<text class="form-label">紧急联系人（选填）</text>
				<view class="contact-row">
					<view class="contact-input">
						<u-input v-model="form.emergency_contact" placeholder="联系人姓名" border="surround" />
					</view>
					<view class="contact-input">
						<u-input v-model="form.emergency_phone" type="number" placeholder="联系人电话" border="surround" maxlength="11" />
					</view>
				</view>
			</view>
		</view>

		<!-- 资料上传 -->
		<view class="section">
			<view class="section-title">
				<u-icon name="attach" size="18" color="#fa8c16" />
				<text>资料上传</text>
			</view>
			<view class="upload-tip">请上传您的检查报告单或出院诊断证明书，上传图片请尽量平整清晰。可上传多张。</view>
			<view class="upload-row">
				<view class="upload-item" v-for="(doc, idx) in form.documents" :key="idx">
					<image class="upload-img" :src="doc" mode="aspectFill" @tap="previewImage(idx)" />
					<view class="upload-del" @tap="form.documents.splice(idx, 1)">×</view>
				</view>
				<view class="upload-box" @tap="chooseDocument">
					<text class="upload-icon">+</text>
					<text class="upload-text">上传图片</text>
				</view>
			</view>
		</view>

		<!-- 授权签名 -->
		<view class="section">
			<view class="section-title">
				<u-icon name="edit-pen-fill" size="18" color="#52c41a" />
				<text>授权签名</text>
			</view>
			<view class="sign-item">
				<view class="sign-left">
					<text class="sign-name">个人可支配收入声明</text>
					<text :class="['sign-status', signedIncome ? 'signed' : '']">{{ signedIncome ? '已签署' : '未签署' }}</text>
				</view>
				<view class="sign-btns" v-if="signedIncome">
					<view class="sign-btn view" @tap="previewSign('income')">查看</view>
					<view class="sign-btn resign" @tap="goSign('income')">重签</view>
				</view>
				<view class="sign-btn primary" v-else @tap="goSign('income')">去签署</view>
			</view>
			<view class="sign-item">
				<view class="sign-left">
					<text class="sign-name">个人信息处理同意书</text>
					<text :class="['sign-status', signedPrivacy ? 'signed' : '']">{{ signedPrivacy ? '已签署' : '未签署' }}</text>
				</view>
				<view class="sign-btns" v-if="signedPrivacy">
					<view class="sign-btn view" @tap="previewSign('privacy')">查看</view>
					<view class="sign-btn resign" @tap="goSign('privacy')">重签</view>
				</view>
				<view class="sign-btn primary" v-else @tap="goSign('privacy')">去签署</view>
			</view>
			<view class="sign-item">
				<view class="sign-left">
					<text class="sign-name">声明与承诺</text>
					<text :class="['sign-status', signedPromise ? 'signed' : '']">{{ signedPromise ? '已签署' : '未签署' }}</text>
				</view>
				<view class="sign-btns" v-if="signedPromise">
					<view class="sign-btn view" @tap="previewSign('promise')">查看</view>
					<view class="sign-btn resign" @tap="goSign('promise')">重签</view>
				</view>
				<view class="sign-btn primary" v-else @tap="goSign('promise')">去签署</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="btn-wrap">
			<u-button text="提交审核" :loading="submitting" @click="handleSubmit" color="#0E63E3" size="large" />
		</view>

		<!-- 地区选择器 -->
		<u-picker v-if="regionColumns[0].length" :show="showRegionPicker" :columns="regionColumns" @confirm="onRegionConfirm"
			@cancel="showRegionPicker = false" @change="onRegionChange" :defaultIndex="regionDefaultIndex" />

		<!-- 已通过重新提交确认弹窗 -->
		<u-popup :show="showConfirmPopup" mode="center" round="12" :safeAreaInsetBottom="false" @close="showConfirmPopup = false">
			<view class="confirm-popup">
				<view class="confirm-title">提示</view>
				<view class="confirm-content">您的资料审核已通过，如果重新提交审核会变为待审核，需要平台重新审核，是否确认提交？</view>
				<view class="confirm-btns">
					<u-button text="取消" size="normal" :plain="true" shape="circle" @click="showConfirmPopup = false" />
					<u-button text="确认提交" size="normal" color="#0E63E3" shape="circle" @click="doSubmit" />
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script setup>
import { ref, reactive, computed, onBeforeUnmount } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { get, post, upload } from '@/utils/request.js'

const info = ref({})
const form = reactive({
	gender: '',
	province_code: '',
	city_code: '',
	district_code: '',
	address: '',
	emergency_contact: '',
	emergency_phone: '',
	tag: '',
	documents: [],
	sign_income: '',
	sign_privacy: '',
	sign_promise: '',
	income_amount: ''
})
const submitting = ref(false)
const showRegionPicker = ref(false)
const showConfirmPopup = ref(false)
const subscribeTmplId = ref('')

// 加载订阅消息模板配置
const loadSubscribeConfig = async () => {
	try {
		const res = await get('/api/mp/subscribeConfig')
		if (res.data && res.data.audit_result) {
			subscribeTmplId.value = res.data.audit_result
		}
	} catch (e) {}
}

// 请求订阅消息授权
const requestSubscribe = () => {
	return new Promise((resolve) => {
		if (!subscribeTmplId.value) return resolve(false)
		// #ifdef MP-WEIXIN
		wx.requestSubscribeMessage({
			tmplIds: [subscribeTmplId.value],
			success: () => resolve(true),
			fail: () => resolve(false)
		})
		// #endif
		// #ifndef MP-WEIXIN
		resolve(false)
		// #endif
	})
}

// 地区数据
const allRegions = ref([])
const regionColumns = ref([[], [], []])
const regionDefaultIndex = ref([0, 0, 0])

const maskedIdCard = computed(() => {
	const v = info.value.id_card || ''
	if (v.length === 18) return v.slice(0, 3) + '***********' + v.slice(-4)
	return v
})

const maskedPhone = computed(() => {
	const v = info.value.phone || ''
	if (v.length === 11) return v.slice(0, 3) + '****' + v.slice(-4)
	return v
})

// 签署状态：form 中有新签的 URL 或 info 中有已保存的 URL
const signedIncome = computed(() => form.sign_income || info.value.sign_income)
const signedPrivacy = computed(() => form.sign_privacy || info.value.sign_privacy)
const signedPromise = computed(() => form.sign_promise || info.value.sign_promise)

const regionText = computed(() => {
	const parts = []
	if (form.province_code) {
		const p = allRegions.value.find(r => r.code === form.province_code)
		if (p) parts.push(p.name)
	}
	if (form.city_code) {
		const prov = allRegions.value.find(r => r.code === form.province_code)
		if (prov && prov.children) {
			const c = prov.children.find(r => r.code === form.city_code)
			if (c) parts.push(c.name)
		}
	}
	if (form.district_code) {
		const prov = allRegions.value.find(r => r.code === form.province_code)
		if (prov && prov.children) {
			const city = prov.children.find(r => r.code === form.city_code)
			if (city && city.children) {
				const d = city.children.find(r => r.code === form.district_code)
				if (d) parts.push(d.name)
			}
		}
	}
	return parts.join(' ')
})

// 签署结果事件监听
const onSignResult = (data) => {
	if (data.type === 'income') {
		form.sign_income = data.url
		if (data.amount) form.income_amount = data.amount
	} else if (data.type === 'privacy') {
		form.sign_privacy = data.url
	} else if (data.type === 'promise') {
		form.sign_promise = data.url
	}
}

onLoad(async () => {
	uni.$on('signResult', onSignResult)
	await loadRegions()
	await loadInfo()
	loadSubscribeConfig()
})

onBeforeUnmount(() => {
	uni.$off('signResult', onSignResult)
})

const goSign = (type) => {
	uni.navigateTo({ url: `/pages/sign/sign?type=${type}` })
}

const previewSign = (type) => {
	const urlMap = {
		income: form.sign_income || info.value.sign_income,
		privacy: form.sign_privacy || info.value.sign_privacy,
		promise: form.sign_promise || info.value.sign_promise
	}
	const url = urlMap[type]
	if (url) uni.previewImage({ urls: [url], current: 0 })
}

const loadRegions = async () => {
	try {
		const res = await get('/common/regions')
		allRegions.value = res.data || []
		buildRegionColumns()
	} catch (e) {}
}

const buildRegionColumns = (pIdx = 0, cIdx = 0) => {
	const provinces = allRegions.value
	const col0 = provinces.map(p => p.name)
	const cities = (provinces[pIdx] && provinces[pIdx].children) || []
	const col1 = cities.map(c => c.name)
	const districts = (cities[cIdx] && cities[cIdx].children) || []
	const col2 = districts.map(d => d.name)
	regionColumns.value = [col0, col1, col2]
}

const onRegionChange = (e) => {
	const { columnIndex, index } = e
	if (columnIndex === 0) {
		buildRegionColumns(index, 0)
		regionDefaultIndex.value = [index, 0, 0]
	} else if (columnIndex === 1) {
		const pIdx = regionDefaultIndex.value[0]
		buildRegionColumns(pIdx, index)
		regionDefaultIndex.value = [pIdx, index, 0]
	}
}

const onRegionConfirm = (e) => {
	const idxs = e.indexs || e.index || [0, 0, 0]
	const provinces = allRegions.value
	const prov = provinces[idxs[0]]
	const city = prov && prov.children ? prov.children[idxs[1]] : null
	const dist = city && city.children ? city.children[idxs[2]] : null
	form.province_code = prov ? prov.code : ''
	form.city_code = city ? city.code : ''
	form.district_code = dist ? dist.code : ''
	showRegionPicker.value = false
}

const loadInfo = async () => {
	try {
		const res = await get('/api/mp/myInfo')
		if (!res.data) return
		info.value = res.data
		// 填充表单
		form.gender = res.data.gender || ''
		form.province_code = res.data.province_code || ''
		form.city_code = res.data.city_code || ''
		form.district_code = res.data.district_code || ''
		form.address = res.data.address || ''
		form.emergency_contact = res.data.emergency_contact || ''
		form.emergency_phone = res.data.emergency_phone || ''
		form.tag = res.data.tag || ''
		form.documents = res.data.documents || []
		form.sign_income = res.data.sign_income || ''
		form.sign_privacy = res.data.sign_privacy || ''
		form.sign_promise = res.data.sign_promise || ''
		form.income_amount = res.data.income_amount || ''
		// 设置地区选择器默认索引
		if (form.province_code && allRegions.value.length) {
			const pIdx = allRegions.value.findIndex(r => r.code === form.province_code)
			if (pIdx >= 0) {
				const cities = allRegions.value[pIdx].children || []
				const cIdx = cities.findIndex(r => r.code === form.city_code)
				const ci = cIdx >= 0 ? cIdx : 0
				const districts = (cities[ci] && cities[ci].children) || []
				const dIdx = districts.findIndex(r => r.code === form.district_code)
				buildRegionColumns(pIdx, ci)
				regionDefaultIndex.value = [pIdx, ci, dIdx >= 0 ? dIdx : 0]
			}
		}
	} catch (e) {}
}

const chooseDocument = () => {
	uni.chooseImage({
		count: 9 - form.documents.length,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			for (const filePath of res.tempFilePaths) {
				try {
					const uploadRes = await upload('/api/mp/upload', { filePath, name: 'file' })
					if (uploadRes.data && uploadRes.data.url) {
						form.documents.push(uploadRes.data.url)
					}
				} catch (e) {}
			}
		}
	})
}

const previewImage = (idx) => {
	uni.previewImage({ urls: form.documents, current: idx })
}

const handleSubmit = async () => {
	if (!info.value.gender && !form.gender) {
		return uni.showToast({ title: '请选择性别', icon: 'none' })
	}
	if (!form.province_code || !form.city_code || !form.district_code) {
		return uni.showToast({ title: '请选择省市区', icon: 'none' })
	}
	if (!form.address.trim()) {
		return uni.showToast({ title: '请填写详细地址', icon: 'none' })
	}
	// 已通过状态需要二次确认
	if (info.value.status === 1) {
		showConfirmPopup.value = true
		return
	}
	await doSubmit()
}

const doSubmit = async () => {
	showConfirmPopup.value = false
	// 先请求订阅消息授权（用户拒绝也继续提交）
	await requestSubscribe()
	submitting.value = true
	try {
		const params = {
			gender: info.value.gender || form.gender,
			province_code: form.province_code,
			city_code: form.city_code,
			district_code: form.district_code,
			address: form.address.trim(),
			emergency_contact: form.emergency_contact,
			emergency_phone: form.emergency_phone,
			tag: form.tag,
			documents: form.documents,
			sign_income: form.sign_income,
			sign_privacy: form.sign_privacy,
			sign_promise: form.sign_promise,
			income_amount: form.income_amount || null,
			// #ifdef MP-WEIXIN
			mp_env_version: uni.getAccountInfoSync().miniProgram.envVersion || 'release'
			// #endif
		}
		await post('/api/mp/saveMyInfo', params)
		uni.showToast({ title: '提交成功', icon: 'success' })
		setTimeout(() => uni.navigateBack(), 1500)
	} catch (e) {
		if (e && e.msg) uni.showToast({ title: e.msg, icon: 'none' })
	} finally {
		submitting.value = false
	}
}
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	background: #f4f4f5;
	padding: 24rpx;
	padding-bottom: 240rpx;
}

.section {
	background: #fff;
	border-radius: 10rpx;
	padding: 32rpx;
	margin-bottom: 24rpx;
	border: 1rpx solid #ebeef5;
}

.reject-tip {
	display: flex;
	align-items: flex-start;
	padding: 24rpx 28rpx;
	background: #fff2f0;
	border: 1rpx solid #ffccc7;
	border-radius: 10rpx;
	margin-bottom: 24rpx;

	.reject-text {
		flex: 1;
		font-size: 26rpx;
		color: #f5222d;
		margin-left: 16rpx;
		line-height: 1.5;
	}
}

.section-title {
	display: flex;
	align-items: center;
	gap: 12rpx;
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 28rpx;
}

.form-group {
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;

	&:last-child {
		border-bottom: none;
	}
}

.form-label {
	font-size: 28rpx;
	color: #555;
	margin-bottom: 16rpx;
	display: block;
}

.readonly-input {
	padding: 20rpx 24rpx;
	background: #f5f5f5;
	border: 1rpx solid #ddd;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #333;
}

.gender-row {
	display: flex;
	gap: 20rpx;
}

.gender-item {
	flex: 1;
	text-align: center;
	padding: 16rpx 0;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #333;

	&.active {
		border-color: #0e63e3;
		color: #0e63e3;
		background: rgba(14, 99, 227, 0.05);
	}
}

.region-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 24rpx;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
}

.region-text {
	font-size: 28rpx;
	color: #333;

	&.placeholder {
		color: #c0c4cc;
	}
}

.arrow {
	font-size: 28rpx;
	color: #c0c4cc;
}

.contact-row {
	display: flex;
	gap: 16rpx;
}

.contact-input {
	flex: 1;
}

.upload-tip {
	font-size: 26rpx;
	color: #888;
	line-height: 1.6;
	margin-bottom: 20rpx;
}

.upload-row {
	display: flex;
	gap: 16rpx;
	flex-wrap: wrap;
}

.upload-item {
	position: relative;
	width: 180rpx;
	height: 180rpx;
}

.upload-img {
	width: 180rpx;
	height: 180rpx;
	border-radius: 8rpx;
	border: 1rpx solid #eee;
}

.upload-del {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	width: 40rpx;
	height: 40rpx;
	background: rgba(0, 0, 0, 0.5);
	color: #fff;
	border-radius: 50%;
	font-size: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.upload-box {
	width: 180rpx;
	height: 180rpx;
	border: 2rpx dashed #ccc;
	border-radius: 8rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background: #fafafa;
}

.upload-icon {
	font-size: 56rpx;
	color: #ccc;
}

.upload-text {
	font-size: 22rpx;
	color: #999;
	margin-top: 4rpx;
}

.sign-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 28rpx 0;
	border-bottom: 1rpx solid #f0f0f0;

	&:last-child {
		border-bottom: none;
	}
}

.sign-left {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.sign-name {
	font-size: 28rpx;
	color: #333;
}

.sign-status {
	font-size: 24rpx;
	color: #f5222d;

	&.signed {
		color: #52c41a;
	}
}

.sign-btns {
	display: flex;
	gap: 12rpx;
	flex-shrink: 0;
}

.sign-btn {
	padding: 10rpx 28rpx;
	border-radius: 28rpx;
	font-size: 24rpx;
	text-align: center;
	flex-shrink: 0;

	&.primary {
		background: #0e63e3;
		color: #fff;
	}

	&.view {
		background: #f0f5ff;
		color: #0e63e3;
		border: 1rpx solid #d0e0ff;
	}

	&.resign {
		background: #fff7e6;
		color: #fa8c16;
		border: 1rpx solid #ffe7ba;
	}

	&:active {
		opacity: 0.7;
	}
}

.btn-wrap {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #fff;
	padding: 20rpx 32rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.06);
	z-index: 100;
}

.confirm-popup {
	padding: 48rpx 40rpx 40rpx;
	width: 560rpx;
}

.confirm-title {
	font-size: 34rpx;
	font-weight: 600;
	color: #333;
	text-align: center;
	margin-bottom: 28rpx;
}

.confirm-content {
	font-size: 28rpx;
	color: #666;
	line-height: 1.7;
	text-align: center;
	margin-bottom: 40rpx;
}

.confirm-btns {
	display: flex;
	gap: 24rpx;
}
</style>
