<template>
	<div class="system-tenant-container">
		<el-card shadow="hover">
			<div class="system-tenant-search mb15">
				<el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="68px">
					<el-form-item label="租户名称" prop="tenantName">
						<el-input
							v-model="tableData.param.tenantName"
							placeholder="请输入租户名称"
							clearable
							size="default"
							style="width: 240px"
							@keyup.enter.native="tenantList"
						/>
					</el-form-item>
					<el-form-item label="租户类型" prop="tenantType">
						<el-select v-model="tableData.param.tenantType" placeholder="请选择租户类型" clearable size="default" style="width: 240px">
							<el-option label="普通类型" :value="1" />
							<el-option label="代理类型" :value="2" />
						</el-select>
					</el-form-item>
					<el-form-item label="所属城市" prop="city">
						<el-cascader
							v-model="tableData.param.cityCode"
							:options="cityOptions"
							placeholder="请选择城市"
							clearable
							size="default"
							style="width: 240px"
						/>
					</el-form-item>
					<el-form-item>
						<el-button size="default" type="primary" class="ml10" @click="tenantList">
							<el-icon><ele-Search /></el-icon>
							查询
						</el-button>
						<el-button size="default" @click="resetQuery(queryRef)">
							<el-icon><ele-Refresh /></el-icon>
							重置
						</el-button>
						<el-button size="default" type="success" class="ml10" @click="onOpenAddTenant">
							<el-icon><ele-FolderAdd /></el-icon>
							新增租户
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<el-table :data="tableData.data" style="width: 100%" v-loading="tableData.loading">
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="tenantName" label="租户名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="tenantType" label="租户类型" show-overflow-tooltip>
					<template #default="scope">
						<el-tag v-if="scope.row.tenantType === 1 || scope.row.tenantType === 0">普通</el-tag>
						<el-tag v-else-if="scope.row.tenantType === 2" type="warning">代理</el-tag>
						<!-- <el-tag v-else type="info">普通</el-tag> -->
					</template>
				</el-table-column>
				<el-table-column prop="cityName" label="所属城市" show-overflow-tooltip>
					<template #default="scope">
						{{ getCityName(scope.row.cityName) }}
					</template>
				</el-table-column>
				<el-table-column prop="userNickname" label="联系人" show-overflow-tooltip></el-table-column>
				<el-table-column prop="mobile" label="电话" show-overflow-tooltip></el-table-column>
				<el-table-column prop="businessLicense" label="营业执照" align="center">
					<template #default="scope">
						<el-image
							style="width: 50px; height: 50px"
							:src="scope.row.businessLicense"
							:preview-src-list="[scope.row.businessLicense]"
							preview-teleported
							fit="cover"
							v-if="scope.row.businessLicense"
						/>
						<span v-else>无</span>
					</template>
				</el-table-column>
				<el-table-column prop="createdAt" label="创建时间" show-overflow-tooltip></el-table-column>
				<!-- <el-table-column prop="updatedAt" label="修改时间" show-overflow-tooltip></el-table-column> -->
				<!-- <el-table-column label="操作" width="200">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="onOpenEditTenant(scope.row)">修改</el-button>
						<el-button size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column> -->
			</el-table>
			<pagination
				v-show="tableData.total > 0"
				:total="tableData.total"
				v-model:page="tableData.param.pageNum"
				v-model:limit="tableData.param.pageSize"
				@pagination="tenantList"
			/>
		</el-card>
		<EditTenant ref="editTenantRef" @getTenantList="tenantList" />
	</div>
</template>

<script lang="ts">
export default {
	name: 'systemTenant',
};
</script>

<script setup lang="ts">
import { toRefs, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import EditTenant from './component/editTenant.vue';
import { getTenantList, deleteTenant } from '/@/api/system/tenant';
import { pcTextArr,provinceAndCityData } from 'element-china-area-data';

const editTenantRef = ref();
const queryRef = ref();
const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			pageNum: 1,
			pageSize: 10,
			tenantName: '',
			tenantType: '',
			cityCode: '',
		},
	},
});

const { tableData } = toRefs(state);

// 省市数据
const cityOptions = ref<any[]>([]);

// 初始化城市数据
const initCityData = () => {
	const data = JSON.parse(JSON.stringify(provinceAndCityData));
	cityOptions.value = data.map((item: any) => {
		// 处理直辖市：北京(110000), 天津(120000), 上海(310000), 重庆(500000)
		if (['110000', '120000', '310000', '500000'].includes(item.value) || ['北京市', '天津市', '上海市', '重庆市'].includes(item.label)) {
			// 移除 children 属性，使其成为叶子节点
			delete item.children;
		}
		return item;
	});
};
initCityData();


// 初始化表格数据
const tenantList = () => {
	state.tableData.loading = true;
	const params = { ...state.tableData.param };
	// 处理城市数据：如果是数组（级联选择器返回），取最后一个值
	if (Array.isArray(params.cityCode) && params.cityCode.length > 0) {
		let lastCode = String(params.cityCode[params.cityCode.length - 1]);
		// 特殊处理直辖市：如果选中的是省级代码，转换为市级代码 (市辖区)
		const municipalityMap: Record<string, string> = {
			'11': '110100', '110000': '110100', // 北京
			'12': '120100', '120000': '120100', // 天津
			'31': '310100', '310000': '310100', // 上海
			'50': '500100', '500000': '500100', // 重庆
		};
		if (municipalityMap[lastCode]) {
			lastCode = municipalityMap[lastCode];
		} else if (lastCode.length === 4) {
			// 普通省市，如果是4位代码，补齐为6位
			lastCode = lastCode + '00';
		}
		params.cityCode = lastCode;
	} else {
		params.cityCode = '';
	}

	getTenantList(params)
		.then((res: any) => {
			const imgAddressPrefix = res.data.imgAddressPrefix || '';
			const list = res.data.list ?? [];
			// 拼接营业执照完整地址
			state.tableData.data = list.map((item: any) => ({
				...item,
				businessLicense: item.businessLicense ? imgAddressPrefix + item.businessLicense : '',
			}));
			state.tableData.total = res.data.total;
		})
		.catch(() => {
			// 模拟数据，防止报错影响演示
			state.tableData.data = [];
			state.tableData.total = 0;
		})
		.finally(() => {
			state.tableData.loading = false;
		});
};

// 打开新增弹窗
const onOpenAddTenant = () => {
	editTenantRef.value.openDialog();
};

// 打开修改弹窗
const onOpenEditTenant = (row: any) => {
	editTenantRef.value.openDialog(row);
};

// 删除
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除租户：“${row.tenantName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			deleteTenant([row.id]).then(() => {
				ElMessage.success('删除成功');
				tenantList();
			});
		})
		.catch(() => {});
};

// 重置
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	tenantList();
};

// 解析城市名称
const getCityName = (cityName: string | string[]) => {
	if (!cityName) return '';
	// 如果是数组则用 / 连接，如果是字符串直接返回
	if (Array.isArray(cityName)) {
		return cityName.join(' / ');
	}
	return cityName;
};

onMounted(() => {
	tenantList();
});
</script>
