<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">
			<!-- 当前节点 -->
			<uni-forms-item label="当前节点" class="form-item">
				<uni-tag :inverted="true" type="primary" :text="taskName"></uni-tag>
			</uni-forms-item>

			<!-- 流程发起人 -->
			<uni-forms-item label="填报人" class="form-item">
				<uni-tag :inverted="true" type="primary" :text="startUserName"></uni-tag>
			</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">
				<!-- <ProjectPicker v-model="formData.projectId" placeholder="请选择项目" :labelKey="'projectName'"
					:valueKey="'projectId'" @change="handleProjectChange"
					:customStyle="{ borderColor: '#e5e5e5', borderRadius: '8px' }" v-if="taskName == '工作填报'" /> -->
				<!-- <ProjectInfo :project="projectObj" v-else></ProjectInfo> -->
				<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="uni-input">
						<uni-easyinput type="text" :disabled="taskName != '工作填报'" v-model="formData.workItem"
							@click="showType = true" placeholder="请选择" :styles="inputStyle" />
					</view>
				</picker>
			</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 == '填报人确认'">
				</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>
			<!-- 提交按钮 -->
			<button class="save-btn" @click="save">保存</button>
			<button class="submit-btn margin-top-xs" type="primary" @click="submitForm">提交</button>
		</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";
export default {
	components: {
		ProjectPicker,
		ProjectInfo
	},
	props: {
		taskForm: Object,
		taskName: String, // 当前节点
		startUserName: String, // 流程发起人
	},
	created() {
		this.getProjectList();
		this.initForm();
		if (this.taskName != '工作填报') {
			this.isScatteredOptions.map(item => item.disable = true)
		}
		uni.setNavigationBarTitle({
			title: '工作填报'
		});
	},
	data() {
		return {
			openProject: false,
			selectedProject: null,
			isScattered: 0,
			formData: {
				userId: null,
				projectId: '',
				workType: '',
				workItem: '',
				workContent: '',
				workLoad: '',
				price: 216,
				submitTime: '',
				coefficient: undefined,
			},
			money: '',
			rules: {
				projectId: {
					rules: [{
						required: true,
						errorMessage: '请选择项目',
					},]
				},
				workType: {
					rules: [{
						required: true,
						errorMessage: '请选择工作类别',
					},]
				},
				workItem: {
					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'
			},
			showType: false,
			workTypeColumns: [{
				text: '外业',
				value: '外业',
			},
			{
				text: '内业',
				value: '内业'
			}
			],
			workItemList: [],
			hasForm: false,
			show: false,
		};
	},
	methods: {
		handleConfirm(project) {
			console.log('选中的项目:', project);
			this.selectedProject = project;
			this.projectObj = project;
		},
		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 (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);
					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() {
			console.log(this.formData);
			let result = Number(this.formData.price) * Number(this.formData.workLoad) * Number(this.formData.coefficient)
			console.log(result);
			this.money = result.toFixed(2)
		},
		async save() {
			if (!this.isScattered) {
				this.formData.projectId = this.projectObj.projectId;
			} else {
				this.formData.projectId = ''
			}
			if (this.hasForm) {
				let updateRes = await updateDeclare(this.formData);
			} else {
				this.formData.formId = this.taskForm.formId;
				let addRes = await addDeclare(this.formData);
				if (addRes.code == 200) {
					this.hasForm = true;
				} else {
					this.hasForm = false;
				}
			}
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			});
		},
		submitForm() {
			this.$refs.form.validate().then(res => {
				console.log('表单数据信息：', res);
				console.log(this.taskForm);
				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);
			})
		},
		confirmSubmit() {
			if (this.taskName == '工作填报') {
				this.declareSubmit();
			} else if (this.taskName == '项目负责人审核' || this.taskName == '部门负责人审核') {
				this.approveForm();
			} else {
				this.confirmForm();
			}
		},
		async declareSubmit() {
			if (this.isScattered == 0) {
				let approval = this.projectObj.projectLeader;
				this.taskForm.variables.approval = approval
			} else {
				let resData = await getUsersDeptLeader({ userId: this.form.userId });
				if (resData.data) {
					this.taskForm.variables.approval = resData.data.userId
					this.taskForm.variables.skip = true;
				}
			}
			if (this.hasForm) {
				updateDeclare(this.formData);
			} else {
				this.formData.formId = this.taskForm.formId;
				addDeclare(this.formData);
			}
			this.handleComplete(this.taskForm);
		},
		async approveForm() {
			if (this.taskName == '项目负责人审核') {
				this.formData.checkStatus = '1';
				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';
				updateDeclare(this.formData);
				this.taskForm.variables.approval = this.formData.userId;
				this.handleComplete(this.taskForm);
			}
		},
		confirmForm() {
			this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
				this.formData.confirmStatus = '1';
				updateDeclare(this.formData);
				this.handleComplete(this.taskForm);
			})
		},
		handleComplete(taskForm) {
			const params = { taskId: this.taskForm.taskId };
			getNextFlowNode(params).then(() => {
				complete(taskForm).then(response => {
					uni.showToast({
						title: response.msg,
						icon: 'success'
					});
					setTimeout(() => {
						this.$emit('goBack')
					}, 500);
				})
			})

		},
	}
};
</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;

	/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;
}
</style>