<template>
	<view class="commission-form-list">
		<!-- 头部按钮组 -->
		<view class="commission-header">
			<u-button type="primary" size="mini" icon="plus" @click="handleAdd">新增分成</u-button>
		</view>

		<!-- 分成信息卡片列表 -->
		<view v-if="loading" class="loading_wrap">
			<u-loading-icon text="加载中" textSize="18"></u-loading-icon>
		</view>
		<view v-else-if="commissionList.length === 0" class="empty_wrap">
			<u-empty text="暂无分成数据"></u-empty>
		</view>
		<view v-else class="card_list">
			<view class="card_item" v-for="(row, index) in commissionList" :key="row.id">
				<view class="card_header">
					<view class="card_title">{{ row.userName || '-' }}</view>
					<view class="card_actions">
						<u-button size="mini" type="text" @click="handleEdit(row)">编辑</u-button>
						<u-button size="mini" type="text" @click="handleDelete(row.id)" style="color: #f56c6c">删除</u-button>
					</view>
				</view>
				<view class="card_body">
					<view class="info_row">
						<view class="info_label">公司:</view>
						<view class="info_value">{{ row.orgName || '-' }}</view>
					</view>
					<view class="info_row">
						<view class="info_label">账户类型:</view>
						<view class="info_value">{{ row.accountType === '1' ? '前端' : '后端' }}</view>
					</view>
					<view class="info_row">
						<view class="info_label">分成比例:</view>
						<view class="info_value highlight">{{ row.commissionRate || '0' }}%</view>
					</view>
					<view class="info_row">
						<view class="info_label">创建时间:</view>
						<view class="info_value">{{ formatTime(row.createTime) }}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 分页组件 -->
		<u-pagination
			v-if="total > 0"
			:total="total"
			:current="queryParams.pageNum"
			:page-size="queryParams.pageSize"
			@change="handlePageChange"
			:page-sizes="[10, 20, 50, 100]"
			:show-total="true"
		></u-pagination>

		<!-- 新增/编辑对话框 -->
		<u-popup v-model="dialogVisible" mode="center" width="500rpx" border-radius="16">
			<view class="dialog_header">{{ dialogTitle }}</view>
			<view class="dialog_body">
				<u-form :model="commissionForm" ref="commissionFormRef" label-width="120rpx">
					<u-form-item label="账户类型" prop="accountType" :required="true">
						<u-radio-group v-model="commissionForm.accountType" :disabled="!isEdit">
							<u-radio name="1" label="前端"></u-radio>
							<u-radio name="2" label="后端"></u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="分成人" prop="userName" :required="true">
						<u-input v-model="commissionForm.userName" placeholder="请选择分成人" :disabled="!isEdit" />
					</u-form-item>
					<u-form-item label="分成比例(%)" prop="commissionRate" :required="true">
						<u-input v-model.number="commissionForm.commissionRate" type="number" placeholder="请输入分成比例(0-100)" />
					</u-form-item>
				</u-form>
			</view>
			<view class="dialog_footer">
				<u-button @click="handleClose">取消</u-button>
				<u-button type="primary" @click="handleSubmit">确定</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	name: 'CommissionFormList',
	props: {
		sendFormId: {
			type: [Number, String],
			required: true
		},
		clueId: {
			type: [Number, String],
			required: true
		}
	},
	data() {
		return {
			commissionList: [],
			total: 0,
			loading: false,
			queryParams: {
				pageNum: 1,
				pageSize: 10
			},
			dialogVisible: false,
			dialogTitle: '新增分成',
			isEdit: true,
			commissionForm: {
				id: null,
				sendFormId: null,
				clueId: null,
				accountType: '1',
				userName: null,
				userId: null,
				commissionRate: 0
			},
			rules: {
				accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
				userName: [{ required: true, message: '请选择分成人', trigger: 'blur' }],
				commissionRate: [
					{ required: true, message: '请输入分成比例', trigger: 'blur' },
					{ type: 'number', min: 0, max: 100, message: '分成比例必须在0-100之间', trigger: 'blur' }
				]
			}
		}
	},
	methods: {
		async getList() {
			this.loading = true
			try {
				const params = {
					...this.queryParams,
					sendFormId: this.sendFormId,
				}
				const res = await uni.$u.api.clueCommissionForm.list(params)
				this.commissionList = res.rows || []
				this.total = res.total || 0
			} catch (error) {
				uni.$u.toast('获取分成列表失败')
			} finally {
				this.loading = false
			}
		},
		// 格式化时间
		formatTime(time) {
			if (!time) return '-'
			const date = new Date(time)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			const seconds = String(date.getSeconds()).padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		},
		handleAdd() {
			this.dialogTitle = '新增分成'
			this.commissionForm = {
				id: null,
				sendFormId: this.sendFormId,
				clueId: this.clueId,
				accountType: '1',
				userName: null,
				userId: null,
				commissionRate: 0
			}
			this.$nextTick(() => {
				if (this.$refs.commissionFormRef) {
					this.$refs.commissionFormRef.clearValidate()
				}
			})
			this.dialogVisible = true
		},
		handleEdit(row) {
			this.dialogTitle = '编辑分成'
			// 深拷贝对象，避免直接修改原数据
			this.commissionForm = JSON.parse(JSON.stringify(row))
			this.dialogVisible = true
		},
		handleDelete(id) {
			uni.showModal({
				title: '警告',
				content: '确定要删除这条分成记录吗？删除后将无法恢复！',
				confirmButtonText: '确定删除',
				cancelButtonText: '取消',
				success: (res) => {
					if (res.confirm) {
						this.deleteRow(id)
					}
				}
			})
		},
		async deleteRow(id) {
			try {
				await uni.$u.api.clueCommissionForm.remove([id])
				uni.$u.toast('删除成功')
				this.getList()
			} catch (error) {
				uni.$u.toast('删除失败，请稍后重试')
			}
		},
		handleSubmit() {
			this.$refs.commissionFormRef.validate(async (valid) => {
				if (valid) {
					// 显示加载状态
					const loading = uni.showLoading({
						title: this.commissionForm.id ? '编辑中...' : '新增中...',
						mask: true
					})

					try {
						if (this.commissionForm.id) {
							await uni.$u.api.clueCommissionForm.update(this.commissionForm)
							uni.$u.toast('编辑成功')
						} else {
							await uni.$u.api.clueCommissionForm.add(this.commissionForm)
							uni.$u.toast('新增成功')
						}
						this.dialogVisible = false
						this.getList()
					} catch (error) {
						uni.$u.toast('操作失败，请重试')
					} finally {
						uni.hideLoading(loading)
					}
				}
			})
		},
		handleClose() {
			this.dialogVisible = false
			// 关闭对话框后重置表单
			this.$nextTick(() => {
				if (this.$refs.commissionFormRef) {
					this.$refs.commissionFormRef.clearValidate()
				}
			})
		},
		handlePageChange(page) {
			this.queryParams.pageNum = page
			this.getList()
		},
		// 外部调用获取列表
		getListByExternal() {
			this.getList()
		}
	},
	created() {
		this.getList()
	}
}
</script>

<style lang="scss" scoped>
.commission-form-list {
	padding: 0 20px 20px;
}

.commission-header {
	margin-bottom: 16px;
}

.card_list {
	display: flex;
	flex-direction: column;
	gap: 16px;
}

.card_item {
	background-color: #fff;
	border-radius: 12px;
	padding: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card_header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
	padding-bottom: 12px;
	border-bottom: 1px solid #f0f0f0;
}

.card_title {
	font-size: 18px;
	font-weight: bold;
	color: #202020;
}

.card_actions {
	display: flex;
	gap: 8px;
}

.card_body {
	display: flex;
	flex-direction: column;
	gap: 12px;
}

.info_row {
	display: flex;
	align-items: center;
	font-size: 14px;
}

.info_label {
	color: #666;
	min-width: 80px;
	font-weight: 500;
}

.info_value {
	color: #202020;
	flex: 1;
	
	&.highlight {
		color: #108cff;
		font-weight: bold;
		font-size: 16px;
	}
}

.loading_wrap,
.empty_wrap {
	padding: 40px 20px;
	text-align: center;
}

.dialog_header {
	padding: 20px;
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
	border-bottom: 1px solid #e9ecef;
}

.dialog_body {
	padding: 20px;
}

.dialog_footer {
	padding: 20px;
	display: flex;
	justify-content: space-around;
	border-top: 1px solid #e9ecef;
}
</style>