<template>
	<div class="section-main-container layout-padding">
		<div class="section-main-padding layout-padding-auto layout-padding-view">
			<div class="section-user-search mb15">
				<el-form :inline="true" :model="source.searchInfo" class="demo-form-inline" label-position="left" size="default"
					@submit.prevent>
					<el-form-item label="公司名称" v-if="source.userInfo.superviseDesk">
						<el-input v-model="source.searchInfo.companyName" placeholder="请输入公司名称" clearable @keyup.enter="getTableData"
							style="max-width: 180px" />
					</el-form-item>
					<el-form-item label="姓名">
						<el-input v-model="source.searchInfo.name" placeholder="请输入姓名" clearable @keyup.enter="getTableData"
							style="max-width: 180px" />
					</el-form-item>
					<el-form-item label="证件号">
						<el-input v-model="source.searchInfo.idCardNo" placeholder="请输入证件号" clearable @keyup.enter="getTableData"
							style="max-width: 180px" />
					</el-form-item>
					<!-- <el-form-item label="监管机构">
            <el-cascader v-model="source.searchInfo.superviseDepartIds" :options="source.regulatorsList" :props="source.props" collapse-tags collapse-tags-tooltip :show-all-levels="false" clearable ref="myCascader" />
          </el-form-item> -->
					<el-form-item label="监管机构">
						<el-cascader v-model="source.superviseDepartIdArr" :options="source.searchInfo.options" :props="customProps"
							collapse-tags collapse-tags-tooltip :show-all-levels="false" clearable ref="myCascader" />
					</el-form-item>
					<el-form-item label="所属驻勤点">
						<el-input v-model="source.searchInfo.securityStationName" placeholder="请输入所属驻勤点" clearable
							@keyup.enter="getTableData" style="max-width: 180px" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="getTableData">查询</el-button>
						<el-button type="default" @click="resetgetTableData">重置</el-button>
						<el-button type="primary" @click="exportData">导出</el-button>
					</el-form-item>
				</el-form>
			</div>
			<el-table :data="source.securityGuardList" v-loading="source.loading" style="width: 100%">
				<el-table-column type="index" width="80" label="序号" align="center" />
				<el-table-column prop="name" label="姓名" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="sexText" label="性别" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="idCardNo" label="证件号" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="contact" label="联系电话" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="companyName" label="公司名称" align="center" show-overflow-tooltip
					v-if="source.userInfo.superviseDesk"></el-table-column>
				<el-table-column prop="superviseDepartName" label="所属监管机构" align="center" show-overflow-tooltip
					v-if="source.userInfo.superviseDesk"></el-table-column>
				<el-table-column prop="authenticatedStatusText" label="实名认证" align="center"
					show-overflow-tooltip></el-table-column>
				<el-table-column label="持证情况" align="center" show-overflow-tooltip>
					<template #default="scope">
						<span>{{ scope.row.hasSecurityCertificateNo ? '是' : '否' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="securityStationName" label="所属驻勤点" align="center" show-overflow-tooltip></el-table-column>
			</el-table>
			<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
				:pager-count="5" :page-sizes="[10, 20, 30, 100, 200, 300, 1000]" v-model:current-page="source.pageIndex"
				background v-model:page-size="source.pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="source.totalCount">
			</el-pagination>
		</div>
	</div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { ConfigApi } from '/@/api/api';
import { useRoute } from 'vue-router';
import { Session } from '/@/utils/storage';

// 定义变量内容
const route = useRoute();
const myCascader = ref();

const source = reactive({
	loading: false,
	securityGuardList: [],
	regulatorsList: [],
	props: {
		multiple: true,// 启用多选
		checkStrictly: false,//父子节点不互相关联
		emitPath: true,//若设置 false，则只返回该节点的值
		value: 'code',//自定义当前数组的键名 - value
		label: 'name', // 自定义当前数组的键名 - label 
	},
	searchInfo: {
		name: '',
		companyName: '',
		idCardNo: '',
		superviseDepartIds: [],
		options: [],
		securityStationName: ''
	},
	superviseDepartIdArr: [] as string[],
	userInfo: {
		superviseDesk: false
	} as any,
	totalCount: 0,
	pageIndex: 1,
	pageSize: 10,
	pageCount: null,
});
source.searchInfo.companyName = route.query?.companyName as string;
localStorage.getItem('userInfo') ? source.userInfo = {
	...source.userInfo,
	...JSON.parse(localStorage.getItem('userInfo') as string)
} : null;
console.info('userInfo', JSON.parse(localStorage.getItem('userInfo') as string));


// 定义变量内容
const customProps = {
	multiple: true,// 启用多选
	checkStrictly: false,//父子节点不互相关联
	emitPath: true,//若设置 false，则只返回该节点的值
	value: 'code',//自定义当前数组的键名 - value
	label: 'name', // 自定义当前数组的键名 - label 
}


// 页面加载时
onMounted(() => {
	searchDeparts();
	getTableData();
	source.userInfo.superviseDesk ? getGegulators() : null; // 非企业调度台时，需要获取监管机构数据
});

// 初始化表格数据
const getTableData = () => {
	source.loading = true;

	let Depstr: [] = []
	if (myCascader.value.getCheckedNodes().length) {
		myCascader.value.getCheckedNodes().forEach((item: { value: any; }) => Depstr.push(item.value))
	}
	source.searchInfo.superviseDepartIds = Depstr

	let params = {
		pageIndex: source.pageIndex,
		pageSize: source.pageSize,
		companyName: source.userInfo.superviseDesk ? source.searchInfo.companyName || '' : undefined,
		name: source.searchInfo.name,
		idCardNo: source.searchInfo.idCardNo,
		securityStationName: source.searchInfo.securityStationName,
		superviseDepartIds: source.searchInfo.superviseDepartIds,
		deskTypes: Session.get('platform')==='2' ? ['Proprietor'] : Session.get('platform')==='3' ? ["TemporarySecurity"] : ['Normal']
	} as any;

	if (source.userInfo.superviseDesk) { // 非企业调度台时
		let Depstr = [] as any;
		if (myCascader.value.getCheckedNodes().length) {
			myCascader.value.getCheckedNodes().forEach((item: any) => Depstr.push(item.value))
		}
		params.superviseDepartIds = Depstr as any;
	}

	ConfigApi().unActivatedSecurityGuardSearchApi(params).then(response => {
		let { status, message, data } = response;

		if (status !== 200) {
			ElMessage.error(message);
			return;
		}

		let { pageCount, pageSize, totalCount } = data;
		source.pageSize = pageSize;
		source.pageCount = pageCount;
		source.totalCount = totalCount;
		source.securityGuardList = data.data;
	});

	setTimeout(() => {
		source.loading = false;
	}, 500);
};


//查询监管机构
const searchDeparts = () => {
	ConfigApi().searchDepartsApi({deskTypes: Session.get('platform')==='2' ? ['Proprietor'] : Session.get('platform')==='3' ? ["TemporarySecurity"] : ['Normal']}).then(response => {
		if (response.status == 200) {
			let data = response.data;
			source.searchInfo.options = data;
		}
	})
}

// 获取监管机构
const getGegulators = () => {
	ConfigApi().searchDepartsApi({deskTypes: Session.get('platform')==='2' ? ['Proprietor'] : Session.get('platform')==='3' ? ["TemporarySecurity"] : ['Normal']}).then(response => {
		let { status, message, data } = response;

		if (status !== 200) {
			ElMessage.error(message);
			return;
		}

		source.regulatorsList = data;
	});
}

const resetgetTableData = () => {
	if (source.userInfo.superviseDesk && myCascader.value.getCheckedNodes().length) {
		myCascader.value.$refs.panel.clearCheckedNodes() //重置el-cascader
	}

	let obj = {
		name: '',
		companyName: '',
		idCardNo: '',
		securityStationName: '',
		superviseDepartIds: null,
		options: source.searchInfo.options

	};
	source.superviseDepartIdArr = [];
	source.searchInfo = reactive(obj) as any;
	nextTick(() => {
		getTableData()
	})
};

// 导出
const exportData = () => {
	const params = {
		pageIndex: source.pageIndex,
		pageSize: source.pageSize,
		companyName: source.searchInfo.companyName,
		name: source.searchInfo.name,
		securityStationName: source.searchInfo.securityStationName,
		idCardNo: source.searchInfo.idCardNo,
		superviseDepartIds: source.searchInfo.superviseDepartIds,
		deskTypes: Session.get('platform')==='2' ? ['Proprietor'] : Session.get('platform')==='3' ? ["TemporarySecurity"] : ['Normal']
	};
	source.loading = true;
	ConfigApi().exportunActivatedSecurityApi(params).then(response => {
		setTimeout(() => {
			source.loading = true;
			getTableData()
		}, 500);
		const content = response;
		const blob = new Blob([content as any]);
		const fileName = `未激活人员.xlsx`;
		if ("download" in document.createElement("a")) {
			// 非IE下载
			const elink = document.createElement("a");
			elink.download = fileName;
			elink.style.display = "none";
			elink.href = URL.createObjectURL(blob);
			document.body.appendChild(elink);
			elink.click();
			URL.revokeObjectURL(elink.href); // 释放URL 对象
			document.body.removeChild(elink);
		} else {
			// IE10+下载
			navigator.msSaveBlob(blob, fileName);
		}
	}).catch((error) => { })

};


// 分页条数改变
const onHandleSizeChange = (val: number) => {
	source.pageSize = val;
	getTableData();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
	source.pageIndex = val;
	getTableData();
};
</script>

<style scoped lang="scss">
.section-main-container {
	.section-main-padding {
		padding: 15px;

		.el-table {
			flex: 1;
		}

	}
}
</style>