<template>
	<el-dialog 
		:title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" 
		:close-on-click-modal="false" 
		:visible.sync="visible" 
		class="NCC-dialog NCC-dialog_center" 
		lock-scroll 
		width="900px"
	>
		<el-form ref="elForm" :model="dataForm" size="small" label-width="120px" label-position="right" :disabled="!!isDetail" :rules="rules">
			<el-row :gutter="15">
				<!-- <el-col :span="24">
					<el-form-item label="配置编号" prop="id">
						<el-input v-model="dataForm.id" placeholder="自动生成" clearable readonly :style='{"width":"100%"}' />
					</el-form-item>
				</el-col> -->
				<el-col :span="24">
					<el-form-item label="工作流名称" prop="workflowName">
						<el-input v-model="dataForm.workflowName" placeholder="请输入工作流名称" clearable :style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="是否启用" prop="isEnabled">
						<el-switch v-model="dataForm.isEnabled" :active-value="1" :inactive-value="0"  />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="描述" prop="description">
						<el-input v-model="dataForm.description" type="textarea" :rows="3" placeholder="请输入描述" clearable :style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
			</el-row>

			<!-- 审批节点配置 -->
			<el-card class="form-card" shadow="hover">
				<div slot="header" class="card-header">
					<i class="el-icon-s-order"></i>
					<span class="card-title">审批节点配置（1-5个节点）</span>
					<el-button 
						v-if="!isDetail"
						type="text" 
						icon="el-icon-plus" 
						@click="addNode"
						style="margin-left: auto;"
						:disabled="dataForm.nodes.length >= 5"
					>
						添加节点
					</el-button>
				</div>
				<div class="nodes-list">
					<div 
						v-for="(node, index) in dataForm.nodes" 
						:key="index"
						class="node-item"
					>
						<div class="node-header">
							<span class="node-order">节点 {{ node.nodeOrder }}</span>
							<el-button 
								v-if="!isDetail"
								type="text" 
								icon="el-icon-delete" 
								@click="removeNode(index)"
								style="color: #F56C6C"
								:disabled="dataForm.nodes.length <= 1"
							>
								删除
							</el-button>
						</div>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item 
									:label="`节点${node.nodeOrder}名称`" 
									:prop="`nodes.${index}.nodeName`"
									:rules="{ required: true, message: '请输入节点名称', trigger: 'blur' }"
								>
									<el-input 
										v-model="node.nodeName" 
										placeholder="请输入节点名称"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item 
									:label="`节点${node.nodeOrder}类型`" 
									:prop="`nodes.${index}.approvalType`"
									:rules="{ required: true, message: '请选择审批类型', trigger: 'change' }"
								>
								<el-select 
									v-model="node.approvalType" 
									placeholder="请选择审批类型"
									style="width: 100%"
								>
									<el-option label="会签" :value="1" />
									<el-option label="或签" :value="0" />
								</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item 
									:label="`节点${node.nodeOrder}审批人`" 
									:prop="`nodes.${index}.approverIds`"
									:rules="{ required: true, message: '请选择至少一个审批人', trigger: 'change' }"
								>
									<user-select 
										v-model="node.approverIds" 
										placeholder="请选择审批人" 
										:multiple="true"
										@change="(val) => handleApproverChange(index, val)"
										style="width: 100%"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="24" v-if="node.approverNames && node.approverNames.length > 0">
								<el-form-item label="已选审批人">
									<el-tag 
										v-for="(name, nameIndex) in node.approverNames" 
										:key="nameIndex"
										style="margin-right: 8px;"
									>
										{{ name }}
									</el-tag>
								</el-form-item>
							</el-col>
						</el-row>
					</div>
					<div v-if="dataForm.nodes.length === 0" class="empty-nodes">
						<el-empty description="请添加审批节点（至少1个）" :image-size="80" />
					</div>
				</div>
			</el-card>
		</el-form>

		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
	import request from '@/utils/request'
	import { getUserInfoList } from '@/api/permission/user'
	import userSelect from '@/components/NCC-userSelect'
	
	export default {
		components: {
			userSelect
		},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				dataForm: {
					id: undefined,
					workflowName: undefined,
					isEnabled: 1,
					description: undefined,
					nodes: []
				},
				rules: {
					workflowName: [
						{ required: true, message: '请输入工作流名称', trigger: 'blur' }
					],
				},
			}
		},
		computed: {},
		watch: {},
		created() {
		},
		mounted() {
		},
		methods: {
			goBack() {
				this.$emit('refresh')
			},
			init(id, isDetail) {
				this.dataForm.id = id || 0;
				this.visible = true;
				this.isDetail = isDetail || false;
				this.$nextTick(() => {
					this.$refs['elForm'].resetFields();
					if (this.dataForm.id) {
						request({
							url: '/api/Extend/LqReimbursementWorkflowConfig/' + this.dataForm.id,
							method: 'get'
						}).then(res => {
							this.dataForm = res.data;
							// 确保 nodes 是数组
							if (!this.dataForm.nodes || !Array.isArray(this.dataForm.nodes)) {
								this.dataForm.nodes = [];
							}
							// 处理节点数据格式转换
							this.dataForm.nodes.forEach(node => {
								// 处理审批人数据：后端返回的是 approvers 数组
								if (Array.isArray(node.approvers) && node.approvers.length > 0) {
									// 从 approvers 数组中提取 userId 和 userName
									const userIds = node.approvers.map(approver => approver.userId).filter(id => id);
									const userNames = node.approvers.map(approver => approver.userName).filter(name => name);
									
									// user-select 组件需要逗号分隔的字符串
									node.approverIds = userIds.join(',');
									node.approverNames = userNames;
								} else {
									// 如果没有 approvers，尝试从 approverIds 和 approverNames 获取
									if (Array.isArray(node.approverIds)) {
										node.approverIds = node.approverIds.filter(id => id && id.trim()).join(',');
									} else if (typeof node.approverIds === 'string') {
										node.approverIds = node.approverIds || '';
									} else {
										node.approverIds = '';
									}
									
									if (!Array.isArray(node.approverNames)) {
										node.approverNames = [];
									}
								}
								
								// 处理 approvalType：可能是字符串 "1" 或 "0"
								if (typeof node.approvalType === 'string') {
									if (node.approvalType === '会签' || node.approvalType === '1') {
										node.approvalType = 1;
									} else if (node.approvalType === '或签' || node.approvalType === '0') {
										node.approvalType = 0;
									} else {
										node.approvalType = 1; // 默认会签
									}
								} else if (typeof node.approvalType === 'number') {
									// 确保是 0 或 1
									node.approvalType = node.approvalType == 0 ? 0 : 1;
								} else {
									node.approvalType = 1; // 默认会签
								}
							});
						})
					} else {
						// 新建时初始化一个节点
						this.dataForm.nodes = [{
							nodeOrder: 1,
							nodeName: '',
							approvalType: 1, // 默认会签
							approverIds: '', // user-select组件需要字符串格式
							approverNames: []
						}];
					}
				})
			},
			addNode() {
				if (this.dataForm.nodes.length >= 5) {
					this.$message.warning('最多只能添加5个节点');
					return;
				}
				const newNode = {
					nodeOrder: this.dataForm.nodes.length + 1,
					nodeName: '',
					approvalType: 1, // 默认会签
					approverIds: '', // user-select组件需要字符串格式
					approverNames: []
				};
				this.dataForm.nodes.push(newNode);
			},
			removeNode(index) {
				if (this.dataForm.nodes.length <= 1) {
					this.$message.warning('至少需要保留一个节点');
					return;
				}
				this.dataForm.nodes.splice(index, 1);
				// 重新排序
				this.dataForm.nodes.forEach((node, idx) => {
					node.nodeOrder = idx + 1;
				});
			},
			async handleApproverChange(index, val) {
				const node = this.dataForm.nodes[index];
				
				// user-select组件返回的是逗号分隔的字符串
				const idsString = val || '';
				// 保存为字符串格式（user-select组件需要字符串）
				node.approverIds = idsString;
				
				// 转换为数组用于获取用户名
				const idsArray = idsString ? idsString.split(',').filter(id => id && id.trim()) : [];
				
				// 获取用户名列表
				if (idsArray.length > 0) {
					try {
						const response = await getUserInfoList(idsArray);
						if (response.code === 200 && response.data && response.data.list) {
							// 创建ID到用户信息的映射，确保顺序正确
							const userMap = new Map();
							response.data.list.forEach(user => {
								userMap.set(user.id, user.fullName || user.realName || user.id);
							});
							
							// 按照原始ID数组的顺序，从映射中取出对应的用户名
							node.approverNames = idsArray.map(id => {
								return userMap.get(id) || id;
							});
						} else {
							node.approverNames = idsArray;
						}
					} catch (error) {
						console.error('获取用户名失败:', error);
						// 如果获取失败，使用ID作为名称
						node.approverNames = idsArray;
					}
				} else {
					node.approverNames = [];
				}
			},
			dataFormSubmit() {
				this.$refs['elForm'].validate((valid) => {
					if (valid) {
						// 验证节点配置
						if (!this.dataForm.nodes || this.dataForm.nodes.length === 0) {
							this.$message.error('至少需要配置一个审批节点');
							return;
						}
						
						// 验证每个节点
						for (let i = 0; i < this.dataForm.nodes.length; i++) {
							const node = this.dataForm.nodes[i];
							if (!node.nodeName) {
								this.$message.error(`节点${i + 1}的名称不能为空`);
								return;
							}
							if (node.approvalType != 0 && node.approvalType != 1) {
								this.$message.error(`节点${i + 1}的审批类型不能为空`);
								return;
							}
							// 验证审批人：approverIds 可能是字符串或数组
							const approverIdsArray = typeof node.approverIds === 'string' 
								? (node.approverIds ? node.approverIds.split(',').filter(id => id && id.trim()) : [])
								: (Array.isArray(node.approverIds) ? node.approverIds : []);
							if (approverIdsArray.length === 0) {
								this.$message.error(`节点${i + 1}至少需要选择一个审批人`);
								return;
							}
						}
						
						// 准备提交数据
						const submitData = {
							workflowName: this.dataForm.workflowName,
							isEnabled: this.dataForm.isEnabled,
							description: this.dataForm.description,
							nodes: this.dataForm.nodes.map(node => {
								// 将 approverIds 从字符串转换为数组
								let approverIdsArray = [];
								if (typeof node.approverIds === 'string' && node.approverIds) {
									approverIdsArray = node.approverIds.split(',').filter(id => id && id.trim());
								} else if (Array.isArray(node.approverIds)) {
									approverIdsArray = node.approverIds.filter(id => id && id.trim());
								}
								
								return {
									nodeOrder: node.nodeOrder,
									nodeName: node.nodeName,
									approvalType: node.approvalType,
									isRequired: node.isRequired || 1,
									approverIds: approverIdsArray,
									approverNames: Array.isArray(node.approverNames) ? node.approverNames : []
								};
							})
						};
						
						if (!this.dataForm.id) {
							request({
								url: `/api/Extend/LqReimbursementWorkflowConfig`,
								method: 'post',
								data: submitData,
							}).then((res) => {
								this.$message({
									message: res.msg,
									type: 'success',
									duration: 1000,
									onClose: () => {
										this.visible = false;
										this.$emit('refresh', true)
									}
								})
							})
						} else {
							request({
								url: '/api/Extend/LqReimbursementWorkflowConfig/' + this.dataForm.id,
								method: 'PUT',
								data: submitData
							}).then((res) => {
								this.$message({
									message: res.msg,
									type: 'success',
									duration: 1000,
									onClose: () => {
										this.visible = false
										this.$emit('refresh', true)
									}
								})
							})
						}
					}
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
.form-card {
	margin-top: 20px;
	.card-header {
		display: flex;
		align-items: center;
		.card-title {
			margin-left: 8px;
			font-weight: 500;
		}
	}
}
.nodes-list {
	.node-item {
		padding: 16px;
		margin-bottom: 16px;
		border: 1px solid #EBEEF5;
		border-radius: 4px;
		background-color: #FAFAFA;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.node-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16px;
			padding-bottom: 12px;
			border-bottom: 1px solid #EBEEF5;
			
			.node-order {
				font-weight: bold;
				font-size: 14px;
				color: #409EFF;
			}
		}
	}
	
	.empty-nodes {
		padding: 40px 0;
		text-align: center;
	}
}
</style>
