<template>
	<view class="page">
		<u-navbar class="nav-bar" title="仓库字段权限配置" :autoBack="true" :placeholder="true" v-hideNav></u-navbar>
		<view class="content">
			<view class="tip-card">
				<u-icon name="setting" size="18" color="#108cff"></u-icon>
				<text class="tip-text">为指定角色配置仓库各字段的「可查看」「可编辑」权限，以及「编辑」「删除」按钮权限。保存后该角色用户将按此配置在列表/详情中看到并可编辑对应字段、使用对应按钮。</text>
			</view>

			<!-- 选择角色 -->
			<view class="section role-section">
				<view class="section-title">选择角色</view>
				<view v-if="roleList.length > 0" class="role-select-wrap">
					<picker :value="roleIndex" :range="roleList" range-key="roleName" @change="onRoleChange">
						<view class="picker-inner">
							<text class="picker-text">{{ currentRoleName }}</text>
							<u-icon name="arrow-down" size="14" color="#999"></u-icon>
						</view>
					</picker>
				</view>
				<view v-else class="role-input-wrap">
					<view class="input-row">
						<text class="input-label">角色ID</text>
						<u--input v-model="formRoleId" type="number" placeholder="请输入角色ID" border="surround"></u--input>
					</view>
					<view class="input-row">
						<text class="input-label">角色Key</text>
						<u--input v-model="formRoleKey" placeholder="如 WAREHOUSER" border="surround"></u--input>
					</view>
					<u-button type="primary" size="small" :loading="loadConfigLoading"
						@click="loadConfig">加载配置</u-button>
				</view>
			</view>

			<!-- 字段权限列表（可编辑） -->
			<view class="section">
				<view class="section-head">
					<text class="section-title">字段权限</text>
					<view class="btn-group">
						<u-button type="success" plain size="mini" 
							:disabled="!currentRoleId || permissionList.length === 0" @click="openAllPermissions">一键全开</u-button>
						<u-button type="error" plain size="mini" 
							:disabled="!currentRoleId || permissionList.length === 0" @click="closeAllPermissions">一键全关</u-button>
						<u-button type="primary" size="mini" :loading="saveLoading"
							:disabled="!currentRoleId || permissionList.length === 0" @click="saveConfig">保存配置</u-button>
					</view>
				</view>
				<view v-if="loadConfigLoading" class="loading-wrap">
					<u-loading-icon mode="circle" size="36"></u-loading-icon>
					<text class="loading-text">加载中...</text>
				</view>
				<scroll-view v-else class="list-wrap" scroll-y enable-back-to-top>
					<view class="field-list">
						<view v-for="(item, index) in permissionList" :key="item.fieldName" class="field-item">
							<view class="field-name-wrap">
								<text class="field-name">{{ fieldLabel(item.fieldName) }}</text>
								<!-- <text class="field-key">{{ item.fieldName }}</text> -->
							</view>
							<view class="field-switches">
								<view class="switch-cell">
									<text class="switch-label">查看</text>
									<u-switch v-model="item.read" size="20" active-color="#108cff"></u-switch>
								</view>
								<view class="switch-cell">
									<text class="switch-label">编辑</text>
									<u-switch v-model="item.edit" size="20" active-color="#09bb07"></u-switch>
								</view>
							</view>
						</view>
					</view>
					<view v-if="permissionList.length === 0 && !loadConfigLoading" class="empty-wrap">
						<u-empty text="请先选择角色并点击「加载配置」" mode="list"></u-empty>
					</view>
				</scroll-view>
			</view>

			<!-- 按钮权限 -->
			<view class="section">
				<view class="section-head">
					<text class="section-title">按钮权限</text>
					<view class="btn-group">
						<u-button type="success" plain size="mini" 
							:disabled="!currentRoleId || buttonPermissionList.length === 0" @click="openAllButtonPermissions">一键全开</u-button>
						<u-button type="error" plain size="mini" 
							:disabled="!currentRoleId || buttonPermissionList.length === 0" @click="closeAllButtonPermissions">一键全关</u-button>
						<u-button type="primary" size="mini" :loading="saveLoading"
							:disabled="!currentRoleId || !buttonPermissionList.length" @click="saveButtonConfig">保存配置</u-button>
					</view>
				</view>
				<view class="button-list">
					<view class="field-item" v-for="item in buttonPermissionList" :key="item.buttonKey">
						<view class="field-name-wrap">
							<text class="field-name">{{ item.label }}</text>
						</view>
						<view class="field-switches">
							<u-switch v-model="item.enabled" size="20" active-color="#09bb07"></u-switch>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import {updateFieldPermissions,updateButtonPermissions} from "@/utils/util.js";
const FIELD_LABELS = {
	goodPicFileList: '商品图片', desc: '商品描述', origin: '来源', type: '商品分类', dictLabel: '品牌',
	series: '系列', model: '型号', dialType: '机芯类型', caseMaterial: '表壳材质', dialDiameter: '表盘直径',
	material: '材质', size: '尺寸', yardage: '尺码', productCondition: '商品成色', detailPicFileList: '细节图',
	title: '商品标题', productNo: '商品货号', productAttribute: '商品属性', stock: '库存数量', price: '官方指导价',
	costPrice: '总成本价', peerPrice: '同行价格', actualPrice: '实价', agentPrice: '代理价格', salePrice: '销售价格',
	productPosition: '商品位置', watchYear: '手表年份', identifyingPerson: '鉴定人员', stockStatus: '是否入库',
	recycleType: '回收类型', recycleSituation: '回收情况', label: '标签', recyclePerson: '回收人员',
	recycleBottomDesc: '回收留底描述', recycleBottomFileList: '回收留底图', recycleTime: '回收时间',
	indentifyCode: '独立编码', targetAudience: '适用人群', productCard: '商品保卡', cardYear: '保卡年份',
	productCardPicFileList: '保卡图片或独立编码照片留底', productTag: '商品标签', productAttachment: '商品附件',
	productDesc: '备注', productDescPicFileList: '备注图片', payType: '付款方式',
};

export default {
	data() {
		return {
			roleList: [],
			roleIndex: 0,
			formRoleId: '',
			formRoleKey: '',
			loadConfigLoading: false,
			saveLoading: false,
			permissionList: [],
			// 按钮权限：编辑、删除、上/下架、开单、查看日志、解/锁单，与后端 buttonKey 一致
			buttonPermissionList: [
				{ buttonKey: 'edit', label: '编辑', enabled: false },
				{ buttonKey: 'delete', label: '删除', enabled: false },
				{ buttonKey: 'shelf', label: '上/下架', enabled: false },
				{ buttonKey: 'openOrder', label: '开单', enabled: false },
				{ buttonKey: 'viewLog', label: '查看日志', enabled: false },
				{ buttonKey: 'lockOrder', label: '解/锁单', enabled: false },
			],
		};
	},
	computed: {
		currentRoleId() {
			if (this.roleList.length > 0) {
				const r = this.roleList[this.roleIndex];
				return r ? r.roleId : null;
			}
			const id = parseInt(this.formRoleId, 10);
			return isNaN(id) ? null : id;
		},
		currentRoleKey() {
			if (this.roleList.length > 0) {
				const r = this.roleList[this.roleIndex];
				return r ? r.roleKey || '' : '';
			}
			return this.formRoleKey || '';
		},
		currentRoleName() {
			if (this.roleList.length > 0) {
				const r = this.roleList[this.roleIndex];
				return r ? (r.roleName || '请选择角色') : '请选择角色';
			}
			return this.currentRoleId ? `角色ID: ${this.currentRoleId}` : '请填写角色ID并加载';
		},
	},
	onLoad() { },
	onShow() {
		this.fetchRoleList();
	},
	methods: {
		fieldLabel(name) {
			return FIELD_LABELS[name] || name;
		},
		fetchRoleList() {
			uni.$u.api.getRoleOptionSelectAll({ custom: { loading: false } })
				.then((res) => {
					const list = (res && res.data) ? (Array.isArray(res.data) ? res.data : []) : [];
					this.roleList = list.map((r) => ({ roleId: r.roleId, roleName: r.roleName || r.roleKey || '', roleKey: r.roleKey || '' }));
					this.roleIndex = 0;
					if (this.roleList.length > 0) {
						this.loadConfig();
					}
				})
				.catch(() => {
					this.roleList = [];
				});
		},
		onRoleChange(e) {
			this.roleIndex = e.detail.value;
			this.permissionList = [];
			this.loadConfig()
		},
		loadConfig() {
			const roleId = this.currentRoleId;
			if (roleId == null) {
				uni.$u.toast('请选择或填写角色');
				return;
			}
			this.loadConfigLoading = true;
			Promise.all([
				uni.$u.api.wareHouseFieldPermissionsConfigGet({ roleId }),
				uni.$u.api.wareHouseButtonPermissionsConfigGet({ roleId }),
			])
				.then(([fieldRes, buttonRes]) => {
					if (fieldRes && fieldRes.data && Array.isArray(fieldRes.data)) {
						this.permissionList = fieldRes.data.map((p) => ({
							fieldName: p.fieldName,
							read: !!p.read,
							edit: !!p.edit,
						}));
					} else {
						this.permissionList = [];
					}
					if (buttonRes && buttonRes.data && Array.isArray(buttonRes.data)) {
						const map = {};
						buttonRes.data.forEach((b) => { map[b.buttonKey] = !!b.enabled; });
						const defaultButtons = [
							{ buttonKey: 'edit', label: '编辑', enabled: !!map['edit'] },
							{ buttonKey: 'delete', label: '删除', enabled: !!map['delete'] },
							{ buttonKey: 'shelf', label: '上/下架', enabled: !!map['shelf'] },
							{ buttonKey: 'openOrder', label: '开单', enabled: !!map['openOrder'] },
							{ buttonKey: 'viewLog', label: '查看日志', enabled: !!map['viewLog'] },
							{ buttonKey: 'lockOrder', label: '解/锁单', enabled: !!map['lockOrder'] },
						];
						this.buttonPermissionList = defaultButtons;
					}
				})
				.catch(() => {
					this.permissionList = [];
					uni.$u.toast('加载失败');
				})
				.finally(() => {
					this.loadConfigLoading = false;
				});
		},
		updateFieldPermissions:updateFieldPermissions,
		updateButtonPermissions:updateButtonPermissions,
		saveConfig() {
			const roleId = this.currentRoleId;
			const roleKey = this.currentRoleKey;
			if (roleId == null) {
				uni.$u.toast('请选择或填写角色');
				return;
			}
			if (!this.permissionList.length) {
				uni.$u.toast('请先加载配置');
				return;
			}
			this.saveLoading = true;
			uni.$u.api.wareHouseFieldPermissionsConfigSave({
				roleId,
				roleKey,
				permissions: this.permissionList.map((p) => ({ fieldName: p.fieldName, read: p.read, edit: p.edit })),
			})
				.then(() => {
					uni.$u.toast('保存成功');
				})
				.catch(() => {
					uni.$u.toast('保存失败');
				})
				.finally(() => {
					this.saveLoading = false;
				});
			this.updateFieldPermissions();
		},
		saveButtonConfig() {
			const roleId = this.currentRoleId;
			const roleKey = this.currentRoleKey;
			if (roleId == null) {
				uni.$u.toast('请选择或填写角色');
				return;
			}
			this.saveLoading = true;
			console.log(this.buttonPermissionList);
			
			uni.$u.api.wareHouseButtonPermissionsConfigSave({
				roleId,
				roleKey,
				permissions: this.buttonPermissionList.map((p) => ({ buttonKey: p.buttonKey, enabled: p.enabled })),
			})
				.then(() => {
					uni.$u.toast('按钮权限保存成功');
				})
				.catch(() => {
					uni.$u.toast('保存失败');
				})
				.finally(() => {
					this.saveLoading = false;
				});
			this.updateButtonPermissions();
		},
		clearConfig() {
			if (!this.currentRoleId) return;
			uni.showModal({
				title: '确认清空',
				content: '将删除该角色下所有字段权限与按钮权限配置，确定吗？',
				success: (res) => {
					if (res.confirm) {
						uni.$u.api.wareHouseFieldPermissionsConfigDeleteByRole(this.currentRoleId).then(() => {
							uni.$u.toast('已清空');
							this.permissionList = [];
							this.buttonPermissionList = [
								{ buttonKey: 'edit', label: '编辑', enabled: false },
								{ buttonKey: 'delete', label: '删除', enabled: false },
								{ buttonKey: 'shelf', label: '上/下架', enabled: false },
								{ buttonKey: 'openOrder', label: '开单', enabled: false },
								{ buttonKey: 'viewLog', label: '查看日志', enabled: false },
								{ buttonKey: 'lockOrder', label: '解/锁单', enabled: false },
							];
						}).catch(() => uni.$u.toast('清空失败'));
					}
				},
			});
		},
		// 一键打开所有权限
		openAllPermissions() {
			this.permissionList.forEach(item => {
				item.read = true;
				item.edit = true;
			});
			uni.$u.toast('已打开所有权限');
		},
		// 一键关闭所有权限
		closeAllPermissions() {
			this.permissionList.forEach(item => {
				item.read = false;
				item.edit = false;
			});
			uni.$u.toast('已关闭所有权限');
		},
		// 一键打开所有按钮权限
		openAllButtonPermissions() {
			this.buttonPermissionList.forEach(item => {
				item.enabled = true;
			});
			uni.$u.toast('已打开所有按钮权限');
		},
		// 一键关闭所有按钮权限
		closeAllButtonPermissions() {
			this.buttonPermissionList.forEach(item => {
				item.enabled = false;
			});
			uni.$u.toast('已关闭所有按钮权限');
		},
	},
};
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	background: #f5f6f8;
	display: flex;
	flex-direction: column;
}

.nav-bar {
	border-bottom: 1px solid #eee;
}

.content {
	flex: 1;
	display: flex;
	flex-direction: column;
	padding: 24rpx;
	box-sizing: border-box;
}

.tip-card {
	display: flex;
	align-items: flex-start;
	gap: 12rpx;
	background: #e8f4ff;
	border-radius: 16rpx;
	padding: 20rpx 24rpx;
	margin-bottom: 24rpx;
	border: 1px solid rgba(16, 140, 255, 0.2);

	.tip-text {
		font-size: 26rpx;
		color: #333;
		line-height: 1.5;
		flex: 1;
	}
}

.section {
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.section-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 20rpx;
}

.section-head {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;

		.section-title {
			margin-bottom: 0;
		}

		.btn-group {
			display: flex;
			gap: 12rpx;

			.u-button {
				width: auto;
				margin: 0;
			}
		}
	}

.role-section {
	.role-select-wrap {
		margin-bottom: 20rpx;
	}

	.picker-inner {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 24rpx;
		background: #f9fafb;
		border-radius: 12rpx;
		border: 1px solid #eee;

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

	.role-input-wrap {
		margin-bottom: 20rpx;

		.input-row {
			display: flex;
			align-items: center;
			margin-bottom: 16rpx;

			.input-label {
				width: 140rpx;
				font-size: 28rpx;
				color: #666;
			}
		}
	}
}

.list-wrap {
	max-height: 35vh;
}

.loading-wrap {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx 0;

	.loading-text {
		margin-top: 16rpx;
		font-size: 26rpx;
		color: #999;
	}
}

.field-list {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
	padding-bottom: 24rpx;
}

.field-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 24rpx;
	background: #fafafa;
	border-radius: 12rpx;
	border: 1px solid #f0f0f0;
}

.field-name-wrap {
	flex: 1;
	min-width: 0;
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.field-name {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
}

.field-key {
	font-size: 22rpx;
	color: #999;
}

.field-switches {
	display: flex;
	align-items: center;
	gap: 32rpx;
	flex-shrink: 0;
}

.switch-cell {
	display: flex;
	align-items: center;
	gap: 12rpx;

	.switch-label {
		font-size: 24rpx;
		color: #666;
	}
}

.empty-wrap {
	padding: 60rpx 0;
}

.button-list {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}
</style>
