<template>
	<view class="content" :style="`height: ${contentHeight}`">
		<z-paging :fixed="false" @query="queryData" :value="list" :default-page-size="pSize" :default-page-no="pageNo"
			ref="paging">
			<!-- 简单的加载中提示 -->
			<view v-if="isLoading && list.length === 0" class="loading-container">
				<view class="loading-content">
					<text class="loading-text">加载中...</text>
				</view>
			</view>

			<!-- 列表项 -->
			<view v-for="(process, index) in list" :key="index">
				<uni-card @click="handleToDetail(process)" :isFull="true" padding="10px 0">
					<uni-row>
						<!-- <uni-col :xs="3" :sm="2">
							<view class="icon_container">
								<text style="font-size: calc(40px + 0.5 * (1rem - 16px));" class="ygoa_work_icon"
									:class="iconDict && iconDict[process.modelName] ? iconDict[process.modelName] : 'icon-outsourcing'"></text>
							</view>
						</uni-col> -->
						<uni-col :xs="24" :sm="24">
							<uni-card padding="0" :isFull="true" :border="false" :is-shadow="false">
								<template v-slot:title>
									<uni-row>
										<uni-col :xs="4" :sm="2">
											<text class="abbreviation-label" :style="`background-color: ${getLabelBgColor(process.abbreviation)}`">
												{{ process.abbreviation || '默认' }}
											</text>
										</uni-col>
										<uni-col :xs="15" :sm="20" v-if="current !== 0">
											<view class="process_title uni-ellipsis">
												<text>{{ process.insName }}</text>
											</view>
										</uni-col>
										<uni-col :xs="19" :sm="22" v-else>
											<view class="process_title uni-ellipsis">
												<text>{{ process.insName }}</text>
											</view>
										</uni-col>
										<uni-col :xs="5" :sm="2" v-if="current !== 0">
											<view class="process_status">
												<uni-tag v-if="current === 2" text="审批中" type="success"></uni-tag>
												<uni-tag v-else-if="current === 3" text="审批中" type="success"></uni-tag>
												<uni-tag v-else-if="current === 4" text="已办结" type="primary"></uni-tag>
											</view>
										</uni-col>
									</uni-row>
								</template>
								<view class="process_contant">
									<uni-row>
										<uni-col :xs="process.isCancel == '1'?20:24" :sm="process.isCancel == '1'?20:24">
											<view v-if="process.tmodelName == undefined">
												<!-- <uni-row v-if="process.insSubName != ''">
													<uni-col :xs="24" :sm="24">
														<text style="color: #79abff;font-weight: bold;">{{ process.insSubName }}</text>
													</uni-col>
												</uni-row>
												<uni-row>
													<uni-col :xs="8" :sm="7">流程类型:</uni-col>
													<uni-col :xs="16" :sm="17">{{ process.typeName || '无'
														}}</uni-col>
												</uni-row>
												<uni-row>
													<uni-col :xs="8" :sm="7">创建时间:</uni-col>
													<uni-col :xs="16" :sm="17">{{ process.createdate }}</uni-col>
												</uni-row> -->
												<view v-if="process.insSubName2" v-for="(item, idx) in parseInsSubName2(process.insSubName2)" :key="idx" class="info-item">
													<text class="info-label">
														{{ item.key }}：
													</text>
													<text class="info-value uni-ellipsis"
														:class="{
															'amount-value': item.key.includes('金额'),
															'timeout-value': item.key === '待办超时'
														}">
														{{ item.value }}
													</text>
												</view>
												<view v-else>
													<view class="info-item">
													<text v-if="process.insSubName != ''" class="info-label" :xs="24" :sm="24">
														<text style="color: #79abff;font-weight: bold;">{{ process.insSubName }}</text>
													</text>
													</view>

													<view class="info-item">
														<text class="info-label">当前流程：</text>
														<text class="info-value uni-ellipsis">{{ process.tmodelName || '无'}}</text>
													</view>
												</view>
												<!-- <view class="info-item">
													<text class="info-label">
														创建时间：
													</text>
													<text class="info-value">
														{{ process.createdate }}
													</text>
												</view> -->
											</view>
											<view v-else @click.stop.prevent="handleCollapseChange(process, index)">
												<!-- <uni-row v-if="process.insSubName != ''">
													<uni-col :xs="24" :sm="24">
														<text style="color: #79abff;font-weight: bold;">{{ process.insSubName }}</text>
													</uni-col>
												</uni-row>
												<uni-row>
													<uni-col :xs="8" :sm="7">当前流程:</uni-col>
													<uni-col :xs="16" :sm="17">
														<text style="color: #79abff; text-decoration: underline;">{{
															process.tmodelName }}</text>
													</uni-col>
												</uni-row>
												<uni-row>
													<uni-col :xs="8" :sm="7">创建时间:</uni-col>
													<uni-col :xs="16" :sm="17">{{ process.createdate }}</uni-col>
												</uni-row> -->
												<view v-if="process.insSubName2" v-for="(item, idx) in parseInsSubName2(process.insSubName2)" :key="idx" class="info-item">
													<text class="info-label" :class="{ 'amount-label': item.key === '合计金额' || item.key === '金额' }">
														{{ item.key }}：
													</text>
													<text class="info-value uni-ellipsis"
														:class="{
															'amount-value': item.key === '合计金额' || item.key === '金额',
															'timeout-value': item.key === '待办超时'
														}">
														{{ item.value }}
													</text>
													<!-- <uni-row class="info-label">
														<uni-col :xs="8" :sm="7">{{ item.key }}：</uni-col>
														<uni-col :xs="16" :sm="17">{{ item.value }}</uni-col>
													</uni-row> -->
												</view>
												<view v-else>
													<view class="info-item">
													<text v-if="process.insSubName != ''" class="info-label" :xs="24" :sm="24">
														<text style="color: #79abff;font-weight: bold;">{{ process.insSubName }}</text>
													</text>
													</view>

													<view class="info-item">
														<text class="info-label">当前流程：</text>
														<text class="info-value uni-ellipsis">{{ process.tmodelName || '无'}}</text>
													</view>
												</view>
												<view class="info-item">
													<text class="info-label">
														创建时间：
													</text>
													<text class="info-value">
														{{ process.createdate }}
													</text>
												</view>
											</view>
										</uni-col>
										<uni-col :xs="4" :sm="4" v-if="process.isCancel == '1'">
											<uni-row>
												<view class="button_container">
													<button type="warn" size="mini"
														@click.stop.prevent="handleToCancel(process)">撤回</button>
												</view>
											</uni-row>
										</uni-col>
									</uni-row>
								</view>
							</uni-card>
						</uni-col>
					</uni-row>
				</uni-card>
				<uni-collapse v-if="process.flowStepItem != undefined && process.flowStepItem.show">
					<uni-collapse-item  class="no-title-collapse" :border="false" :show-arrow="false" :open="process.flowStepItem.show" title-border="none">
						<template v-slot:title>
							<view class="flow_step_section">
								<!-- <uni-section title="流转过程" type="line" titleFontSize="0.8rem"></uni-section> -->
							</view>
						</template>
						<view class="flow_step_container">
							<up-steps class="up_step_view" :current="process.flowStepItem.stepActive"
								activeColor="#18bc37" inactiveColor="#2979ff" direction="column">
								<view v-for="(step, index) in process.flowStepItem.options" :key="index">
									<up-steps-item :contentClass="'redcontent'" v-if="step.state == '3'"
										:title="step.title + ' 退回'" :desc="step.desc" error></up-steps-item>
									<up-steps-item :contentClass="'redcontent'" v-else-if="step.state == '0'"
										:title="step.title + ' 撤销'" :desc="step.desc" error></up-steps-item>
									<up-steps-item v-else-if="step.state == '8' || step.state == '9'"
										:title="step.title + ' 回收'" :desc="step.desc" error></up-steps-item>
									<up-steps-item v-else-if="index == process.flowStepItem.stepActive"
										:title="step.title" :desc="step.desc">
										<template #icon>
											<view class="active_step_circle">
												<text class="active_step_text">{{ Number(index) + 1 }}</text>
											</view>
										</template>
									</up-steps-item>
									<up-steps-item v-else :title="step.title" :desc="step.desc"></up-steps-item>
								</view>
							</up-steps>
						</view>
					</uni-collapse-item>
				</uni-collapse>
			</view>
		</z-paging>
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { getProcessFlow } from '@/api/process'
import { useUserStore } from '@/store/user.js'
const userStore = useUserStore()
const iconDict = {
	'外协结算申请': 'icon-outsourcing',
	'用车申请': 'icon-apply-car',
	'出差申请': 'icon-apply-business',
	'外出申请': 'icon-apply-out',
	'费用报销申请': 'icon-apply-expense',
	'加班申请': 'icon-apply-overtime',
	'请假申请': 'icon-apply-leave',
	'采购申请': 'icon-apply-purchase',
	'补卡申请': 'icon-buka',
	'合同会签': 'icon-apply-sign-contract',
	'付款申请': 'icon-fukuan',
	'私车公用': 'icon-sichegongyong',
	'商务餐': 'icon-shangwucan',
	'离职申请': 'icon-lizhi',
	'人员变动': 'icon-renyuanbiandong',
	'公车维修': 'icon-gongcheweixiu',
	'办公用品': 'icon-bangongyongpin',
	'借款申请': 'icon-jiekuan',
	'签呈申请': 'icon-qiancheng',
}

const props = defineProps({
	contentHeight: { type: String, default: '85vh' },
	current: { type: Number, default: 0 }, // 消息类型
	pSize: { type: Number, default: 10 }, // 分页大小
	pageNo: { type: Number, default: 1 }, // 默认页
})
const emits = defineEmits([
	'clickSegment', // 点击分段器
	'clickItem', // 点击内容项
	'scrollToBottom', // 到达底部
	'clickCancel', // 点击取消按钮
])

const paging = ref(null)
// 加载完成 更新数据
const list = ref([])
const totalPage = ref(0)
const isLoading = ref(false) // 添加加载状态

/**
 * 根据标签名称获取背景色
 * @param label 标签名称（如"报销"、"申请"）
 * @returns 背景色值
 */
function getLabelBgColor(label) {
	if (!label) return '#f5f5f5';
	// 自定义标签颜色映射
	const colorMap = {
		'报销': '#e1f3ff',
		'申请': '#f0f9eb',
		'审批': '#fff7e6',
		'结算': '#fef0f0',
		'借款': '#f5fafe',
		'采购': '#f9f5ff',
		'付款': '#f9f5ff'
	};
	return colorMap[label] || '#f5f5f5';
}

/**
 * 解析标准JSON格式的process.insSubName2
 * 支持格式：[{"项目名称":"测试测试"},{"合计金额":"10000.00"}]
 * @param jsonStr 标准JSON字符串
 * @returns 键值对数组，格式如[{key: '项目名称', value: '测试测试'}, ...]
 */
function parseInsSubName2(data) {
	debugger
  if (!data || data == null) {
    return [];
  }

  let arr = data;
// 统一处理数组，转为键值对格式
	return arr
	  .filter(item => typeof item === 'object' && item !== null && Object.keys(item).length > 0)
	  .map(item => {
		const key = Object.keys(item)[0];
		return {
		  key: key || '',
		  value: item[key] !== undefined ? item[key].toString() : ''
		};
	  });
}

function handleCollapseChange(process, index) {
	// console.log('handleCollapseChange', process);
	if (list.value[index].flowStepItem == undefined) {
		getProcessFlow(userStore.user.useId, process).then(({ returnParams }) => {
			const flowStepItem = {
				options: [],
				stepActive: -1,
				show: true
			}
			flowStepItem.options = returnParams.list.map((item, index) => {
				const { tmodelName, name, createdate, finishdate, remark, state, task, groupName, positionName } = item
				if (state == 1) {
					flowStepItem.stepActive = index
				}
				const title = tmodelName + (name == '' ? '' : ' ( ' + name + ' ' + groupName + '-' + positionName + ' )')
				let desc = (finishdate == '' ? '\n' : '办理时间: ' + finishdate)
				if(task && task.length > 0) {
					desc += '抄送信息'
					task.forEach((taskitem) => {
						desc += '\n抄送对象:（' + taskitem.username + '） 抄送时间: ' + taskitem.createdate
					})
				}
				return {
					title,
					desc,
					state
				}
			})
			if (flowStepItem.stepActive === -1) flowStepItem.stepActive = returnParams.list.length
			list.value[index]['flowStepItem'] = flowStepItem
		})
		return
	}
	list.value[index].flowStepItem.show = !list.value[index].flowStepItem.show
}

function complete(dataList, total, pageNo) {
	totalPage.value = Math.ceil(total / props.pSize)
	if (pageNo <= totalPage.value) {
		list.value.push(...dataList);
	}
	// 第一页直接加载数据
	if (pageNo === 1) {
		list.value = dataList
		paging.value.complete(dataList)
		return
	}
	// 防止重复获取最后一次信息
	if (props.pSize * pageNo < total) {
		paging.value.complete(dataList)
	} else {
		paging.value.complete([])
	}
}
// 点击分段器
function onClickItem() {
	// 重新加载数据 pageNo恢复为默认值
	list.value = []
	paging.value.reload()
}
// 刷新
function queryData(pageNo, pSize, queryType) {
	switch (queryType) {
		case 0: // 下拉刷新
		case 1: // 初始加载
			reloadData()
			break
		case 3: // 上拉加载
			scrollQuery(pageNo, pSize)
			break
		default: // 默认刷新
			reloadData()
			break
	}
}
// 刷新数据
function reloadData() {
	isLoading.value = true
	const params = {
		pSize: props.pSize,
		pageNo: props.pageNo,
	}
	emits('clickSegment', params, (dataList, total, pageNo) => {
		complete(dataList, total, pageNo)
		isLoading.value = false
	})
}
// 上拉加载
function scrollQuery(pageNo, pSize) {
	isLoading.value = true
	const params = {
		pSize,
		pageNo,
	}
	emits('scrollToBottom', params, (dataList, total, pageNo) => {
		complete(dataList, total, pageNo)
		isLoading.value = false
	})
}

function handleToDetail(process) { // 跳转流程详情页
	emits('clickItem', process)
}
function handleToCancel(process) {
	emits('clickCancel', process)
}
defineExpose({
	onClickItem,
});
</script>

<style lang="scss" scoped>
// @import url("@/static/font/ygoa/iconfont.css");

::v-deep .no-title-collapse .uni-collapse-item__title {
  display: none !important;
}

// 简单的加载中样式
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
}

.loading-content {
  text-align: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.flow_step_section {
	.uni-section .uni-section-header {
		padding: 0px 0px;
	}
}

.flow_step_container {
	min-height: 100px;

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

				.redcontent {
					.u-text__value--content {
						color: #ff4500;
					}
				}

				.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: 0.6875rem;
						display: flex;
						flex-direction: row;
						align-items: center;
						justify-content: center;
						text-align: center;
						line-height: 0.6875rem;
					}
				}
			}

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

				.u-text__value--content {
					font-size: 1rem !important;
				}

				.u-text__value--main {
					font-size: 1rem !important;
				}
			}
		}
	}

}

.content {

	.icon_container {
		margin: 45% 0;
	}

	.process_title {
		// TODO 长度限制15字
		line-height: 1.5rem;
		font-weight: 500;
		font-size: 1.1rem;
		margin: 5px 0;
		color: #333;
	}

	.process_status {
		margin: 5px 0;
		height: 1.5rem;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		white-space: nowrap;
		overflow: hidden;
	}

	.process_contant {
		color: #777;
	}
}
// 左上角标签样式
	.abbreviation-label {
		margin: 5px 10px 0px 0px;
		height: 1.5rem;
	  padding: 0px 2px;
	  border-radius: 4px;
	  color: #409eff;
	  // font-weight: 500;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  text-align: center;
	  white-space: nowrap; // 不换行
	}

.info-label {
  color: #666;
  min-width: 70px;
  font-size: 28rpx;
  font-weight: 500;
}
.info-value {
  // color: #333;
  font-size: 28rpx;
  flex: 1;
  // word-break: break-all;
  overflow: hidden;
}

// 信息项样式
.info-item {
  display: flex;
  align-items: center;
  font-size: 0.9rem;
  line-height: 1.8;
}

.amount-value {
  font-weight: 600;
  color: #e6a23c;
}
</style>
