<template>
	<view class="form-container">
		<!-- 表单标题 -->
		<view class="form-title">
			<text class="title-text">工作填报</text>
			<view class="title-line"></view>
		</view>
		<!-- 表单内容 -->
		<uni-forms ref="form" :modelValue="formData" :rules="rules" label-position="top" label-width="150"
			class="custom-form">
			<flow-note :taskForm="taskForm"></flow-note>
			<!-- 当前节点 -->
			<uni-forms-item label="当前节点" class="form-item" v-if="taskName">
				<uni-tag :inverted="true" type="primary" :text="taskName"></uni-tag>
			</uni-forms-item>

			<!-- 流程发起人 -->
			<uni-forms-item label="填报人" class="form-item">
				<b style="font-size:30rpx;">{{ applierUserName }}</b>
			</uni-forms-item>

			<!-- 填报日期 -->
			<uni-forms-item label="填报日期" class="form-item">
				<text>{{ formData.submitTime }}</text>
			</uni-forms-item>
			<!-- 是否零星项目 -->
			<uni-forms-item label="是否零星项目" class="form-item" name="isScattered">
				<uni-data-checkbox v-model="isScattered" :localdata="isScatteredOptions"></uni-data-checkbox>
			</uni-forms-item>

			<!-- 选择项目 -->
			<uni-forms-item label="选择项目" required class="form-item" v-if="!isScattered" name="projectId">
				<u-button type="primary" @click="openProject = true" v-if="taskName == '工作填报'">选择项目</u-button>
				<ProjectPicker :visible.sync="openProject" :selected.sync="selectedProject" @confirm="handleConfirm" />
				<ProjectInfo :project="projectObj"></ProjectInfo>
			</uni-forms-item>

			<!-- 工作类别 -->
			<uni-forms-item label="工作类别" required class="form-item" name="workType">
				<uni-data-select :disabled="taskName != '工作填报'" :clear="taskName == '工作填报'" v-model="formData.workType"
					:localdata="workTypeColumns" @change="bindWorkTypeChange"></uni-data-select>
			</uni-forms-item>

			<!-- 工作细项 -->
			<uni-forms-item label="工作细项" required class="form-item" name="workItem">
				<picker @change="bindWorkItemChange" :value="formData.workItem" :range="workItemList"
					:disabled="taskName != '工作填报'">
					<view class="picker-selector" :class="{ 'picker-disabled': taskName != '工作填报' }">
						<text class="picker-text" :class="{ 'picker-placeholder': !formData.workItem }">
							{{ formData.workItem || '请选择' }}
						</text>
						<uni-icons type="arrowdown" size="16" color="#c0c4cc"></uni-icons>
					</view>
				</picker>
			</uni-forms-item>

			<!-- 工作日期 -->
			<uni-forms-item label="工作日期" required class="form-item" name="beginDate">
				<uni-datetime-picker v-if="taskName == '工作填报'" type="daterange" v-model="dateRange" start-placeholder="开始日期"
					end-placeholder="结束日期" range-separator="至" return-type="string" @change="handleDateRangeChange" :border="true"
					:clear-icon="true" />
				<view v-else class="date-display">
					<text class="date-text">{{ formatDateRange() }}</text>
				</view>
			</uni-forms-item>

			<!-- 具体内容 -->
			<uni-forms-item label="具体内容" required class="form-item" name="workContent">
				<uni-easyinput :disabled="taskName != '工作填报'" type="textarea" v-model="formData.workContent"
					placeholder="请输入具体工作内容" :styles="textareaStyle" />
			</uni-forms-item>

			<!-- 工天 -->
			<uni-forms-item label="工天" required class="form-item" name="workLoad">
				<uni-easyinput :disabled="taskName != '工作填报'" type="number" v-model="formData.workLoad" placeholder="请输入工天"
					:styles="inputStyle">
					<text slot="right" class="unit">天</text>
				</uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="系数" required class="form-item" name="coefficient" v-if="taskName != '工作填报'">
				<uni-easyinput type="number" v-model="formData.coefficient" placeholder="请输入系数" :styles="inputStyle"
					@blur="countMoney" @clear="countMoney" :disabled="!taskName || taskName == '填报人确认'">
				</uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="工天单价" class="form-item" v-if="taskName != '工作填报'">
				<u-tag :text="formData.price + '/人天'" type="success" plain></u-tag>
			</uni-forms-item>

			<uni-forms-item label="预估绩效" class="form-item" v-if="taskName != '工作填报'">
				<u-tag :text="'¥' + money" type="primary" plain></u-tag>
			</uni-forms-item>
			<!-- 提交按钮 -->
			<view v-if="taskName">
				<button class="save-btn" @click="save">保存</button>
				<button class="submit-btn margin-top-xs" type="primary" @click="submitForm"
					v-if="taskName == '工作填报'">提交</button>
				<button class="submit-btn margin-top-xs" type="primary" @click="submitForm" v-else>确认审核</button>
			</view>
		</uni-forms>

		<uv-modal ref="popModal" title="提示" content='是否提交表单？' :showCancelButton="true" @confirm="confirmSubmit"></uv-modal>
	</view>
</template>

<script>
import ProjectPicker from '@/pages/components/ProjectPicker.vue';
import ProjectInfo from '@/pages/components/ProjectInfo.vue';
import { listPrice, getWorkTypeList, getWorkItemList } from '@/api/oa/price/price'
import { listProject, submitProject, modifyProject, delProject } from "@/api/oa/project/project";
import { listDeclare, getDeclare, addDeclare, updateDeclare } from '@/api/oa/declare/declare';
import { parseTime } from "@/utils/common.js"
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { getUsersDeptLeader, getUsersDeptLeaderByDept, getUsersManageLeaderByDept } from "@/api/system/post.js";
import FlowNote from '@/pages/components/flowNote.vue';
export default {
	components: {
		ProjectPicker,
		ProjectInfo,
		FlowNote
	},
	props: {
		taskForm: Object,
		taskName: String, // 当前节点
		startUserName: String, // 流程发起人
	},
	created() {
		this.applierUserName = this.startUserName;
		this.getProjectList();
		this.initForm();
		if (this.taskName != '工作填报') {
			this.isScatteredOptions.map(item => item.disable = true)
		}
		uni.setNavigationBarTitle({
			title: '工作填报'
		});
	},
	data() {
		return {
			applierUserName: '',
			openProject: false,
			selectedProject: null,
			isScattered: 0,
			formData: {
				userId: null,
				projectId: '',
				workType: '',
				workItem: '',
				beginDate: '',
				endDate: '',
				workContent: '',
				workLoad: '',
				price: 200,
				submitTime: '',
				coefficient: undefined,
			},
			money: '',
			rules: {
				projectId: {
					rules: [{
						required: true,
						errorMessage: '请选择项目',
					},]
				},
				workType: {
					rules: [{
						required: true,
						errorMessage: '请选择工作类别',
					},]
				},
				workItem: {
					rules: [{
						required: true,
						errorMessage: '请选择工作细项',
					},]
				},
				beginDate: {
					rules: [{
						required: true,
						errorMessage: '请选择开始日期',
					},]
				},
				endDate: {
					rules: [{
						required: true,
						errorMessage: '请选择结束日期',
					},]
				},
				workContent: {
					rules: [{
						required: true,
						errorMessage: '请输入具体内容',
					},]
				},
				workLoad: {
					rules: [{
						required: true,
						errorMessage: '请输入工天',
					},]
				},
				coefficient: {
					rules: [{
						required: true,
						errorMessage: '请输入系数',
					},]
				}
			},
			projectObj: {},
			isScatteredOptions: [{
				text: '否',
				value: 0,
				disable: false
			}, {
				text: '是',
				value: 1,
				disable: false
			}],
			projects: [],
			projectIndex: -1,
			inputStyle: {
				borderColor: '#e5e5e5',
				borderRadius: '8px'
			},
			textareaStyle: {
				borderColor: '#e5e5e5',
				borderRadius: '8px',
				height: '100px'
			},

			workTypeColumns: [{
				text: '外业',
				value: '外业',
			},
			{
				text: '内业',
				value: '内业'
			}
			],
			workItemList: [],
			hasForm: false,
			show: false,
			isSubmitting: false, // 提交状态
		};
	},
	computed: {
		dateRange: {
			get() {
				if (this.formData.beginDate && this.formData.endDate) {
					return [this.formData.beginDate, this.formData.endDate];
				}
				return [];
			},
			set(value) {
				if (value && value.length === 2) {
					this.formData.beginDate = value[0];
					this.formData.endDate = value[1];
				} else {
					this.formData.beginDate = '';
					this.formData.endDate = '';
				}
			}
		}
	},
	methods: {
		handleConfirm(project) {
			this.selectedProject = project;
			this.projectObj = project;
			// 同时设置formData中的projectId，避免表单验证失败
			this.formData.projectId = project.projectId;
		},
		initForm() {
			if (this.taskName == '工作填报') {
				this.formData.submitTime = parseTime(new Date(), "{y}-{m}-{d}");
				this.formData.userId = this.$store.getters.userId;
			}
			getDeclare(this.taskForm.formId).then(res => {
				if (res.data) {
					this.hasForm = true;
					this.formData = res.data;
					if (!this.applierUserName) {
						this.applierUserName = this.formData.user.nickName;
					}
					if (res.data.projectId) {
						this.isScattered = 0;
					} else {
						this.isScattered = 1;
					}
					res.data.project.projectLeader = res.data.projectLeader
					this.projectObj = res.data.project;
					this.selectedProject = res.data.project;
					this.bindWorkTypeChange(this.formData.workType);

					// 处理日期范围和工天的关系
					if (!this.formData.beginDate) {
						this.formData.beginDate = '';
					}
					if (!this.formData.endDate) {
						this.formData.endDate = '';
					}
					if (this.formData.beginDate && this.formData.endDate) {
						// 如果有日期范围，计算建议工天数但不覆盖现有值
						this.calculateWorkDays();
					}

					this.countMoney();
				} else {
					this.hasForm = false;
				}
			})
		},
		bindProjectChange(e) {
			this.projectIndex = e.detail.value;
			this.formData.project = this.projects[this.projectIndex];
		},
		bindWorkTypeChange(e) {
			listPrice({
				workType: e,
				pageNum: 1,
				pageSize: 9999
			}).then(res => {
				if (res.code == 200) {
					let data = res.rows;
					let list = [];
					for (let d of data) {
						list.push(d.workItem)
					}
					if (e == '内业') {
						list.push('其他')
					}
					this.workItemList = [...new Set(list)];
				}
			})
		},
		bindWorkItemChange(e) {
			this.formData.workItem = this.workItemList[e.detail.value];
		},
		handleRadioChange(e) {
			this.formData.isScattered = e.detail.value;
		},
		handleProjectChange(row) {

		},
		getProjectList() {
			listProject({
				pageNum: 1,
				pageSize: 10
			}).then(res => {
				this.projects = res.rows
			})
		},
		countMoney() {
			let result = Number(this.formData.price) * Number(this.formData.workLoad) * Number(this.formData.coefficient)
			this.money = result.toFixed(2)
		},
		handleDateRangeChange(range) {
			this.dateRange = range;
			this.calculateWorkDays();
		},
		calculateWorkDays() {
			if (!this.formData.beginDate || !this.formData.endDate) {
				return;
			}

			const startDate = new Date(this.formData.beginDate);
			const endDate = new Date(this.formData.endDate);

			if (startDate && endDate && startDate <= endDate) {
				// 计算日期差（包含开始和结束日期）
				const timeDiff = endDate.getTime() - startDate.getTime();
				const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;

				// 直接设置工天
				this.formData.workLoad = daysDiff;
			}
		},

		formatDateRange() {
			if (this.formData.beginDate && this.formData.endDate) {
				const beginDate = this.formData.beginDate.split(' ')[0]; // 只取日期部分，去掉时间
				const endDate = this.formData.endDate.split(' ')[0];
				return `${beginDate} 到 ${endDate}`;
			}
			return '未选择日期';
		},
		async save(showToast = true) {
			try {
				if (!this.isScattered) {
					this.formData.projectId = this.projectObj.projectId;
				} else {
					this.formData.projectId = ''
				}

				let result;
				if (this.hasForm) {
					result = await updateDeclare(this.formData);
				} else {
					this.formData.formId = this.taskForm.formId;
					result = await addDeclare(this.formData);
					if (result.code == 200) {
						this.hasForm = true;
					} else {
						this.hasForm = false;
					}
				}

				if (result && result.code === 200) {
					if (showToast) {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
					}
					return Promise.resolve(result);
				} else {
					throw new Error(result?.msg || '保存失败');
				}
			} catch (error) {
				console.error('保存失败:', error);
				if (showToast) {
					uni.showToast({
						title: error.message || '保存失败',
						icon: 'error'
					});
				}
				return Promise.reject(error);
			}
		},
		submitForm() {
			// 在表单验证前确保projectId被正确设置
			if (!this.isScattered && this.projectObj && this.projectObj.projectId) {
				this.formData.projectId = this.projectObj.projectId;
			} else if (this.isScattered) {
				this.formData.projectId = '';
			}

			this.$refs.form.validate().then(res => {
				this.taskForm.variables.skip = false;
				if (!this.projectObj.projectLeader) {
					if (this.isScattered == 0) {
						this.$message.error('该项目未指定项目负责人，无法提交。')
						return
					}
				}
				this.$refs.popModal.open();
			}).catch(err => {
				console.log('表单错误信息：', err);
			})
		},
		async confirmSubmit() {
			if (this.isSubmitting) return; // 防止重复提交

			try {
				this.isSubmitting = true;

				// 显示保存中提示
				uni.showLoading({
					title: '正在保存...'
				});

				// 先保存表单，不显示保存成功提示
				await this.save(false);

				uni.hideLoading();

				if (this.taskName != '填报人确认') {
					// 显示提交中提示
					uni.showLoading({
						title: '正在提交...'
					});
				}

				// 保存成功后执行相应的提交流程
				if (this.taskName == '工作填报') {
					await this.declareSubmit();
				} else if (this.taskName == '项目负责人审核' || this.taskName == '部门负责人审核') {
					await this.approveForm();
				} else {
					await this.confirmForm();
				}
			} catch (error) {
				console.error('保存失败，无法提交:', error);
				uni.hideLoading();
				uni.showToast({
					title: '保存失败，请重试',
					icon: 'error'
				});
			} finally {
				this.isSubmitting = false;
			}
		},
		async declareSubmit() {
			if (this.isScattered == 0) {
				let approval = this.projectObj.projectLeader;
				this.taskForm.variables.approval = approval
			} else {
				let resData = await getUsersDeptLeader({
					userId: this.formData.userId
				});
				if (resData.data) {
					this.taskForm.variables.approval = resData.data.userId
					this.taskForm.variables.skip = true;
				}
			}
			// 数据已在confirmSubmit中保存，直接进行流程提交
			this.handleComplete(this.taskForm);
		},
		async approveForm() {
			if (this.taskName == '项目负责人审核') {
				this.formData.checkStatus = '1';
				// 更新状态后需要再次保存
				await updateDeclare(this.formData);
				let resData = await getUsersDeptLeader({
					userId: this.formData.userId
				});
				if (resData.data) {
					this.taskForm.variables.approval = resData.data.userId;
					this.handleComplete(this.taskForm);
				}
			} else if (this.taskName == '部门负责人审核') {
				this.formData.checkStatus = '1';
				this.formData.auditStatus = '1';
				// 更新状态后需要再次保存
				await updateDeclare(this.formData);
				this.taskForm.variables.approval = this.formData.userId;
				this.handleComplete(this.taskForm);
			}
		},
		confirmForm() {
			return this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(async () => {
				this.formData.confirmStatus = '1';
				// 更新确认状态后需要再次保存
				await updateDeclare(this.formData);
				this.handleComplete(this.taskForm);
			})
		},
		handleComplete(taskForm) {
			const params = {
				taskId: this.taskForm.taskId
			};
			getNextFlowNode(params).then(() => {
				complete(taskForm).then(response => {
					uni.hideLoading(); // 隐藏loading
					uni.showToast({
						title: response.msg,
						icon: 'success'
					});
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/message/index'
						})
					}, 500);
				}).catch(error => {
					uni.hideLoading(); // 隐藏loading
					console.error('提交失败:', error);
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'error'
					});
				})
			}).catch(error => {
				uni.hideLoading(); // 隐藏loading
				console.error('获取下一节点失败:', error);
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'error'
				});
			})
		},
	}
};
</script>

<style lang="scss" scoped>
.form-container {
	padding: 20px;
	background-color: #f8f8f8;
}

.form-title {
	margin-bottom: 15px;
	text-align: center;

	.title-text {
		font-size: 20px;
		font-weight: bold;
		color: #333;
	}

	.title-line {
		width: 50px;
		height: 2px;
		background-color: #007AFF;
		margin: 8px auto;
	}
}

.custom-form {
	background-color: #fff;
	padding: 15px;
	border-radius: 12px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.form-item {
	margin-bottom: 20px;

	::v-deep .uni-forms-item__label {
		font-weight: 500;
		color: #666;
		padding-bottom: 8px;
	}
}

.picker {
	width: 100%;
	padding: 10px;
	border: 1px solid #e5e5e5;
	border-radius: 8px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	color: #333;
}

.radio-label {
	margin-right: 25px;
	display: inline-flex;
	align-items: center;
}

.unit {
	color: #999;
	padding: 0 10px;
}



.date-display {
	padding: 10px;
	border: 1px solid #e5e5e5;
	border-radius: 8px;
	background-color: #f7f6f6;
	min-height: 44px;
	display: flex;
	align-items: center;
}

.date-text {
	font-size: 14px;
	color: #333333;
	line-height: 1.4;
}

.picker-selector {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10px;
	border: 1px solid #e5e5e5;
	border-radius: 8px;
	background-color: #fff;
	min-height: 44px;
	box-sizing: border-box;
}

.picker-selector.picker-disabled {
	background-color: #f7f6f6;
	color: #333333;
}

.picker-text {
	flex: 1;
	font-size: 14px;
	color: #333;
	line-height: 1.4;
}

.picker-text.picker-placeholder {
	color: #c0c4cc;
}
</style>