<template>
    <div class="system-dept-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-dept-search mb15">
				<span>模块:</span>
				<el-select @change="handleChangeModule" size="default" v-model="state.tableData.param.moduleName" placeholder="请选择" clearable style="max-width: 180px;margin:0 10px;">
                    <el-option 
					:data-op="item.id" v-for="(item,index) in moduleList" 
					:key="index" 
					:label="item.moduleName" 
					:value="item.moduleName">
				</el-option>
                </el-select>
				<span>标签:</span>
                <el-select size="default" v-model="state.tableData.param.labelName" placeholder="请选择" clearable class="ml10" style="max-width: 180px;margin:0 10px;">
					<el-option 
					v-for="(item,index) in labelList" 
					:key="index" 
					:label="item.name" 
					:value="item.name">
				</el-option>
                </el-select>
				<span>名称:</span>
                <el-input size="default" placeholder="请输入" v-model="state.tableData.param.name" class="ml10" style="max-width: 250px;margin-right: 20px;"> </el-input>
				<el-button @click="getTableData" size="default" type="primary" class="ml10" style="margin-right: 15px;">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button @click="reset" size="default" type="primary" class="ml10"  style="margin-right: 15px;">
					<el-icon>
						<ele-RefreshRight />
					</el-icon>
					重置
				</el-button>
				<el-button @click="switchDrawer(0)" size="default" type="primary" class="ml10">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					添加图片
				</el-button>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%" class="custom-table">
				<el-table-column type="selection" width="55" />
				<el-table-column prop="name" label="图片名称"  show-overflow-tooltip width="180px"></el-table-column>
				<el-table-column  label="素材"  width="300px" align="center">
					<template #default="scope">
						<el-image lazy :src="jpgFormatter(scope.row)" preview-teleported="true" :preview-src-list="[jpgFormatter(scope.row)]"/>
					</template>
				</el-table-column>
				<el-table-column prop="moduleName" label="模块"  show-overflow-tooltip width="200px" align="center"></el-table-column>		
				<el-table-column prop="labelName" label="标签"  show-overflow-tooltip width="200px" align="center"></el-table-column>		
				<el-table-column prop="uploadName" label="上传者"  show-overflow-tooltip width="200px" align="center"></el-table-column>		
				<el-table-column prop="createtime" label="创建时间" :formatter="dateFormatter" show-overflow-tooltip width="200px" align="center"></el-table-column>
				<el-table-column label="操作" width="250" align="center">
					<template #default="scope">
						<el-button  text type="primary" @click="switchDrawer(2,scope.row.id)">
							<el-icon>
								<ele-View />
							</el-icon>
						</el-button>
						<el-button  text type="primary" @click="switchDrawer(1,scope.row.id)">
							<el-icon>
								<ele-Edit />
							</el-icon>
						</el-button>
						<el-button  text type="primary" @click="download(scope.row)">
							<el-icon>
								<ele-Download />
							</el-icon>
						</el-button>
						<el-button  text type="primary" @click="deleteBanner(scope.row.id)">
							<el-icon>
								<ele-Delete />
							</el-icon>
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 新增或编辑弹窗  -->
			<el-drawer
				v-model="dialog"
				:title="changeTitle()"
				@close="resetForm"
				direction="rtl"
				size="45%"
			>
				<div class="demo-drawer__content">
					<el-form  
						ref="ruleFormRef"
						style="max-width: 85%"
						:model="state.formData"
						:rules="state.rules"
						label-width="110px"
						class="demo-ruleForm"
						:size="formSize"
						status-icon
						v-loading="state.formData.loading"
						:disabled="isForbidden"
					>
						<el-form-item label="模块:" prop="moduleName">
							<el-select @change="handleChangeModule" size="default" v-model="state.formData.moduleName" placeholder="请选择" clearable>
								<el-option 
									:data-op="item.id" v-for="(item,index) in moduleList" 
									:key="index" 
									:label="item.moduleName" 
									:value="item.moduleName">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="标签:" prop="labelName">
							<el-select size="default" v-model="state.formData.labelName" placeholder="请选择" clearable >
								<el-option 
									v-for="(item,index) in labelList" 
									:key="index" 
									:label="item.name" 
									:value="item.name">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="图片名称:" prop="name" >
							<el-input v-model="state.formData.name" />
						</el-form-item>
						<el-form-item label="图片:" prop="fileList">
							<el-upload ref="uploadRef" action="#" list-type="picture-card" :class="{disabled:uploadDisabled}" 
							:limit="1" :file-list="state.formData.fileList" :on-change="handleChange" :auto-upload="false">
							<el-icon><Plus /></el-icon>
							<template #file="{ file }">
							<div>
								<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
								<span class="el-upload-list__item-actions">
								<span
									class="el-upload-list__item-preview"
									@click="handlePictureCardPreview(file)"
								>
									<el-icon><zoom-in /></el-icon>
								</span>
								<span
									v-if="!disabled"
									class="el-upload-list__item-delete"
									@click="handleRemove(file)"
								>
									<el-icon><Delete /></el-icon>
								</span>
								</span>
							</div>
							</template>
						</el-upload>
						<el-dialog v-model="dialogVisible">
							<img :src="dialogImageUrl"  style="width: 100%"  alt="Preview Image" />
						</el-dialog>
						</el-form-item>
					</el-form>
					<div class="demo-drawer__footer">
						<el-button v-show="isHide" @click="submitForm(flag)" :loading="loading" style="margin-right: 30px;" >
							{{ loading ? '保存 ...' : '保存' }}
						</el-button>
						<el-button type="primary" @click="resetForm">取消</el-button>
					</div>
				</div>
			</el-drawer>
			<!-- 分页器 -->
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30]"
				v-model:current-page="state.tableData.param.current"
				background
				v-model:page-size="state.tableData.param.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="photos">
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElDrawer, ElMessage, ElMessageBox, TableColumnCtx, timePickerDefaultProps } from 'element-plus';
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { ComponentSize, FormInstance, FormRules, UploadFile, UploadProps, UploadUserFile } from 'element-plus'
import { baseUrlHost } from '../../api/baseUrlHost';
import { photosApi } from '/@/api/photos';
import { downloadPhoto } from '../../api/download';

const router = useRouter();

// 数据
const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			labelName: '',
			moduleName: '',
			name:'',
			current: 1,
			size: 10,
		},
	},
	formData: {
		labelName: '',
		moduleName: '',
		fileList: [],
		name:"",
		loading: false
	},
	rules: {
		name: [
    		{ required: true, message: '请输入名称', trigger: 'blur' }
		],
		fileList: [
			{ required: true, message: '请选择图片', trigger: 'blur' }
		],
		moduleName: [
			{ required: true, message: '请选择模块', trigger: 'blur' },
		],
		labelName: [
			{ required: true, message: '请选择标签', trigger: 'blur' },
		],
	},
});

// 引入 api 请求接口
const photoApi = photosApi();

// 模块列表
const moduleList = ref([]);

const getModuleList = async() => {
	try {
		let res = await photoApi.getModuleList();
		if(res?.success){
			moduleList.value = res.data;
		}else{
			ElMessage.error('模块列表获取失败！');
		}
	} catch (error) {
		ElMessage.error('模块列表获取失败！');
	} finally {
	}
}

// 标签列表
const labelList = ref([]);

// 模块选择
const handleChangeModule = async(val: any) => {
	try {
		state.tableData.param.labelName = '';
		state.formData.labelName = '';
		if(!val){labelList.value=[]; return;}
		const op:any = event?.currentTarget;
		let res = await photoApi.getLabelList(op.dataset.op);
		if(res?.success){
			labelList.value = res.data;
		}else{
			ElMessage.error('标签列表获取失败！');
		}
	} catch (error) {
		ElMessage.error('标签列表获取失败！');
	} finally {
	}
}

// #region

// 获取表格数据
const getTableData = async() => {
	try {
		state.tableData.loading = true;
		let res = await photoApi.getPhotosList(state.tableData.param);
		if(res?.success){
			state.tableData.data = res.data.records;
			state.tableData.total = res.data.total;
		}else{
			ElMessage.error('图片列表获取失败！');
		}
	} catch (error) {
	} finally {
		state.tableData.loading = false;
	}
};

// 重置
const reset = () =>{
	state.tableData.param = {
		name: '',
		current: 1,
		size: 10,
	}
	getTableData();
}

// 图片基本路径
const viteUrl = import.meta.env.VITE_API_URL;

// 图片链接格式化
const jpgFormatter = (row: any) => {
	let newPath;
	if (row?.data) {
		newPath = row.data.path.replaceAll('\\', '/')	
	} else {
		newPath = row.path.replaceAll('\\\\', '/')	
	}
	newPath = newPath.includes('http://8.138.171.103/')||newPath.includes('http://guojunjie.oss-cn-hangzhou.aliyuncs.com/') ? 
	newPath : encodeURI(viteUrl + newPath)
	console.log(newPath);
	
  	return `${newPath}`;
}

// 日期格式化
const dateFormatter = (row: any, column: TableColumnCtx<String>) => {
	let date = new Date(row.createtime);
  	return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.size = val;
	getTableData();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.current = val;
	getTableData();
};
// #endregion

// #region
const dialog = ref(false)
const flag = ref(false)


const formSize = ref<ComponentSize>('large')
const ruleFormRef = ref<FormInstance>()
const uploadDisabled = ref(false)
const isHide = ref(false)
const headTitle = ref("")

const changeTitle = () => {
	if (flag.value) {
		headTitle.value="新增图片"
	} else {
		headTitle.value="编辑图片"
	}
	if (!isHide.value) {
		headTitle.value="查看图片"
	}
	return headTitle.value;
}

// 获取图片详情
const getPhotoDetail = async (id: number) => {
	state.formData.loading = true;
		let res = await photoApi.getPhotosDetail(id)
		if (res?.success) {
			state.formData.fileList.push({ url: jpgFormatter(res) });
			Object.assign(state.formData, res.data);
			state.formData.path = res.data.path;
			uploadDisabled.value = true;
			state.formData.loading = false;
		} else {
			ElMessage.error('获取图片详情失败！')
			state.formData.loading = false;
		}
}

const isForbidden = ref(false)

// 切换右侧边栏
const switchDrawer = async (staus,id: number) => {
	if (staus == 1) {
		flag.value = false;
		isHide.value = true;
		disabled.value = false;
		getPhotoDetail(id);
	} else if (staus == 2) {
		isForbidden.value = true;
		isHide.value = false;
		disabled.value = true;
		getPhotoDetail(id);
	} else {
		console.log("添加图片");
		flag.value = true;
		isHide.value = true;
	}
	dialog.value = true;
}

// 添加图片
const disabled = ref(false)

const handleChange: UploadProps['onChange'] = async (file: uploadFile, uploadFiles) => {
	state.formData.loading = true;
	if (file.raw.type === 'image/png' || file.raw.type === 'image/jpeg' || file.raw.type === 'image/jpg') {
		state.formData.fileList = uploadFiles;
		uploadDisabled.value = true;
		try {
			const formdata = new FormData();
			formdata.append('file', file.raw);
			let res = await photoApi.uploadFile(formdata);
			if(res?.success){
				state.formData.url = jpgFormatter(res);
				state.formData.path = res.data.path;
				ElMessage({
					message: '图片上传成功！',
					type: 'success',
				})
				state.formData.loading = false;
			}else{
				ElMessage.error('图片上传失败！');
			}
		} catch (error) {
			state.formData.loading = false;
			console.log(error);
			
			ElMessage.error('图片上传失败！');
		}
	} else {
		ElMessageBox.alert('图片的格式不正确，请重新选择！', '提示', {
			confirmButtonText: '确定',
		})
		console.log("handleChange3",uploadFiles);
		uploadFiles.pop()
		console.log("handleChange4",uploadFiles);
		uploadDisabled.value = false;
	}
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePictureCardPreview = (file: UploadFile,uploadFiles) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const uploadRef = ref();

const handleRemove = (file: UploadFile, uploadFiles) => {
	uploadRef.value.clearFiles();
	state.formData.path = "";
	uploadDisabled.value = false;

};

//下载图片
const download = async(row:any) =>{
	state.formData.loading = true;
	let newPath;
	if (row?.data) {
		newPath = row.data.path.replaceAll('\\', '/')	
	} else {
		newPath = row.path.replaceAll('\\\\', '/')	
	}
	newPath = newPath.includes('http://localhost:8888/') ? newPath : viteUrl + newPath
	try{
		await downloadPhoto(newPath);
	}catch(error){
		console.error(error);
		ElMessage.error('图片下载失败！')
	}finally{
		state.formData.loading = false;
	}
}; 

// 删除图片
const deleteBanner = (id: number) => {
	ElMessageBox.confirm('确定要删除该图片吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
	.then(async() => {
		try {
			state.tableData.loading = true;
			let res = await photoApi.deletePhotos(id);
			if(res?.success){ 
				await getTableData();
				ElMessage.success('图片删除成功！');
			} else ElMessage.error('图片删除失败！');
		} catch(e) {
			ElMessage.error('删除失败！');
		} finally {
			state.tableData.loading = false;
		}
	})
} 

const loading = ref(false)

//保存
const submitForm = (decision) => {
	ruleFormRef.value?.validate(async(valid: boolean) => {
		if (valid) {
			if (decision) {
				console.log("新增新增新增");
				loading.value = true;
				const form = { ...state.formData };
				try {
					let res = await photoApi.addPhotos(form);
					if(res?.success){
						ElMessage({
							message: '保存成功！',
							type: 'success',
						})
						loading.value = false;
						getTableData();
						dialog.value = false;
					}
				} catch (error) {
					console.log(error);
					ElMessage.error('保存失败！');
					loading.value = false;
				}
			} else {
				console.log("编辑编辑编辑");
				const form = { ...state.formData };
				try {
					let res = await photoApi.updatePhotos(form);
					if(res?.success){
						ElMessage({
							message: '保存成功！',
							type: 'success',
						})
						loading.value = false;
						getTableData();
						dialog.value = false;
					}
				} catch (error) {
					console.log(error);
					ElMessage.error('保存失败！');
					loading.value = false;
				}
			}
        }else{
			ElMessage.error('请填写必要信息！');
			loading.value = false;
		}
    });
}

// 表单重置和取消
const resetForm = () => {
	dialog.value = false;
	ruleFormRef.value?.resetFields();
	state.formData.fileList.pop();
	uploadDisabled.value = false;
	isForbidden.value = false;
}

// #endregion

onMounted(() => {
	getTableData();
	getModuleList();
})

</script>

<style scoped lang="scss">
.system-dept-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		
		.el-table {
			flex: 1;
			width: 100%;
			table-layout: fixed;
		}
	}
	
};

::v-deep .el-table__body{
	width: 100% !important;
}

::v-deep .el-image {
  width: 250px; // 固定图片宽度
  height: 150px; // 固定图片高度
  object-fit: cover; // 图片居中剪裁
  display: block;
}

::v-deep .el-drawer .el-drawer__header {
	margin: 15px 0 20px 0!important;
    border-bottom: 0!important;
}
::v-deep .el-drawer__title {
    font-size: 28px!important;
}
::v-deep .el-form-item--large{
    --font-size: 18px;
    margin-bottom: 28px!important;
}

.demo-drawer__footer{
	margin:40px 0 0 150px!important;
}

::v-deep .disabled{
    .el-upload--picture-card{
      display: none;
    }
}

::v-deep .el-select--large .el-select__wrapper {
    padding: 5px 10px;
    min-height: 30px;
}

::v-deep .el-form {
    margin: 0 19px;
}
</style>