<template>
	<view class="process_container">
		<uni-card margin="10px" spacing="0">
			<uni-forms label-position="left" :label-width="125" :border="true">
				<uni-forms-item v-for="(item, index) in formElements" :label="item.elementName" :key="index">
					<uni-easyinput v-if="'多少小时' == item.elementName" :disabled="true" placeholder=""
						:value="diffHours"></uni-easyinput>
					<!-- 输入框 -->
					<uni-easyinput v-else-if="'0' == item.type" :disabled="'0' == item.canEdit" :placeholder="'0' == item.canEdit?'':'请输入内容'" :value="item.defaultValue"></uni-easyinput>
					<!-- 富文本输入框 -->
					<uni-easyinput v-else-if="'1' == item.type" :disabled="'0' == item.canEdit" :placeholder="'0' == item.canEdit?'':'请输入内容'" :value="item.defaultValue" type="textarea"></uni-easyinput>
					<!-- 下拉框 -->
					<picker class="picker_container" v-else-if="'2' == item.type" @change="bindPickerChange($event, item)" :value="item.defaultValue" :range="formatDict(item.typeDetail.enum)">
						<view class="uni-input input_text">
						<!-- 设置默认值为第一个选项 -->
						{{ item.defaultValue ? item.defaultValue:item.defaultValue = item.typeDetail.enum[0].enumVname }}
						</view>
					</picker>
					<!-- 开始时间选择器 -->
					<uni-datetime-picker :end="endTime" @change="setTimeRange(item)"
						v-else-if="timeFlag && '9' == item.type && '开始时间' == item.elementName" v-model="item.defaultValue"
						:clear-icon="false" type="datetime" />
					<!-- 结束时间选择器 -->
					<uni-datetime-picker :start="startTime" @change="setTimeRange(item)" :disabled="disableEndTime"
						:placeholder="disableEndTime ? '请先确认开始时间' : '确认结束时间'"
						v-else-if="timeFlag && '9' == item.type && '结束时间' == item.elementName" v-model="item.defaultValue"
						:clear-icon="false" type="datetime" />
					<!-- 其他时间选择器 -->
					<!-- 年月日 时分秒 -->
					<uni-datetime-picker v-else-if="'9' == item.type" v-model="item.defaultValue" type="datetime" />
					<!-- 年月日 -->
					<uni-datetime-picker v-else-if="'3' == item.type" v-model="item.defaultValue" type="date" />
				</uni-forms-item>
			</uni-forms>
		</uni-card>
		<uni-card title="上传附件" :extra="`${fileList.length}/15`" margin="10px" spacing="0">
			<uni-file-picker 
				ref="filePicker" 
				:value="fileList" 
				:auto-upload="true" 
				mode="list" limit="10" 
				file-mediatype="all"
				@select="handleFileSelect" 
				@progress="handleFileProgress" 
				@success="handleFileSuccess" 
				@fail="handleFileFail" 
				@delete="handleFileDelete"
			/>
			<button :loading="!button_state" type="default" class="submit_button" @click="submitProcess">提交</button>
		</uni-card>
	</view>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user.js'
import $modal from '@/plugins/modal.js'
import $tab from '@/plugins/tab.js'
import { getProcessInfo, getProcessForm, submitProcessForm, uploadFiles } from '@/api/work.js'

let processInfo = reactive({
	modelName: '流程申请',
	control: '',
	formId: '',
	modelId: '',
	tmodelId: '',
	isMoreIns: '',
	pathJudgeType: '',
	form: []
})
const userStore = useUserStore()
const title = ref('')
onLoad((options) => {
	const { modelName, modelId, control } = options
	processInfo.modelName = modelName
	processInfo.modelId = modelId
	processInfo.control = control
	title.value = userStore.user.name + '的' + processInfo.modelName
	// 设置导航栏标题
	uni.setNavigationBarTitle({
		title: title.value
	});
})

onMounted(() => {
	initProcessInfo().then(() => {
		initProcessForm()
	})
})

function initProcessInfo() {
	return new Promise<void>((resolve, reject) => {
		getProcessInfo(processInfo)
			.then(({ returnParams }) => {
				const { formId, tmodelId, isMoreIns, pathJudgeType } = returnParams.flow[0]
				processInfo.formId = formId
				processInfo.tmodelId = tmodelId
				processInfo.isMoreIns = isMoreIns
				processInfo.pathJudgeType = pathJudgeType
				resolve()
			})
	})
}
// 下拉框
function bindPickerChange(e, item) {
	const index = e.detail.value;
	item.defaultValue = item.typeDetail.enum[index].enumVname
}
function formatDict(dict) {
	return dict.map(({enumVname}) => enumVname)
}

const formElements = ref([])
const startEleIndex = ref(0) // 开始时间
const endEleIndex = ref(0) // 结束时间
function initProcessForm() {
	getProcessForm(userStore.user, processInfo).then(({ returnParams }) => {
		formElements.value = returnParams.formElements

		startEleIndex.value = formElements.value.findIndex((item) => '开始时间' == item.elementName)
		endEleIndex.value = formElements.value.findIndex((item) => '结束时间' == item.elementName)
		// console.log('startEle', startEleIndex.value);
		// console.log('endEle', endEleIndex.value);
		if (startEleIndex.value != -1 && endEleIndex.value != -1) { // 判断是否需要计算时间差
			// console.log('if (startEleIndex && endEleIndex)');
			timeFlag.value = true
			disableEndTime.value = true // 计算时间差时默认禁用结束时间选择器
			formElements.value[startEleIndex.value].defaultValue = new Date()
		}
	})
}

const startTime = ref(0) // 开始时间
const endTime = ref(0) // 结束时间
const diffHours = ref(' ') // 时间差
const timeFlag = ref(false) // 是否计算时间差
const disableEndTime = ref(false) // 禁用 结束时间选择器
function setTimeRange(e) {
	if (timeFlag.value && '开始时间' == e.elementName) {
		startTime.value = e.defaultValue // 设置 开始时间
		disableEndTime.value = false // 解除 结束时间选择器 禁用
	}
	if (timeFlag.value && '结束时间' == e.elementName) {
		endTime.value = e.defaultValue // 设置 结束时间
	}
	if (timeFlag.value && startTime.value && endTime.value) {
		const start = new Date(startTime.value).getTime() // 获取  开始时间 时间戳
		const end = new Date(endTime.value).getTime() // 获取  结束时间 时间戳
		const diffSec = Math.abs(end - start) // 获取 时间戳 差值
		diffHours.value = (diffSec / 1000 / 60 / 60).toFixed(2) // 计算 时间差值 并格式化 为只有2位小数
	}
}

const uploadFileConfig = ref({
	maxCount: 10,
	uploadType: "file",
	hostUrl: "",
	autoUpload: false
})
const fileList = ref([]) // 文件列表
const fileSeqs = ref([]) // 文件上传返回 seq 列表
const filePicker = ref(null)
function handleFileSelect(file) { // 新增文件
	console.log('handleFileSelect', file)
	console.log('handleFileProgress', file)
	const data = {
		name: file.tempFiles[0].name,
		files: file.tempFiles[0].file.path,
	}
	uploadFiles(data)
	.then(res => {
		fileSeqs.value.push(res.returnParams)
		let newFile = file.tempFiles[0]
		newFile.seq = res.returnParams
		fileList.value.push(newFile)
	})
	.catch(err => {
		if (err == -20201) {
			console.log('文件上传失败 返回值不是JSON字符串');
		}
	})
}
function handleFileProgress(file, progress) {
	console.log('handleFileProgress', file, progress);
	
}
function handleFileSuccess(file, res) {
	console.log('handleFileSuccess', file, res);
}
function handleFileFail(file, err) {
	console.log('handleFileFail', file, err);
}
function handleFileDelete(file, index) { // 移除文件
	console.log('handleDelete', file)
	fileList.value.splice(fileList.value.indexOf(file.tempFiles), 1)
	fileSeqs.value.splice(index, 1)
}

const button_state = ref(true)
function submitProcess() { // 提交表单
	// 禁用提交按钮
	button_state.value = false
	// 保存表单数据
	processInfo.form = formElements.value.map(({tableField, defaultValue}) => {
		return { name: tableField, value: defaultValue }
	})
	console.log('submitProcessForm', processInfo.form);
	console.log('fileList', fileList.value);
	console.log('fileSeqs', fileSeqs.value);
	console.log('filePicker', filePicker.value);
	button_state.value = true
	submitProcessForm(userStore.user, processInfo, fileSeqs.value).then(res => {
		console.log('submitProcessForm', res);
		if (res.returnMsg.includes('提交失败')) {
			// 启用提交按钮
			button_state.value = true
			$modal.msgError(res.returnMsg)
		} else {
			$modal.msgSuccess(res.returnMsg)
			// 返回上一页
			$tab.navigateBack();
		}
	})
}
</script>

<style lang="scss">
.process_container {
	.picker_container {
		border: 1px solid #e5e5e5;
		background-color: #fff;
    border-radius: 4px;
    // box-sizing: border-box;
		.input_text{
			color: #333;
			font-size: 14px;
			line-height: 35px;
			height: 35px;
			padding: 0 0 0 10px;
		}
	}
	.is-disabled {
		color: #666 !important;
	}
	.submit_button {
		background-color: #007aff !important;
		color: #fff !important;
	}
}
</style>