<!-- 情报新增待审批 -->
<script setup lang="ts">
import { useUserStore } from '@/stores/modules/user'
import DataBaseHead from '@/views/home/components/DataBaseHead.vue'
import UserList from '@/views/home/intelligence/process/UserPages.vue'
import {
	getNoticeList,
	deleteWithdraw,
	getManagerList,
	fetchdbReviewFileList,
	fetchdbReview,
	fetchdbWithdraw,
	cateFileUpdate,
	fetchdbAuthGetInfo,
	fetchReviewAuthCateList
} from '@/api/daikin/base'
import { noticeld } from '@/stores/modules/noticeId'
import { databaseld } from '@/stores/modules/database'
import { NTag, useMessage, NModal, NPopover } from 'naive-ui'
import { ArrowDown, Check, Close } from '@element-plus/icons-vue'
const store = noticeld()
const store2 = useUserStore()
const user: any = store2.user
const header = { token: user.token }
console.log('🚀 ~ file: Process.vue:25 ~ user:', user)
const { push } = useRouter()
const database = databaseld()
const route = useRoute()
const listData = ref<any>([])
const message = useMessage()
const activeName = ref(1)
const flg = ref(false)
const userCode = ['admin', 'database_dandang', 'tech_service'].includes(
	store2.user.roleCode
)
const isDbReview = computed(() => !!user?.isDbReview)
const isDbUpload = computed(() => !!user?.isDbUpload)
const Status = reactive({
	reviewStatus: 1,
	reviewSource: 2
})
const pageInfo = reactive({
	currentPage: 1,
	pageNum: 1,
	pageSize: 10,
	total: 10
})
const selCommand = ref<number>()
const selItemId = ref<number>()
const dialogVisible = ref(false)
const dialogText = ref('')
const handleDialogConfirm = async () => {
	const req = { id: selItemId.value, status: selCommand.value }
	const { code }: any = await fetchdbReview(req)
	if (code === 200) {
		message.success('操作成功')
		dialogVisible.value = false
		getPageList()
	}
}
const handleCommand = (command: number, row: any) => {
	selCommand.value = command
	dialogText.value = `确认${command === 2 ? '通过' : '驳回'}标题为 ${
		row.title
	} 的文件发布吗?`
	dialogVisible.value = true
	selItemId.value = row.id
}
const handleSizeChange = (e) => {
	console.log(e)
}
const handleCurrentChange = (e) => {
	console.log(e)
}
async function getPageList(cateId: any = database.database.id) {
	// if (!cateId) return
	listData.value = []
	const { pageNum, pageSize } = pageInfo
	const { rows = [], total = 0 }: any = await fetchdbReviewFileList({
		pageNum,
		pageSize,
		status: activeName.value
		// cateId
	})
	listData.value = rows
	pageInfo.total = total
}
const handleEditClick = async () => {
	const row = { ...editObj.value }
	if (!row) return
	if (!row.cateId) {
		message.error('所属类别不能为空！')
		return
	}
	let url: any[] = []
	if (row.fileList && row.fileList.length > 0) {
		row.fileList.forEach((index: any) => {
			if (index.response) {
				url.push(index.response.url)
			} else {
				url.push(index.url)
			}
		})

		row.filePath = url
	}
	let list: any[] = []
	if (row.userList && row.userList.length > 0) {
		row.userList.forEach((index: any) => {
			list.push(index.userId)
		})
		row.userIdList = list
	}
	const { code }: any = await cateFileUpdate(row)
	if (code === 200) {
		message.success('操作成功')
		getPageList()
		shomk.value = false
	}
}
// 详情页
const clickTo = (data: any) => {}
// 撤回按钮
const clickCancel = (data: any) => {
	const { id, noticeId, reviewStatus } = data
	deleteWithdraw(id).then((res) => {
		console.log(res, '删除结果')
		getPageList()
	})
}
const showDetail = (row: any) => {
	console.log(row, '单选一行')
}
const tabsList = ref([
	{
		name: '审核中',
		id: 1
	},
	{
		name: '审核通过',
		id: 2
	},
	{
		name: '驳回',
		id: 3
	},
	{
		name: '撤回',
		id: 4
	}
])
// tab
const tabsList2 = ref([
	{
		name: '待审核',
		id: 1
	},
	{
		name: '已发布',
		id: 2
	},
	{
		name: '审核驳回',
		id: 3
	},
	{
		name: '撤回',
		id: 4
	}
])
let tabs = ref(isDbReview ? tabsList2.value : tabsList.value)
const goBacks = () => {
	// history.back()
	push('/DataBase')
}

// watchEffect(() => {
// 	getAuth()
// })
watchEffect(() => {
	activeName.value
	getPageList()
})
getTree()

const openUrl = async (it: any) => {
	let { filePath, isSelect } = it
	// if (isSelect === 2) {
	// 	message.info('没有访问权限')
	// 	return
	// }
	if (!filePath) {
		message.info('没有可预览文件！')
		return
	}
	const srcType = getLastSubstring(filePath)
	if (['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'pdf'].includes(srcType)) {
		// src.value = filePath
		// pdfShow.value = true
		filePath = 'https://view.xdocin.com/view?src=' + filePath
		const screenWidth = window.screen.width
		const screenHeight = window.screen.height
		window.open(
			filePath,
			'',
			'width=' +
				screenWidth +
				',height=' +
				screenHeight +
				',top=' +
				0 +
				',left=' +
				0
		)
	} else {
		message.error(
			"文件格式不是 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx','pdf'！"
		)
	}
}
function getLastSubstring(str: string): string {
	const lastIndex = str.lastIndexOf('.')
	if (lastIndex !== -1) {
		return str.substring(lastIndex + 1)
	} else {
		return ''
	}
}

const handTooltip = (data: any[] = []) => {
	return data.map((item: any) => item.nickName)?.join(', ') || ''
}
const editObj = ref<any>({})
const setUserList = ref<any>([])
const showModal = ref(false)
const userData = ref(false)
const shomk = ref(false)
const edit = ref<any>({})
const editClick = (obj: any = {}) => {
	editObj.value = obj
	editObj.value.cateIds = []
	if (obj.filePath) {
		editObj.value.fileList = [
			{
				name: obj.title,
				originalFilename: obj.title,
				url: obj.filePath
			}
		]
	}
	setUserList.value = obj.userList || []
	userData.value = setUserList.value.length > 0 ? true : false
	let ids: any[] = getParentIds(obj.cateId)
	if (ids?.length > 0) {
		ids = ids.reverse()
		// ids.push(obj.cateId)
		editObj.value.cateIds = ids
		console.log('🚀 ~ file: Process.vue:248 ~ ids:', ids)
	}
	shomk.value = true
}

const handleWithdraw = async (row: any) => {
	if (row && row.id) {
		const { code, msg }: any = await fetchdbWithdraw({ id: row.id })
		if (code === 200) {
			message.success('撤回成功')
		} else message.warning(msg)
	}
	getPageList()
}
const handleChild = async (data: any) => {
	const { showModal: show, multipleSelection } = data
	showModal.value = unref(show) || false
	let userIdList: any[] = []
	multipleSelection.value.forEach((i: { userId: any }) => {
		userIdList.push(i.userId)
	})
	editObj.userIdList = userIdList
	if (userIdList.length > 0) {
		userData.value = true
	} else userData.value = false
}

async function getUser(row: { id?: any; userList?: any; type?: number }) {
	showModal.value = !showModal.value
	if (row.id && row.userList) {
		setUserList.value = row.userList
	}
}
const CloseThiss = (data?: boolean) => {
	showModal.value = data || false
	// setUserList.value = []
}

// const arr = [1706, 1416, 1415, 1414, 1413, 1412, 1411, 1410, 1386, 1388, 1391]

const downloads = (data: any = {}) => {
	const { fileCommon, filePath } = data
	if ((fileCommon?.fileSize || 0) > 25 * 1024 * 1024) {
		message.info('正在下载中，请稍等～')
		downloadFile(filePath)
		return
	}
	if (filePath) {
		window.open(filePath)
		// window.open("https://view.officeapps.live.com/op/view.aspx?src=" + encodeURIComponent(data.filePath))
	} else {
		message.info('没有可预览文件！')
	}
}
function downloadFile(url: any) {
	fetch(url)
		.then((response) => response.blob())
		.then((blob) => {
			const downloadUrl = URL.createObjectURL(blob)
			const link = document.createElement('a')
			link.href = downloadUrl
			link.download = getFileNameFromUrl(url)
			link.click()
		})
}
function getFileName(url: string) {
	let lastSplashIndex = url.lastIndexOf('/')
	let lastDotIndex = url.lastIndexOf('.')
	return url.slice(lastSplashIndex + 1, lastDotIndex)
}
function handOnExceed() {
	message.warning('最多只能上传一个文件！')
}

function getFileNameFromUrl(url: string) {
	const lastSlashIndex = url.lastIndexOf('/')
	if (lastSlashIndex !== -1) {
		return url.substring(lastSlashIndex + 1)
	} else {
		return 'Invalid URL'
	}
}

// 获取该目录下是否设置过权限
const hasUpload = ref(false)
const hasReview = ref(false)
async function getAuth() {
	if (!database.database.id) return
	const { data: uploadUser = [] } = await fetchdbAuthGetInfo({
		cateId: database.database.id,
		type: 1
	})
	hasUpload.value = uploadUser.findIndex((x: any) => x.userId === user?.id) > -1
	const { data: reviewUser = [] } = await fetchdbAuthGetInfo({
		cateId: database.database.id,
		type: 2
	})
	hasReview.value = reviewUser.findIndex((x: any) => x.userId === user?.id) > -1
}
const tableData = ref([])
async function getTree() {
	const { data } = await fetchReviewAuthCateList()
	tableData.value = data
}
const handleChange = (e: string | any[]) => {
	console.log(e)
	if (e && e.length == 1) {
		// console.log(e, editB.value)
		edit.value.cateId = e[0]
	} else if (e && e.length == 2) {
		edit.value.cateId = e[1]
	} else if (e && e.length == 3) {
		edit.value.cateId = e[2]
	} else if (e && e.length == 4) {
		edit.value.cateId = e[3]
	} else {
		edit.value.cateId = e[0]
	}
	// console.log(e,editB.value.cateId,99999)
}
// 根据 ID 返回所有父级 ID 的函数
function getParentIds(id: number, list: any[] = tableData.value): any {
	if (!id) return
	for (let i in list) {
		if (list[i].id == id) return [list[i].id]
		if (list[i].childList) {
			let node = getParentIds(id, list[i].childList)
			if (node !== undefined) return node.concat(list[i].id)
		}
	}
}
</script>

<template>
	<div>
		<DataBaseHead />
		<div class="w-full h-1px bg-#507FFD mt50px rd-b-20px"></div>
		<div class="bg-#fff rd-15px px30px w-full h920px relative flex flex-col">
			<div class="q-wrapper flex-1 mt30px text-#142142 flex flex-col bg-#fff">
				<!-- tab标题页 -->
				<el-tabs v-model="activeName">
					<el-tab-pane v-for="item in tabs" :key="item" :name="item.id">
						<template #label>
							<span class="custom-tabs-label">
								<span class="text-20px">{{ item.name }}</span>
							</span>
						</template>
						<div
							class="float-right cursor-pointer rounded-md px20px py10px z-200 bg-#f5f5f5 flex items-center justify-center text-#000 w-100px mb-16px"
							@click="goBacks"
						>
							<el-icon class="text-red"><ArrowLeftBold size="18" /></el-icon>
							返回
						</div>
					</el-tab-pane>
				</el-tabs>

				<div class="w100% h750px overflow-auto">
					<el-table
						class="tableClass"
						:data="listData"
						style="width: 100%; margin-bottom: 20px"
						row-key="id"
						border
						:header-cell-style="{
							background: '#2A7BF7',
							color: '#fff',
							height: '60px',
							lineHeight: '60px',
							textAlign: 'center',
							'font-size': '24px'
						}"
						:cell-style="{ 'text-align': 'center', 'overflow-y': 'auto' }"
						:tree-props="{
							children: 'childList',
							hasChildren: 'hasChildren'
						}"
					>
						<el-table-column
							prop="cateName"
							label="所属分类"
							show-overflow-tooltip
						>
						</el-table-column>
						<el-table-column
							prop="title"
							label="标题名称"
							show-overflow-tooltip
						/>
						<el-table-column prop="deptName" label="上传科室" />
						<el-table-column prop="parentDeptName" label="上传部门" />
						<el-table-column prop="createTime" label="上传日期" />
						<el-table-column
							label="文件列表"
							prop="filePath"
							show-overflow-tooltip
						/>
						<!-- <el-table-column label="排序" prop="sort" show-overflow-tooltip/> -->
						<el-table-column label="查看范围" prop="userIdList">
							<template #default="scope">
								<!-- <el-button type="primary"  class="button" @click="getUser(scope.row)">查看范围</el-button> -->

								<!-- <span class="descStyle" v-if="scope.row.userList" v-for="it in scope.row.userList"> &nbsp;&nbsp; {{it.nickName}}</span> -->
								<!-- <span>{{ scope.row.userList }}</span> -->
								<el-tooltip
									v-if="scope.row.userList.length"
									:content="handTooltip(scope.row.userList)"
									placement="top"
								>
									<div class="descStyle max-w-60vw !h-46px">
										<p
											v-for="(it, e) in scope.row.userList"
											:class="
												scope.row.userList.length < 2 ? '!leading-46px' : ''
											"
										>
											{{ it.nickName }}
											<span v-if="e == 1 && scope.row.userList.length > 2"
												>...共{{ scope.row.userList.length }}人</span
											>
										</p>
									</div>
								</el-tooltip>
							</template>
						</el-table-column>
						<el-table-column prop="address" label="操作" width="300">
							<template #default="{ row }">
								<div>
									<!-- <el-button style="color: #000" @click="openUrl(row)"
										>预览</el-button
									> -->
									<div class="inline-block">
										<n-popover
											trigger="hover"
											placement="top-start"
											v-if="(row.fileCommon?.fileSize || 0) > 25 * 1024 * 1024"
										>
											<template #trigger>
												<el-button style="color: #000" @click="downloads(row)"
													>查看</el-button
												>
											</template>
											<span
												>该文件超过25MB，无法进行预览，请点击 查看
												进行下载！</span
											>
										</n-popover>
										<el-button
											v-else
											style="color: #000"
											@click="downloads(row)"
											>查看</el-button
										>
									</div>
									<el-dropdown
										v-if="activeName === 1 && isDbReview"
										trigger="click"
										@command="handleCommand($event, row)"
									>
										<el-button
											class="ml-16px flex justify-center items-center"
											type="warning"
											@click=""
										>
											审核
											<el-icon class="el-icon--right"><arrow-down /></el-icon>
										</el-button>
										<template #dropdown>
											<el-dropdown-menu>
												<el-dropdown-item :command="2" :icon="Check"
													>同意</el-dropdown-item
												>
												<el-dropdown-item
													:command="3"
													:icon="Close"
													type="danger"
													>驳回</el-dropdown-item
												>
											</el-dropdown-menu>
										</template>
									</el-dropdown>
									<el-button
										v-if="activeName > 2 && isDbUpload"
										type="primary"
										class="ml-16px"
										@click="editClick(row)"
									>
										编辑</el-button
									>
									<template
										v-if="(activeName === 1 || activeName === 3) && isDbUpload"
									>
										<el-popconfirm
											title="确认撤回该文件?"
											@confirm="handleWithdraw(row)"
										>
											<template #reference>
												<el-button class="ml-16px" type="danger">
													撤回</el-button
												>
											</template>
										</el-popconfirm>
									</template>
								</div>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div class="float-right absolute bottom-10px right-30px z-2000 bg-#fff">
					<el-pagination
						v-model:current-page="pageInfo.currentPage"
						v-model:page-size="pageInfo.pageSize"
						layout="prev, pager, next, jumper"
						:total="pageInfo.total"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div>

				<div
					v-if="false"
					v-for="i in listData"
					:key="i"
					class="mt8px cursor-pointer flex items-center p15px pl20px text-18px"
				>
					<NTag
						type="info"
						v-if="i.reviewStatus == 5 && Status.reviewSource === 2"
						class="shrink-0 w80px inline-flex px8px py5px lh-1.5em text-14px rd-6px text-#fff/80 vertical-middle items-center justify-center bg-#547EE9 mr10px"
					>
						个人撤回
					</NTag>
					<NTag
						type="info"
						v-else-if="i.reviewStatus == 4 && Status.reviewSource === 2"
						class="shrink-0 w80px inline-flex px8px py5px lh-1.5em text-14px rd-6px text-#fff/80 vertical-middle items-center justify-center bg-#002FA7 mr10px"
					>
						领导驳回
					</NTag>
					<el-dropdown>
						<span
							class="truncate flex-1 text-#142142 hover:underline w400px max-w400px"
							:title="i.title"
							@click="clickTo(i)"
						>
							{{ i.title }}
						</span>
						<template #dropdown v-if="flg && i.firstReviewName">
							<el-dropdown-menu>
								<el-dropdown-item v-if="i.firstReviewName">
									<div class="ml20px text-#808696 !text-12px flex">
										<span class="min-w120px"
											>初审人：{{ i.firstReviewName }}</span
										>
										<span class="ml20px"
											>初审时间：{{ i.firstReviewTime }}</span
										>
									</div>
								</el-dropdown-item>
								<el-dropdown-item v-if="i.ultimateReviewName">
									<div class="ml20px text-#808696 !text-12px flex">
										<span class="min-w120px"
											>终审人：{{ i.ultimateReviewName }}</span
										>
										<span class="ml20px"
											>终审时间：{{ i.ultimateReviewTime }}</span
										>
									</div>
								</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
					<span class="shrink-0 ml38px text-#808696 w220px">{{
						i.createTime
					}}</span>
					<span
						v-if="store2.user.isReview > 0 && i.publishName"
						class="ml20px text-#808696 text-16px flex-1"
						>来自: {{ i.publishName }}</span
					>
					<span class="absolute right-10px top-18px">
						<el-button @click="clickCancel(i)">撤回</el-button>
					</span>
				</div>
			</div>
		</div>
		<n-modal v-model:show="showModal">
			<UserList
				:userDataList="setUserList"
				@clickChild="handleChild"
				@CloseThis="CloseThiss"
			/>
		</n-modal>
		<NModal v-model:show="shomk" :z-index="99999">
			<div class="bg-#FFF p30px">
				<el-form :model="editObj" label-width="120px" :inline="true">
					<!-- <el-form-item label="标题" v-if="editB.type!='add'"> -->
					<el-form-item label="标题">
						<el-input v-model="editObj.title" />
					</el-form-item>
					<br />
					<el-form-item label="排序">
						<el-input v-model="editObj.sort" type="number" />
					</el-form-item>
					<br />
					<el-form-item label="所属类别">
						<el-cascader
							:modelValue="editObj.cateIds"
							:options="tableData"
							@change="handleChange"
							:props="{ children: 'childList', label: 'name', value: 'id' }"
						/>
					</el-form-item>
					<br />
					<el-form-item label="查看范围">
						<el-button
							class="button"
							size="small"
							@click="getUser"
							:type="userData ? 'success' : ''"
							:icon="userData ? 'Check' : ''"
							>{{ userData ? '已设置' : '设置' }}</el-button
						>
					</el-form-item>

					<br />
					<el-form-item label="文件">
						<el-upload
							v-model:file-list="editObj.fileList"
							class="upload-demo"
							:headers="header"
							action="/test-api/common/upload"
							:on-exceed="handOnExceed"
							multiple
						>
							<el-button type="primary" size="small">选择文件</el-button>
						</el-upload>
					</el-form-item>
					<br />
					<div class="text-center">
						<el-button type="primary" @click="handleEditClick" class="mb-20px">
							确认</el-button
						>
					</div>
				</el-form>
			</div>
		</NModal>
		<el-dialog
			v-model="dialogVisible"
			title="提示"
			width="30%"
			top="40vh"
			center
		>
			<span class="text-18px">
				{{ dialogText }}
			</span>
			<template #footer>
				<span class="dialog-footer">
					<el-button size="large" @click="dialogVisible = false"
						>取消</el-button
					>
					<el-button
						class="!ml-50px"
						size="large"
						type="primary"
						@click="handleDialogConfirm"
					>
						确认
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<style scoped lang="less">
.top {
	position: absolute;
	right: 30px;
	top: -92px;
}

::-webkit-scrollbar {
	width: 1px;
}

.q-wrapper {
	// border-radius: 18px;
	// border: 1px solid #e7ebf5;
	// box-shadow: inset 1px 2px 12px rgba(14, 86, 221, 0.32);
	overflow: auto;
}
.descStyle {
	overflow: hidden;
	text-overflow: ellipsis;
	word-break: break-all;
	display: -webkit-box;
	-webkit-line-clamp: 3; //行数
	-webkit-box-orient: vertical;
}
.tableClass .cell {
	padding: 0 !important;
	height: 50px;
	line-height: 25px !important;
	text-align: center;
}
:deep {
	.el-dropdown-menu__item {
		font-weight: bold;
		&:nth-child(2) {
			color: red;
		}
	}
	.el-popconfirm__main {
		white-space: nowrap !important;
	}
}
</style>
