<template>
	<!-- 左侧列表 -->
	<div class="flow-content">
		<!-- 搜索条件 -->
		<div class="search-box">
			<div class="search-segment" style="flex: 1 1 0%">
				<el-input v-model="searchParams.processName" placeholder="流程名称">
					<template #append>
						<el-button icon="Search" @click.stop="initList" />
					</template>
				</el-input>
			</div>
			<div class="search-segment">
				<el-tooltip effect="dark" content="重置" placement="top">
					<el-button icon="Refresh" @click.stop="resetSearch('external')" />
				</el-tooltip>
			</div>
			<div class="search-segment">
				<EditPopover :visible="searchMoreVisible" placement="right" :width="320" :show-footer="false">
					<template #reference>
						<el-button icon="Filter" @click="searchMoreVisible = true" />
					</template>
					<div class="title">高级筛选</div>
					<el-scrollbar max-height="400px">
						<!-- 创建人 -->
						<el-input v-model="searchParams.createBy" style="width: 240px; margin-bottom: 10px" placeholder="请输入创建人名称" clearable />
						<!-- 流程状态 -->
						<el-select v-model="searchParams.instanceState" placeholder="流程状态" style="margin-bottom: 10px; width: 240px" clearable>
							<el-option v-for="item in instanceStateOps" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
						<el-date-picker
							v-model="searchParams.beginTime"
							style="width: 240px; margin-bottom: 10px"
							type="date"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							placeholder="开始时间"
							:disabled-date="disabledDateStart"
						/>
						<el-date-picker
							v-model="searchParams.endTime"
							style="width: 240px; margin-bottom: 10px"
							type="date"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							placeholder="结束时间"
							:disabled-date="disabledDateEnd"
						/>
					</el-scrollbar>
					<div class="footer">
						<el-button plain @click="searchReset">重置</el-button>
						<el-button type="primary" plain @click="searchSubmit">检索</el-button>
					</div>
				</EditPopover>
			</div>
		</div>
		<!-- 内容值 -->
		<div v-infinite-scroll="loadList" :infinite-scroll-disabled="disabledInfinite" class="flow-list-box">
			<div
				v-for="i in listData.list"
				:key="i.instanceId"
				class="item-box"
				:class="[i.instanceId === taskProcessInfo.currentTaskRow.instanceId ? 'item-box-choosed' : '']"
				@click="getTaskDetail(i)"
			>
				<div class="flow-card-box flow-card-box-hoverable">
					<!--头部-->
					<div class="header">
						<el-text tag="b">{{ i.processName }}</el-text>
						<div>
							<el-text v-if="['pendingApproval', 'pendingClaim'].indexOf(props.currentTaskType) !== -1" style="margin-right: 15px">{{
								i.performType == 2 ? '会签' : i.performType == 3 ? '或签' : i.performType == 4 ? '票签' : ''
							}}</el-text>

							<el-tag v-if="currentTaskType === 'pendingApproval'">待审批</el-tag>
							<template v-else>
								<el-tag v-if="i.instanceState === 0">审批中</el-tag>
								<el-tag v-if="i.instanceState === 1" type="success">审批通过</el-tag>
								<el-tag v-if="i.instanceState === 2" type="danger">审批拒绝</el-tag>
								<el-tag v-if="i.instanceState === 3" type="warning">撤销审批</el-tag>
								<el-tag v-if="i.instanceState === 4" type="danger">超时结束</el-tag>
								<el-tag v-if="i.instanceState === 5" type="danger">强制终止</el-tag>
							</template>
						</div>
					</div>
					<!--操作类容-->
					<div class="summary-list">
						<template v-if="['myReceived', 'myApplication', 'approved'].indexOf(currentTaskType) !== -1">
							<div v-if="i.endTime" class="summary-item">
								<div class="label">结束时间：</div>
								<div class="value">{{ i.endTime }}</div>
							</div>
							<div v-if="i.duration" class="summary-item">
								<div class="label">处理耗时：</div>
								<div class="value">{{ format_milliseconds(i.duration) }}</div>
							</div>
						</template>

						<div v-if="i.currentNode !== 'complete'" class="summary-item">
							<div class="label">当前所在节点：</div>
							<div class="value">{{ i.currentNode }}</div>
						</div>
					</div>
					<!--底部-->
					<div class="footer">
						<!-- 头像 -->
						<div class="initiator">
							<FlowNodeAvatar :name="i.createBy" />
						</div>
						<!-- 时间 -->
						<div class="begin-time">提交于 {{ i.createTime }}</div>
					</div>
				</div>
			</div>
			<div v-if="loading" class="flow-bottom-txt">加载中...</div>
			<div v-if="noMore" class="flow-bottom-txt no-more">没有更多了</div>
		</div>
	</div>
</template>

<script setup>
import useTaskProcessStore from '@/store/modules/taskProcess'
import FlowNodeAvatar from '@/components/Flow/FlowNodeAvatar.vue'
// import { Search, Filter, Refresh } from '@element-plus/icons-vue'
import EditPopover from '@/components/EditPopover.vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { format_milliseconds } from '@/utils'
import {
	processTaskPagePendingApprovalApi,
	processTaskPageMyApplicationApi,
	processTaskPagePendingClaimApi,
	processTaskPageApprovedApi,
	processTaskPageMyReceivedApi
} from '@/api/flow/processTask'

const props = defineProps({
	/**
	 * pendingApproval 待审批
	 * myApplication 我的申请
	 * myReceived 我收到的
	 * pendingClaim 认领任务
	 * approved 已审批
	 */
	currentTaskType: {
		type: String,
		default: ''
	}
})

/***
 * 待审批：发起人 流程分组 最小提交时间 最大提交时间
 * 我的申请：流程分组 流程状态 最小提交时间 最大提交时间 最小完成时间 最大完成时间
 * 我收到的：发起人 流程分组 流程状态 最小提交时间 最大提交时间 最小完成时间 最大完成时间
 * 已审批：发起人 流程分组 流程状态 最小提交时间 最大提交时间 最小完成时间 最大完成时间
 */
const instanceStateOps = [
	{
		value: 0,
		label: '审批中'
	},
	{
		value: 1,
		label: '审批通过'
	},
	{
		value: 2,
		label: '审批拒绝'
	},
	{
		value: 3,
		label: '撤销审批'
	},
	{
		value: 4,
		label: '超时结束'
	},
	{
		value: 5,
		label: '强制终止'
	}
]
// const processName = ref('') // 流程名称
// const createId = ref(null) // 发起人
// const createBy = ref(null) // 创建人
// const instanceState = ref(null) // 流程状态
// const beginTime = ref(null) // 开始时间
// const endTime = ref(null) // 结束时间
const searchMoreVisible = ref(false)

// store值
const taskProcessInfo = useTaskProcessStore()
// 下拉滚动属性值 start
const loading = ref(false) // loading
// const totalNumber = ref(0) // 总条数
// const totalPages = ref(0) // 总页数
// 当前页码数和每页条数
const condition = reactive({
	page: 1,
	pageSize: 10
})
const _searchInit = {
	// 流程名称
	processName: undefined,
	// 发起人
	createId: undefined,
	// 创建人
	createBy: undefined,
	// 流程状态
	instanceState: undefined,
	// 开始时间
	beginTime: undefined,
	// 结束时间
	endTime: undefined
}
const searchParams = reactive({ ..._searchInit })
const listData = ref({
	list: [],
	total: 0,
	page: 0
})
const list = ref([]) // 列表数据
// 下拉滚动属性值 end

// 搜索条件更多重置
const searchReset = () => {
	// createBy.value = undefined
	// instanceState.value = undefined
	// beginTime.value = undefined
	// endTime.value = undefined
	Object.assign(searchParams, { ..._searchInit })
	// searchMoreVisible.value = false
}

// 搜索条件更多
const searchSubmit = () => {
	condition.page = 1
	searchMoreVisible.value = false
	getPagedSatellites(true)
}

// 初始化
const initList = () => {
	loading.value = false
	condition.page = 1
	// list.value = []
	// totalNumber.value = 0
	// totalPages.value = 0
	listData.value = {
		list: [],
		total: 0,
		page: 0
	}
	taskProcessInfo.refresh = false
	loadList()
}

// 分页获取数据
const loadList = () => {
	// if (loading.value) return false
	// loading.value = true
	getPagedSatellites()
}

// 获取分页数据
const getPagedSatellites = async isInit => {
	loading.value = true
	try {
		let responseData = {}
		const { currentTaskType } = props
		const params = {
			...condition,
			data: searchParams
			/*data: {
				processName: processName.value,
				createBy: createBy.value,
				instanceState: instanceState.value,
				beginTime: beginTime.value,
				endTime: endTime.value
			}*/
		}
		if (currentTaskType === 'pendingApproval') {
			responseData = await processTaskPagePendingApprovalApi(params)
		} else if (currentTaskType === 'myApplication') {
			responseData = await processTaskPageMyApplicationApi(params)
		} else if (currentTaskType === 'myReceived') {
			responseData = await processTaskPageMyReceivedApi(params)
		} else if (currentTaskType === 'pendingClaim') {
			responseData = await processTaskPagePendingClaimApi(params)
		} else if (currentTaskType === 'approved') {
			responseData = await processTaskPageApprovedApi(params)
		}
		const { records, total, pages } = responseData
		records.forEach(item => {
			// todo .. 这里将每个模块的不同值进行调整
			// 我收到、我申请 已审批 [结束时间 / 处理耗时 / 当前所在节点]
			// 待审批、认领 [会签/货签/票钱、当前所在节点]
			const flag1 = ['myReceived', 'myApplication', 'approved'].indexOf(props.currentTaskType) !== -1
			const flag2 = ['pendingApproval', 'pendingClaim'].indexOf(props.currentTaskType) !== -1
			item.currentNode = flag2 ? item.taskName : item.currentNode // 当前节点
			item.createTime = flag2 ? item.launchTime : item.createTime // 创建时间
			item.createBy = flag2 ? item.launchBy : item.createBy // 创建人
			if (!isInit) {
				listData.value.list.push(item)
				// list.value.push(item)
			}
		})

		if (isInit) {
			listData.value.list = records
			// list.value = records
		}
		// totalNumber.value = total
		// totalPages.value = pages
		listData.value.total = total
		// listData.value.page = pages
		loading.value = false
		if (condition.page > pages) {
			console.log('没有更多数据了')
			return
		}
		if (!isInit) {
			condition.page++
		}
	} catch (e) {
		console.log(e)
	}
}

// 点击当前实例的具体
const getTaskDetail = item => {
	taskProcessInfo.setCurrentTaskRow(item)
}

// 开始时间的禁用
const disabledDateStart = time => {
	if (!searchParams.endTime) return false
	return +time >= +new Date(`${searchParams.endTime} 23:59:59`)
}

// 结束时间的禁用
const disabledDateEnd = time => {
	if (!searchParams.beginTime) return false
	return +time <= +new Date(`${searchParams.beginTime} 00:00:00`)
}

/**
 * 重置搜索
 * @param type external：重置输入框
 * clear: 重置内部的值
 */
const resetSearch = type => {
	if (type === 'external') {
		// processName.value = ''
		searchParams.processName = undefined
		initList()
	}
}

onMounted(() => {
	taskProcessInfo.refresh = true
	taskProcessInfo.setCurrentTaskRow({})
})

/**
 * 监听同级子组件通知
 * 1、监听refresh的值变化，进行刷新
 */
watch(
	() => taskProcessInfo.refresh,
	(nValue, oValue) => {
		if (nValue) {
			initList()
		}
	},
	{ immediate: true }
)

const noMore = computed(() => {
	const _data = listData.value
	return _data.list.length >= _data.total
})

const disabledInfinite = computed(() => loading.value || noMore.value)
</script>

<style scoped lang="scss">
.flow-content {
	width: 330px;
	min-width: 330px;
	height: 100%;
	overflow: hidden;
	background: var(--el-bg-color);
	border-radius: 6px;

	// 搜搜条件
	.search-box {
		display: flex;
		align-items: center;
		height: 56px;
		padding: 0 12px;

		.search-segment + .search-segment {
			margin-left: 4px;
		}
		//> .el-button {
		//	padding: 0;
		//	width: 32px;
		//	background-color: var(--el-fill-color-light);
		//}
	}

	.flow-list-box {
		background-color: var(--el-bg-color);
		padding: 0 12px;
		height: calc(100vh - 192px);
		overflow: hidden auto;
		scroll-snap-type: y mandatory;
		will-change: scroll-position;
		.item-box {
			margin-bottom: 12px;
			&.item-box-choosed {
				.flow-card-box {
					border-color: var(--el-color-primary);
				}
			}
		}
		.flow-card-box {
			-webkit-user-select: none;
			user-select: none;
			border-radius: 6px;
			overflow: hidden;
			border: 1px solid var(--el-border-color);
			padding: 10px 12px;
			cursor: pointer;
			transition: box-shadow 0.2s cubic-bezier(0, 0, 1, 1);

			&.flow-card-box-hoverable {
				&:hover {
					box-shadow: 4px 4px 12px var(--el-border-color-hover);
				}
			}

			// 头部
			.header {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			// 操作类容
			.summary-list {
				margin-top: 10px;
				.summary-item {
					display: flex;
					min-height: 20px;
					.label {
						color: var(--el-text-color-secondary);
						overflow: hidden;
						white-space: nowrap;
						flex-shrink: 0;
					}
					.value {
						color: var(--el-text-color-primary);
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}
			}

			// 底部
			.footer {
				margin-top: 10px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 13px;
				.begin-time {
					color: var(--el-text-color-regular);
				}
			}
		}
	}
	.flow-bottom-txt {
		color: var(--el-color-primary);
		background: var(--el-color-primary-light-9);
		padding: 6px;
		margin-bottom: 6px;
		&.no-more {
			color: var(--el-color-warning);
			background: var(--el-color-warning-light-9);
		}
	}
}
</style>
