<template>
	<view class=" knowledge-container">
		<CustomNavbar
			title="知识库"
			type="center"
			:isLeft="true"
			bgColor="#94f1f1"
			@handleLeft="handleLeft"
		/>
		<!-- <view class="bg"></view> -->
		<view class="content" :style="{'margin-top':systemBarHeight + 'px'}">
			<!-- 顶部导航 -->
			<view class="flex-r-b challenge-top" @click="handleMenuSelect">
				<view class="flex-r-c" :class="{ 'challenge-active': currentIndex }"
					>系统知识库</view
				>
				<view class="flex-r-c" :class="{ 'challenge-active': !currentIndex }"
					>我的知识库</view
				>
				<view
					class="challenge-top-bg"
					:style="{ left: currentIndex ? '19%' : '68%' }"
				></view>
			</view>
			<!-- 提示 -->
			<view class="tips flex-r-c"><CustomIcon iconName="exclamation-circle" color="#4E5969" size="30rpx"/>{{
				currentIndex ? tipsText : tipsMyText
			}}</view>
			<!-- 系统知识库 -->
			<view class="system-list pd-12" v-if="currentIndex">
				<view class="item" v-for="(item, index) in dataList" :key="index" @click="toPage(item.url)">
					<view class="title">{{ item.name }}</view>
					<view class="bottom">
						<view
							><text :class="`flag_${item.type} flag` ">{{ changeType(item.type) }}</text
							><text>{{ item.source }}</text></view
						>
						<view>{{ item.createTime }}</view>
					</view>
				</view>
			</view>
			<!-- 我的知识库 -->
			<view class="my-list pd-12" v-else>
				<view class="item" v-for="(item, index) in dataList" :key="index" >
					<view class="bottom">
						<view @click="toPage(item.url)"
							><text :class="`flag_${item.type} flag` ">{{ changeType(item.type) }}</text
							><text>{{ item.createTime }}</text></view
						>
						<view class="switch-box"
							><uv-switch
								v-model="item.status"
								:activeValue="0"
								:inactiveValue="1"
								activeColor="#05D3A2"
								size="24"
                @change.stop="handleSwitchChange(item.id,item.status)"
							/>
							<text class="switch-text" v-if="item.status == 0" >启用</text>
							<text class="switch-text right" v-else>停用</text>
						</view>
					</view>
					<view class="title">{{ item.name }}</view>
					<view class="delete flex-r-c" @click.prevent="handleDelete(item.id)"> 删除 </view>
				</view>
			</view>
			<CustomLoadMore :status="loadStatus" />
		</view>
		<view class="upload" @click="handleUpload">
      <CustomIcon iconName="shangchuan" color="#05D3A2"/>
			<text>上传</text>
		</view>
	</view>
  <uv-modal ref="modal" title="提示" content='是否删除选择的知识库' 
      confirmText="确定"
      confirmColor="#11C3AE"
      :showCancelButton="true"
      @confirm="modalConfirm" align="center"></uv-modal>
</template>

<script lang="ts" setup>
import { ref, inject, onMounted } from "vue";
import baseApi from "@/api/base";
import { onReachBottom } from "@dcloudio/uni-app";
import { requestCommon } from "@/utils/request";
//用于显示提示
const $showToast: any = inject("$showToast");

//当前类型
const currentIndex = ref(true);
//类型展示文本
const tipsText = ref("以下是本系统AI内置的知识库，AI会检索并引用其知识");
//类型展示文本
const tipsMyText = ref(
	"以下是我上传的知识库(仅我可见)，启用后AI会检索并引用其知识，停用则不检索"
);
const loadStatus = ref('nomore')
const modal = ref<any>(null)
const deleteId = ref(0)
//页面数据
const dataList = ref<any>([
]);
// 页面分页数据
const paramsData = ref({
	pageNum:1,
	pageSize:10,
	flagType:0
})
//页面列表总数
const pageTotal = ref(0)
//导航栏返回
const handleLeft = () => {
	uni.navigateBack({ delta: 1 });
};
//菜单切换
const handleMenuSelect = () => {
	currentIndex.value = !currentIndex.value;  // 切换选中的索引
	dataList.value = []  //重置数据
	getData()
};
/**
 * 删除回调
 */
const handleDelete = (id:number) => {
	deleteId.value = id
  modal.value.open()
}
const changeType = (e: string) => {
  let obj: { [key: string]: string } = {
    "0": "标准",
    "1": "药品说明书",
    "2": "医学指南",
    "3": "论文研究",
    "4": "病历",
  };
  return obj[e];
};
/**
 * 删除模态框确认回调
 */
const modalConfirm = async () => {
	await baseApi.delete({knowledgeId:deleteId.value})
	$showToast("删除成功")
	dataList.value = []
	getData()
}
/**
 * 上传文件
 */
 const handleUpload = () => {
  wx.chooseMessageFile({
    count: 1,
    type: 'file',
    extension: ['pdf', 'doc', 'docx'],
    success: async (res:any) => {
      const file = res.tempFiles[0];
      const filePath = file.path;
      console.log(file);
			uni.showLoading()
			await baseApi.uploadKnowledge(filePath)
			$showToast("上传成功")
			
			setTimeout(() => {
				dataList.value = []
				getData()
			},500)
			
      // uni.uploadFile({
      //   url: 'http://192.168.3.206:6699/doctor/base/uploadKnowledge', // 确保这个 URL 是有效的
      //   filePath: filePath,
      //   name: 'file', // 表单中对应的字段名称
			// 	header: {
			// 		Authorization: requestCommon.getToken(),
			// 		"content-type":"multipart/form-data"
			// 	},
      //   formData: {
      //     user: 'test', // 可选的额外数据
      //   },
      //   success: (uploadRes) => {
      //     console.log('上传成功', uploadRes);
      //   },
      //   fail: (err) => {
      //     console.error('上传失败', err);
      //   }
      // });
    },
    fail: (err:any) => {
      console.error('选择文件失败', err);
    }
  });
};

/**
 * 更改切换器回调
 */
const handleSwitchChange = async(id:any,status:number) => {

	await baseApi.changeStatus({knowledgeId:id,status:status == 1 ? 1 : 0})
	$showToast("更改成功")
}
const toPage = (url:string) => {
	uni.navigateTo({url:'/subpackages/webview/index?url='+url})
}
/**
 * 获取页面数据
 */
const getData = async () => {
	loadStatus.value = 'loading'
	paramsData.value.flagType = currentIndex ? 1 : 0
	const {data:{records, total}} = await baseApi.query(paramsData.value)
	dataList.value.push(...records)
	pageTotal.value = total
	
	if(dataList.value.length < total) {
		loadStatus.value = "loadmore"
	}else {
		loadStatus.value = "nomore"
	}
}
onReachBottom(() => {
		loadStatus.value = 'loading'
	if(dataList.value.length < pageTotal.value) {
		++ paramsData.value.pageNum 
		getData()
	}else {
		loadStatus.value = "nomore"
	}
})
const systemBarHeight = ref(0);
// 获取系统栏高度
const getSysteminfo = () => {
	uni.getSystemInfo({
		success: (res) => {
			console.log(res.statusBarHeight);
			systemBarHeight.value = (res.statusBarHeight || 0) + 44
		},
	});
};
onMounted(() => {
	getData()
	getSysteminfo()
})
</script>

<style lang="scss">
@import "./index.scss";
page {
	background-color: #f5f7fa;
}
</style>
