<template>
	<view class="process_detail_container">
		<uni-card>
			<view class="main_container">
				<uni-section titleFontSize="1.3rem" title="申请内容" type="line"></uni-section>
				<uni-list>
					<uni-list-item v-for="(elem, index) in formElements" :key="index">
						<template v-slot:header>
							<text class="element_name">{{ elem.elementName }}</text>
						</template>
						<template v-slot:footer>
							<view class="element_value">
								<view v-if="elem.canEdit == '1'" class="element_value">
									<uni-easyinput v-if="'1' == elem.type" placeholder="请输入内容"
										v-model="elem.defaultValue" type="textarea"></uni-easyinput>
								</view>
								<text v-else>{{ elem.defaultValue }}</text>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</view>
		</uni-card>
		<view>
			<!-- 重复表 -->
			<uni-card v-if="repeatingFormNotEmpty" spacing="0" padding="0">
				<button @click="handlerepeatingForm" type="primary">查看重复表</button>
			</uni-card>
			<uni-popup v-if="repeatingFormNotEmpty" ref="repeatingFormPopup">
				<uni-card margin="0px" spacing="0px" padding="0px">
					<view class="repeating_table_container">
						<uni-table :border="true" stripe>
							<uni-tr>
								<uni-th align="center" v-for="(item, index) in repeatingForm.elementItem" :key="index">
									{{ item.elementName.slice(3, 5) }}
								</uni-th>
							</uni-tr>
							<uni-tr
								v-for="(item, index) in (repeatingForm.elements.length / repeatingForm.elementItem.length)"
								:key="index">
								<uni-td align="center" v-for="col in repeatingForm.elementItem.length" :key="col">
									<!-- (列数 - 1) * 总行数 + 当前行数 -->
									{{ repeatingForm.elements[(col - 1) * (repeatingForm.elements.length /
										repeatingForm.elementItem.length) + index]!.defaultValue }}
								</uni-td>
							</uni-tr>
						</uni-table>
					</view>
				</uni-card>
			</uni-popup>
		</view>
		<!-- 附件 -->
		<view v-for="(item, index) in fileList" :key="index">
			<uni-card v-if="item.files.length != undefined && item.files.length > 0">
				<uni-section titleFontSize="1.3rem" title="附件" type="line"></uni-section>
				<attachment-list :attachments="item.files"></attachment-list>
			</uni-card>
		</view>
		<view>
			<uni-card>
				<view class="flow_step_container">
					<uni-section titleFontSize="1.3rem" title="流转过程" type="line"></uni-section>
					<up-steps :current="stepActive" activeColor="#18bc37" inactiveColor="#2979ff" direction="column">
						<view v-for="(step, index) in options">
							<up-steps-item v-if="step.state == 3" :title="step.title + ' 退回'" :desc="step.desc"
								:key="index" error></up-steps-item>
							<up-steps-item v-else-if="step.state == 0" :title="step.title + ' 撤销'" :desc="step.desc"
								:key="index" error></up-steps-item>
							<up-steps-item v-else-if="index == stepActive" :title="step.title" :desc="step.desc"
								:key="index">
								<template #icon>
									<view class="active_step_circle">
										<text class="active_step_text">{{ index + 1 }}</text>
									</view>
								</template>
							</up-steps-item>
							<up-steps-item v-else :title="step.title" :desc="step.desc" :key="index"></up-steps-item>
						</view>
					</up-steps>
				</view>
			</uni-card>
		</view>
		<view v-if="processInfo.tinsId">
			<view class="remark_container">
				<uni-card>
					<uni-section titleFontSize="1.3rem" title="环节备注" type="line"></uni-section>
					<view class="remark_content">
						<uni-easyinput type="textarea" autoHeight v-model="remark" placeholder="请输入"></uni-easyinput>
					</view>
				</uni-card>
			</view>
		</view>
		<view v-if="processInfo.tinsId" class="approve_button">
			<uni-card spacing="0" padding="0">
				<button :loading="!button_state" type="primary" @click="handleSubmitProcess('1')">通过</button>
			</uni-card>
		</view>
	</view>
	<view v-if="processInfo.tinsId">
		<view class="reject_button">
			<uni-card spacing="0" padding="0" :is-shadow="false" :border="false">
				<uni-row>
					<uni-col :span="11">
						<button :loading="!button_state" type="warn" @click="handleSubmitProcess('0')">退回上一级</button>
					</uni-col>
					<uni-col :span="11" :offset="2">
						<button :loading="!button_state" type="warn" @click="handleSubmitProcess('2')">退回发起人</button>
					</uni-col>
				</uni-row>
			</uni-card>
		</view>
	</view>
	<view v-else-if="processInfo.username == userStore.user.name">
		<view class="remark_container">
			<uni-card>
				<uni-section titleFontSize="1.3rem" title="撤销备注" type="line"></uni-section>
				<view class="remark_content">
					<uni-easyinput type="textarea" autoHeight v-model="remark" placeholder="请输入"></uni-easyinput>
				</view>
			</uni-card>
		</view>
		<view class="cancel_button_container">
			<uni-card spacing="0" padding="0">
				<button :loading="!button_state" type="warn" @click="handleCancelProcess">撤销</button>
			</uni-card>
		</view>
	</view>
	<view style="height: 5px; margin-top: 20px;"></view>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import attachmentList from '@/components/ygoa/attachmentList.vue'
import $tab from '@/plugins/tab.js'
import $modal from '@/plugins/modal.js'
import { getProcessFlowInfo, getProcessFormInfo, getProcessFormInfoInFlow, getProcessFlow, submitProcessFlow, cancelProcessFlow } from '@/api/process.js'
import { useUserStore } from '@/store/user.js'
const userStore = useUserStore()
const processInfo = reactive({
	insId: '',
	insName: '',
	control: 1,
	username: '',
	tinsId: undefined
})
onLoad(({ username, insId, tinsId, insName, control }) => {
	// 获取传入的标题参数
	const title = insName || '流程信息';
	processInfo.insId = insId
	processInfo.insName = insName
	processInfo.control = control
	processInfo.username = username
	if (tinsId) {
		processInfo['tinsId'] = tinsId
	}
	// 设置导航栏标题
	uni.setNavigationBarTitle({
		title: title
	});
})

onMounted(() => {
	initProcessInfo()
	initProcessFlow()
})

const repeatingForm = ref({
	elements: [],
	elementItem: [],
})
const repeatingFormNotEmpty = ref(false)
function repeatingFormHasValue() {
	if (repeatingForm.value === undefined) return
	if (repeatingForm.value.elementItem.length <= 0) return
	repeatingForm.value.elements.forEach(({ defaultValue }) => {
		if (defaultValue != "") {
			repeatingFormNotEmpty.value = true
			return new Promise((resolve, reject) => {
				resolve(repeatingFormNotEmpty)
			})
		}
	})

}
const formElements = ref([])
const formInfo = ref({
	formElements: [],
	formId: '',
	formInsId: ''
})
const fileList = ref([])
function initProcessInfo() {
	if (processInfo.tinsId) {
		getProcessFormInfoInFlow(userStore.user.useId, processInfo).then(({ returnParams }) => {
			formElements.value = returnParams.formElements
			formInfo.value = returnParams.formInfo[0]
			repeatingForm.value = returnParams.repeatingForm
			// fileList.value = returnParams.fileList
			repeatingFormHasValue()
		})
	} else {
		getProcessFormInfo(userStore.user.useId, processInfo.insId).then(({ returnParams }) => {
			formElements.value = returnParams.formElements
			repeatingForm.value = returnParams.repeatingForm
			fileList.value = returnParams.fileList
			repeatingFormHasValue()
		})
	}
}
const options = ref([])
const stepActive = ref(-1)
const flowInfo = ref({})
function initProcessFlow() {
	getProcessFlow(userStore.user.useId, processInfo).then(({ returnParams }) => {
		options.value = returnParams.list.map((item, index) => {
			const { tmodelName, name, createdate, finishdate, remark, state } = item
			if (state == 1) {
				stepActive.value = index
			}
			const title = tmodelName + (name == '' ? '' : ' ( ' + name + ' )')
			const desc = '创建时间: ' + createdate
				+ (finishdate == '' ? '\n' : '\n办理时间: ' + finishdate)
				+ (remark == '' ? '\n' : '\n环节意见: ' + remark)
			return {
				title,
				desc,
				state
			}
		})
		if (stepActive.value === -1) stepActive.value = returnParams.list.length
		// 获取未完成过程
		if (processInfo.tinsId) {
			getProcessFlowInfo(userStore.user.useId, processInfo).then(({ returnParams }) => {
				options.value.push({ title: returnParams.nextTmodels[0].nextTmodelName })
				flowInfo.value = returnParams.flow[0]
				fileList.value = [
					{ files: returnParams.flow[0].files }
				]
			})
		}
	})
}

const repeatingFormPopup = ref(null)
function handlerepeatingForm() {
	repeatingFormPopup.value.open()
}

const button_state = ref(true)
const remark = ref('')
function handleSubmitProcess(result) {
	let content = '确认退回'
	if (result == "1") {
		content = '确认通过'
	}
	$modal.confirm(content).then(() => {
		submitProcess(result)
	}).catch(() => { })
}
function submitProcess(result) {
	formInfo.value.formElements = formElements.value.map(({ tableField, defaultValue }) => {
		return {
			name: tableField,
			value: defaultValue
		}
	})
	let flow = Object.assign({}, flowInfo.value)
	flow['staffId'] = userStore.user.useId
	flow['gxId'] = userStore.user.gxId
	flow['groupId'] = flowInfo.value.groupid
	flow['fileIds'] = ''
	// result: 1通过 2退回发起人 0退回上一级
	flow['result'] = result
	flow['remark'] = remark.value
	flow['nextTmodelId'] = 'undefined'
	submitProcessFlow(flow, formInfo.value, processInfo.control).then(({ returnMsg }) => {
		if (returnMsg.includes('提交失败')) {
			// 启用提交按钮
			button_state.value = true
			$modal.msgError(returnMsg)
		} else {
			$modal.msgSuccess(returnMsg)
			// 通知列表刷新数据
			uni.$emit('ReloadProcessData');
			setTimeout(() => {
				$tab.navigateBack();
			}, 1000)
		}
	})
}

function handleCancelProcess() {
	$modal.confirm('确认撤销').then(() => {
		cancelProcess()
	}).catch(() => { })
}
function cancelProcess() {
	cancelProcessFlow(userStore.user.useId, remark.value, processInfo).then(({ returnMsg }) => {
		if (returnMsg.includes('success')) {
			$modal.msgSuccess('撤销成功')
			// 通知列表刷新数据
			uni.$emit('ReloadProcessData');
			setTimeout(() => {
				$tab.navigateBack();
			}, 1000)
		} else {
			// 启用按钮
			button_state.value = true
			$modal.msgError(returnMsg)
		}
	})
}
</script>

<style lang="scss">
.element_name {
	width: 10rem;
	font-weight: 600;
}

.element_value {
	width: 60%;
}

.uni-section {
	margin-left: -15px;
	margin-bottom: 10px;
}

.process_detail_container {
	position: relative;

	.main_container {
		min-height: 70vh;
	}

	.repeating_table_container {
		width: 98vw;

		.uni-table-scroll {
			max-height: 80vh;

			.uni-table {
				min-width: 100% !important;

				.uni-table-th {
					min-width: 50px;
					background-color: #2979ff;
					font-weight: bold;
					color: #fcfcfc;
				}
			}
		}
	}

	.flow_step_container {
		min-height: 200px;

		.u-steps {
			.u-steps-item {
				padding-bottom: 11px;

				.active_step_circle {
					width: 20px;
					height: 20px;
					box-sizing: border-box;
					flex-shrink: 0;
					border-radius: 100px;
					border-width: 1px;
					border-color: #A78BFA;
					background-color: #A78BFA;
					border-style: solid;
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: center;
					transition: background-color .3s;

					.active_step_text {
						color: #fff;
						font-size: 11px;
						display: flex;
						flex-direction: row;
						align-items: center;
						justify-content: center;
						text-align: center;
						line-height: 11px;
					}
				}
			}

			.u-steps-item view:last-of-type {
				margin-top: 0 !important;

				.u-text__value--content {
					font-size: 16px !important;
				}

				.u-text__value--main {
					font-size: 16px !important;
				}
			}
		}
	}

	.remark_container {
		.remark_content {
			margin-bottom: 10px;
		}
	}

	.approve_button {
		position: sticky;
		z-index: 999;
		width: 100%;
		bottom: 10px;
	}

	.reject_button {
		::v-deep uni-card {
			background-color: #f5f5f5;
		}
	}
}
</style>