<template>
	<v-container fluid class="vtk-height pa-0">
		<v-tabs v-model="examType" bg-color="transparent" height="38" style="width: 100%">
			<v-tab @click="examAll()">
				<span><v-icon size="16" class="mr-1">mdi-clipboard-arrow-up</v-icon>全部</span>
			</v-tab>
			<v-tab @click="list">
				<span><v-icon size="16" class="mr-1">mdi-star-circle</v-icon>审核</span>
			</v-tab>
			<v-tab @click="tip">
				<span><v-icon size="16" class="mr-1">mdi-hand-heart</v-icon>实施</span>
			</v-tab>
			<v-tab @click="tip">
				<span><v-icon size="16" class="mr-1">mdi-comment-minus</v-icon>评价</span>
			</v-tab>
			<v-tab @click="tip">
				<span><v-icon size="16" class="mr-1">mdi-credit-card-check</v-icon>支付</span>
			</v-tab>
			<v-spacer />
		</v-tabs>
		<v-card elevation="0" style="min-height: calc(100% - 38px)">
			<v-card-title style="height: 88px">
				<v-menu v-if="examType == '0' && (expShow || user.grole >= 2)" offset-y :close-on-content-click="false" location="bottom">
					<template v-slot:activator="{ props }">
						<v-btn @click="exv" v-bind="props" class="bg-orange text-white mr-3" elevation="0">
							<v-icon>mdi-export-variant</v-icon> 导出
						</v-btn>
					</template>
					<v-card class="pa-3" width="300">
						<div>
							<p class="mb-2 font-weight-bold">公共字段</p>
							<p class="text-caption">
								服务事项
								<span class="text-grey mx-1">|</span>
								所属区县
								<span class="text-grey mx-1">|</span>
								所属镇街
								<span class="text-grey mx-1">|</span>
								所属社区
								<span class="text-grey mx-1">|</span>
								申请人证件号
								<span class="text-grey mx-1">|</span>
								申请人姓名
								<span class="text-grey mx-1">|</span>
								残疾人证号
								<span class="text-grey mx-1">|</span>
								性别
								<span class="text-grey mx-1">|</span>
								申请人手机号
								<span class="text-grey mx-1">|</span>
								补助金额
								<span class="text-grey mx-1">|</span>
								开户银行
								<span class="text-grey mx-1">|</span>
								银行卡号
								<span class="text-grey mx-1">|</span>
								收款人姓名
								<span class="text-grey mx-1">|</span>
								收款人证件号
								<span class="text-grey mx-1">|</span>
								状态
							</p>
							<v-divider />
							<div v-if="queryParam.servState == '1' && projName">
								<v-card-title class="pa-0 text-body-1 mb-2 pt-3">
									<v-checkbox @update:model-value="chkAll" v-model="select" class="mt-n1" hide-details>
										<template v-slot:append>
											<v-icon class="active" style="display: none" size="18">mdi-check-circle</v-icon>
										</template>
									</v-checkbox>
									<span class="font-weight-bold ml-n2">拓展字段</span>
									<v-spacer />
								</v-card-title>
								<p v-if="formArr?.length > 0" class="mb-0 expBox">
									<v-checkbox
										v-for="(item, index) in formArr"
										:key="index"
										v-model="expArr"
										:label="item.label"
										:value="{ name: item.name, valu: `${item.label}${item.valu && item.valu.includes('/') && item.valu.includes(':') ? `(${item.valu})` : ''}` }"
										class="mt-2"
										multiple
										hide-details>
										<template v-slot:append>
											<v-icon class="active" style="display: none" size="18">mdi-check-circle</v-icon>
										</template>
									</v-checkbox>
								</p>
								<p v-else class="text-red text-body-2 mb-2">{{ projTip }}</p>
							</div>
							<div v-else>
								<p class="mb-3 pt-3 font-weight-bold">导出提示</p>
								<p :class="queryParam.servState == '1' ? 'text-green' : 'text-red'" class="mb-3 text-body-2">
									<v-icon size="20" :color="queryParam.servState == '1' ? 'green' : 'red'">{{ queryParam.servState == "1" ? "mdi-progress-check" : "mdi-progress-close" }}</v-icon>
									导出数据仅限已服务信息
								</p>
								<p class="mb-2 text-body-2" :class="projName ? 'text-green' : 'text-red'">
									<v-icon size="20" :color="projName ? 'green' : 'red'">{{ projName ? "mdi-progress-check" : "mdi-progress-close" }}</v-icon>
									至少选择一个服务事项导出
								</p>
							</div>
						</div>
						<v-btn @click="exp" :disabled="!(projName && queryParam.servState == '1')" elevation="0" color="primary" class="vtk-width mt-3" size="small">确认导出</v-btn>
					</v-card>
				</v-menu>
				<v-spacer />
				<vtk-search v-model="queryParam" @search="searchQuery" placeholder="输入姓名/身份证查询" :styles="'width:320px'">
					<v-text-field @click="searchProj" v-model="projName" :title="projName" clearable readonly variant="outlined" placeholder="服务事项" density="compact" hide-details class="my-3"></v-text-field>
					<vtk-area-tabs v-model="queryParam.areaCode" :styles="'width:100%'" />
					<div v-if="examType == 0" style="width: 400px">
						<vtk-select v-model="queryParam.servState" @change="searchQuery" placeholder="服务状态" list="0:服务中/1:已服务" class="mt-3 d-inline-block mr-3 mb-3" style="width: calc(50% - 6px)" hide-details density="compact" variant="outlined" clearable></vtk-select>
						<vtk-select v-model="queryParam.rateState" @change="searchQuery" placeholder="是否评价" list="0:未评价/1:已评价" class="mt-3 d-inline-block" style="width: calc(50% - 6px)" hide-details density="compact" variant="outlined" clearable></vtk-select>
						<v-menu v-model="menu" :close-on-content-click="false" transition="scale-transition" location="bottom" max-width="290px" min-width="auto">
							<template v-slot:activator="{ props }">
								<v-text-field v-model="queryParam.servFtime0" placeholder="开始时间" persistent-hint append-icon="mdi-calendar" class="d-inline-block" style="width: calc(50% - 16px)" hide-details variant="outlined" density="compact" v-bind="props"></v-text-field>
							</template>
							<v-date-picker v-model="queryParam.servFtime0" title="" @update:model-value="menu = false" view-mode="month" :max="queryParam.servFtime1"></v-date-picker>
						</v-menu>
						<span class="mx-2">至</span>
						<v-menu v-model="menu1" :close-on-content-click="false" transition="scale-transition" location="bottom" max-width="290px" min-width="auto">
							<template v-slot:activator="{ props }">
								<v-text-field v-model="queryParam.servFtime1" placeholder="结束时间" persistent-hint append-icon="mdi-calendar" class="d-inline-block" style="width: calc(50% - 15px)" hide-details variant="outlined" density="compact" v-bind="props"></v-text-field>
							</template>
							<v-date-picker v-model="queryParam.servFtime1" title="" @update:model-value="menu1 = false" view-mode="month" :min="queryParam.servFtime0"></v-date-picker>
						</v-menu>
						<vtk-select v-if="queryParam.servState == '1'" @change="searchQuery" v-model="queryParam.state" class="mt-3" placeholder="状态" list="1:已通过/0:未通过" hide-details density="compact" variant="outlined" clearable></vtk-select>
					</div>
				</vtk-search>
			</v-card-title>
			<v-card-text>
				<v-data-table :headers="headers" :items="desserts" :loading="loading" disable-pagination loading-text="数据加载中..." class="elevation-0" hide-default-footer>
					<template v-slot:[`item.objsName`]="{ item }">
						<div class="py-3" @click="toView(item)">
							<p class="vtk-cursor-pointer text-body-1 font-weight-bold mb-2">
								{{ item.objsName }}<span class="ml-3 text-grey">{{ formatIdCard(item.objsCode) }} </span>
								<v-chip class="ml-2" :class="getServStateClass(item.servState)" size="small" label>{{ getServStateText(item.servState) }} </v-chip>
								<v-chip class="ml-2" :class="getRateStateClass(item.rateState)" size="small" label>{{ getRateStateText(item.rateState) }} </v-chip>
							</p>
							<span>
								<v-chip class="bg-orange-lighten-5 text-orange" size="small" label> 事项编码:{{ item.projCode }} </v-chip>
								<v-chip class="text-primary ml-2" size="small" label> 办件编号:{{ item.inst }} </v-chip>
							</span>
							<div class="mb-0 mt-2 text-grey">
								<div class="d-inline-block" style="min-width: 320px">
									服务名称:<span class="text-blue">{{ item.projName }}</span>
								</div>
								<span>补助金额:{{ item.servAmts }}元</span>
							</div>
							<v-row class="py-2" style="color: #979797c2">
								<v-col style="max-width: 320px">
									<span :title="item.name" class="d-block" style="color: #979797c2">申请途径:{{ getServFromText(item.servFrom) }}</span>
								</v-col>
								<v-col>
									<span :title="item.name" class="d-block" style="color: #979797c2">申请时间:{{ formatDate(item.servCtime) }}</span>
								</v-col>
							</v-row>
						</div>
					</template>
					<template v-slot:[`item.actions`]="{ item }">
						<a v-if="item.state != 0 && user.areacode?.length == 6 && item.servState == '1'" @click="del(item)" class="text-error" text>作废</a>
						<div v-if="item.state == 0" class="state_btg text-right"></div>
					</template>
					<template v-slot:no-data>
						<vtk-empty />
					</template>
				</v-data-table>
				<vtk-page :page-sizes="[10, 20]" :page-data="pageData" @pageChange="getListPage" />
			</v-card-text>
		</v-card>
		<!-- 服务事项 -->
		<vtk-proj ref="MprojRef" @toPage="toPage" />
		<!-- 删除服务 -->
		<v-dialog v-model="dialog" persistent max-width="500">
			<v-card>
				<v-card-title>作废</v-card-title>
				<v-card-text class="pb-0">
					服务作废后将无法恢复,请谨慎操作!!!
					<v-textarea v-model="delNote" variant="outlined" label="请填写作废原因" class="mt-3" hide-details density="compact"></v-textarea>
				</v-card-text>
				<v-card-actions>
					<v-spacer />
					<v-btn @click="dialog = false" variant="text">取消</v-btn>
					<v-btn @click="delSave(true)" variant="text">确定</v-btn>
				</v-card-actions>
			</v-card>
		</v-dialog>
	</v-container>
</template>

<script setup>
import { ref, watch, onActivated } from 'vue';
import { useMixins } from '@/composables/useMixins'
import Request from '@/commons/request';

// 定义组件选项
defineOptions({
	name: 'VtkProj',
	inheritAttrs: false,
});

// 表单列表 URL 配置
const urlConfig = {
	list: '/kudas/xfwez/page',
	exp: '/kudas/xfwez/exp',
	delete: '/kudas/xfwez/delete'
};

// 使用 mixins composable
const {
	pageData,
	getListPage,
	loadPage,
	expData,
	desserts,
	loading,
	queryParam: mixinQueryParam,
	url
} = useMixins(urlConfig);

// 合并 queryParam
Object.assign(mixinQueryParam, {});
const queryParam = mixinQueryParam;

// 响应式数据
const user = ref({});
const examType = ref(1);

const headers = ref([
	{ title: '事项', key: 'objsName', sortable: false },
	{ title: '状态', key: 'actions', sortable: false, align: 'end' },
]);

// 主题筛选
const permits = ref([]);
const projName = ref('');
const projTip = ref('');
const bizType = ref('');
const expShow = ref(false);
const menu = ref(false);
const menu1 = ref(false);

// 导出
const expArr = ref([]);
const formArr = ref([]);
const select = ref(false);
const selectAll = ref([]);

// 删除
const dialog = ref(false);
const delItem = ref({});
const delNote = ref('');

// ref
const MprojRef = ref(null);

// 监听器
watch(expArr, (newVal) => {
	if (newVal.length < selectAll.value.length) {
		select.value = false;
	}
}, { deep: true });

// 生命周期
onActivated(() => {
	alert('onActivated');
	list();
	// 监听接收消息,刷新页面
	window.addEventListener('storage', (event) => {
		if (JSON.parse(event?.newValue)?.fwez) {
			examType.value == '0' ? examAll() : loadPage();
		}
	});
});

// 方法
// 全选
const chkAll = (e) => {
	expArr.value = e ? selectAll.value : [];
};

const list = () => {
	bizType.value = '';
	expShow.value = false;
	user.value = getUserInfo();
	permits.value = [];
	user.value.permits?.forEach((e) => {
		if (e.permNkey.includes('biz_type')) {
			permits.value.push(e);
			bizType.value = bizType.value + e.permNkey.slice(9) + ',';
		} else if (e.permNkey == 'btn_expo') {
			expShow.value = true;
		}
	});
	queryParam.bizType = bizType.value;
	examWait();
};

// 获取用户信息
const getUserInfo = () => {
	try {
		// 实际项目中从存储或状态管理获取
		return window.$vtk?.storage?.get('user') || {};
	} catch (error) {
		console.warn('获取用户信息失败:', error);
		return {};
	}
};

// 待审
const examWait = () => {
	examType.value = 1;
	queryParam.operateLeve = user.value.areacode?.length;
	queryParam.servState = '0';
	loadPage();
};

// 全部审核
const examAll = () => {
	examType.value = 0;
	delete queryParam.operateLeve;
	delete queryParam.servState;
	loadPage();
};

// 审核
const toView = (item) => {
	const url = item.servState == 1
		? `#/mino/suse/view/${item.inst}?ddtab=true`
		: `#/mino/suse/exam/${item.inst}?ddtab=true`;
	window.open(url);
};

// 服务事项查询/筛选
const searchProj = () => {
	MprojRef.value?.add(queryParam.projCode);
};

const toPage = (param) => {
	projName.value = param.projName;
	queryParam.projCode = param.projCode;
	delete queryParam.bizType;
	searchQuery();
};

const searchQuery = () => {
	// 搜索查询逻辑
	loadPage();
};

// 导出相关
const exv = () => {
	if (projName.value && queryParam.servState == '1') {
		expArr.value = [];
		formArr.value = [];
		// 显示加载状态
		Request.postJson('/kudas/xfwez/exv', { codex: queryParam }).then((res) => {
			if (res.meta.success) {
				JSON.parse(res.data.formJson).forEach((item) => {
					if (['text', 'radio', 'number', 'time', 'checkbox', 'textarea', 'select'].includes(item.type)) {
						item.value = {
							name: item.name,
							valu: `${item.label}${item.valu && item.valu.includes('/') && item.valu.includes(':') ? `(${item.valu})` : ''}`
						};
						formArr.value.push(item);
						selectAll.value.push(item.value);
					}
				});
			} else {
				projTip.value = res.meta.message;
			}
		});
	}
};

const exp = () => {
	queryParam.fields = expArr.value;
	expData();
};

// 服务作废
const del = (item) => {
	dialog.value = true;
	delItem.value = item;
	delNote.value = '';
};

const delSave = () => {
	if (delNote.value) {
		Request.postForm(url.delete, { id: delItem.value.id, note: delNote.value }).then((res) => {
			if (res.meta.success) {
				// 显示成功消息
				dialog.value = false;
				loadPage();
			} else {
				// 显示失败消息
			}
		});
	} else {
		// 显示错误消息
	}
};

// 提示
const tip = () => {
	// 显示应用开发中的消息
};

// 工具函数
const formatIdCard = (idcard) => {
	if (!idcard) return '';
	return idcard.replace(/^(.{6})(?:\d+)(.{4})$/, '$1********$2');
};

const formatDate = (dateStr) => {
	if (!dateStr) return '';
	const date = new Date(dateStr);
	return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, '0')}月${String(date.getDate()).padStart(2, '0')}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

const getServStateClass = (state) => {
	return state == '0' ? 'bg-blue-lighten-5 text-blue' : 'bg-green-lighten-5 text-green';
};

const getServStateText = (state) => {
	return state == '0' ? '服务中' : '已服务';
};

const getRateStateClass = (state) => {
	return state == '0' ? 'bg-orange-lighten-5 text-orange' : 'bg-blue-lighten-5 text-blue';
};

const getRateStateText = (state) => {
	return state == '0' ? '未评价' : '已评价';
};

const getServFromText = (from) => {
	const fromMap = {
		'100': '特殊渠道',
		'101': '移动端代办',
		'102': '窗口端通办',
		'200': '特殊渠道',
		'210': '浙里办App',
		'211': '浙里办微信小程序',
		'212': '浙里办支付宝小程序',
		'230': '微信小程序',
		'240': '支付宝小程序',
		'250': '自助机',
		'300': '特殊渠道',
		'310': '服务外包代办'
	};
	return fromMap[from] || from;
};
</script>

<style lang="scss" scoped>
.state_btg {
	padding-right: 0;
	height: 100%;
	background: url(../../assets/img/objs_btg.png) no-repeat;
	background-size: 80px;
	background-position: 100% 100%;
}

:deep(.v-tab) {
	background: url(../../assets/img/tab-2.png) no-repeat;
	background-size: 100% 100%;
	width: 150px;
	margin-left: -11px;
	border-top-left-radius: 20px;
	border-top-right-radius: 20px;
	span {
		z-index: 99;
	}
}

/* Dark theme */
.v-theme--dark {
	:deep(.v-tab) {
		background: url(../../assets/img/tab-4.png) no-repeat;
		background-size: 100% 100%;
	}

	:deep(.v-tabs__slider) {
		background: url(../../assets/img/tab-3.png) no-repeat !important;
		background-size: 100% 100% !important;
	}
}

:deep(.v-tab::before),
:deep(.v-tab:focus::before),
:deep(.v-tab:hover::before) {
	background-color: transparent !important;
	opacity: 0 !important;
}

:deep(.v-tabs__slider) {
	height: 38px !important;
	background: url(../../assets/img/tab-1.png) no-repeat;
	background-size: 100% 100%;
}

.expBox {
	:deep(td) {
		border-bottom: thin solid rgba(123, 123, 123, 0.22);
	}

	:deep(.v-data-table__empty-wrapper td) {
		border: none;
	}

	:deep(.v-checkbox.v-selection-control--dirty) {
		background-color: rgba(33, 149, 243, 0.06) !important;

		.v-label {
			color: rgb(33, 150, 243) !important;
		}

		.active {
			color: rgb(33, 150, 243);
			display: inline-block !important;
		}
	}

	:deep(.v-selection-control__input) {
		display: none;
	}

	:deep(.v-checkbox) {
		padding: 4px 8px 4px 10px;
		border-radius: 6px;
		background-color: rgba(117, 117, 117, 0.06);

		.v-label {
			margin-top: 3px;
			font-size: 12px;
		}
	}
}
</style>
