<template>
	<basic-container>
	  <avue-crud 
			ref="crud"
			:option="option"
			:table-loading="loading"
			:data="tableList"
			:permission="permissionList"
			@on-load="onLoad"
			@refresh-change="onLoad"
			@search-change="searchChange"
			@search-reset="searchReset"
			v-model="formData"
			@row-save="rowSave"
			@row-update="rowUpdate"
			@row-del="handleDelete"
			v-model:page="page"
			@current-change="currentChange"
			@size-change="sizeChange"
			:before-open="beforeOpen"
			:upload-error="uploadError"
			:upload-before="uploadBefore"
			:upload-after="uploadAfter"
			:upload-preview="uploadPreview">
	  </avue-crud>
	</basic-container>
</template>

<script>
	import {getList, getDetail, add, update, remove} from "@/api/systemSet/notice";
	import {mapGetters} from "vuex";
	
	export default {
		data () {
			return {
				query: {},
				loading: false,
				page: {
				  pageSize: 10,
				  currentPage: 1,
				  total: 0
				},
				tableList: [{}],
				formData: {},
				option: {
					height: 'auto',
					calcHeight: 32,
					index: true,
					indexLabel: '序号',
					indexWidth: 60,
					menuFixed: true,
					menuWidth: 200,
					border: true,
					searchMenuSpan:6,
					searchMenuPosition: "left",
					searchGutter:20,
					labelWidth: 98,
					dialogWidth: '800',
					gutter:10,
					column:[
						{
							label: '公告类型',
							prop: 'objType',
							minWidth: 200,
							search: true,
							span:24,
							rules: [{
								required: true,
								message: '请选择',
								trigger: 'change',
							}],
							type: 'select',
							dicUrl: '/blade-system/dict/dictionary?code=notice_type',
							props: {
								label: 'dictValue',
								value: 'dictKey',
							},
						},
						{
							label: '公告标题',
							prop: 'title',
							minWidth: 200,
							search: true,
							span:24,
							rules: [{
								required: true,
								message: '请输入',
								trigger: 'blur',
							}],
						},
						{
							label: '创建时间',
							prop: 'createTime',
							minWidth: 200,
							display:false,
						},
						{
							label:'指定服务商',
							prop: 'siteId',
							span:24,
							type: 'select',
							dicUrl: '/sf/operationSite/list',
							props: {
								label: 'name',
								value: 'id',
							},
							// dicFormatter:(res)=>{
							// 	return res.data.records
							// },
							hide:true,
							filterable:true,
							multiple: true,
							// collapseTags: true,
							// maxCollapseTags: 3,
							// collapseTagsTooltip: true,
						},
						{
							label:'公告内容',
							prop: 'html',
							span:24,
							component: 'avue-ueditor',
							hide:true,
							action: '/blade-resource/oss/endpoint/put-file?code=aliyun',
							propsHttp: {
							  res: 'data',
							  url: 'link',
							},
						},
						{
						  label: '附件上传',
						  prop: 'fileUrl',
						  type: 'upload',
						  loadText: '上传中，请稍等',
						  span: 24,
							limit:1,
							dataType: 'object',
							propsHttp: {
								home:this.imgUrl,
							  res: 'data',
								url:'name',
								name:'originalName'
							},
							action: '/blade-resource/oss/endpoint/put-file?code=aliyun',
							tip:'1.您可以上传需要用到的技术资料，每份最大30MB，支持格式:jpg、png、gif、doc、docx、ppt、pdf、xls、xlsx、txt、mp4、mp3、avi、mov、mmvb、mm、fliv、3gp；2.禁止上传违反新能源相关规定的内容，一切风险均由本人承担!',
							hide:true,
						},
					]
				},
			}
		},
		computed: {
		  ...mapGetters(["permission"]),
		  permissionList() {
		    return {
		      addBtn: this.validData(this.permission.notice_add, false),
		  		editBtn:this.validData(this.permission.notice_edit, false),
		  		delBtn:this.validData(this.permission.notice_del, false),
		    };
		  },
		},
		methods:{
			beforeOpen(done, type) {
			  if (['edit', 'view'].includes(type)) {
					// getDetail(this.formData.id).then(res=>{
						
					// })
			    if(this.formData.fileUrl){
			    	this.formData.fileUrl = [{
			    		label:this.formData.originalName,
			    		value:this.formData.fileUrl
			    	}];
			    }
			  }
			  done();
			},
			uploadBefore(file, done, loading, column) {
					console.log("上传前",file, column);
					const maxSize = 30 * 1024 * 1024;
					if(file.size > maxSize){
						this.$message.error('文件大小不能超过 30MB!');
					}else{
						done()
					}
					// 如果你想修改file文件,由于上传的file是只读文件，必须复制新的file才可以修改名字，完后赋值到done函数里,如果不修改的话直接写done()即可
					// var newFile = new File([file], {type: file.type});
					// done(newFile)
			},
			uploadAfter(res, done, loading, column) {
					// 该位置拼接有问题
					console.log("上传后",res);
					// 后端需直接返回name=“xxxx” url=“xxxx” 才行，可以看avue官网的上传 F12 中看network 就可以看到她的返回格式
					// 刚开始我以为可以直接进行 imgUrL 的push  无论怎么使用，都是有问
					// 多个文件的上传，在 propsHttp 配置为  res: 'data.0' 就会多次调用uploadAfter方法，进行对图片，文件的回显操作
					done();
					// this.$message.success('上传后的方法')
			},
			// 上传错误
			uploadError (error, column) {
				this.$message.success('上传失败，' + error)
				console.log("上传错误",error, column)
			},
			uploadPreview(file,column,done){
				console.log("查看",file,column)
				let suffix = file.url.substring(file.url.lastIndexOf('.') + 1) //获取文件后缀
				if(suffix.search(/doc|docx|ppt|pdf|xls|xlsx|txt/) != -1){
					// let href = 'https://view.officeapps.live.com/op/view.aspx?src='+ encodeURIComponent(file.url)
					window.open(file.url, "_blank");
				}else{
					done();
				}
			},
			onLoad() {
			  this.loading = true;
			  getList(this.page, this.query).then(res => {
			    const data = res.data.data;
			    this.page.total = data.total;
			    this.tableList = data.records;
			    this.loading = false;
			  });
			},
			searchReset() {
			  this.query = {};
			  this.onLoad();
			},
			searchChange(params, done) {
			  this.query = params;
			  this.page.currentPage = 1;
			  this.onLoad();
			  done();
			},
			currentChange(currentPage){
			  this.page.currentPage = currentPage;
			},
			sizeChange(pageSize){
			  this.page.pageSize = pageSize;
			}, 
			rowSave(row, done, loading) {
				// row.fileUrl = row.fileUrl ? row.fileUrl.split(",").map(itm=> itm.replace(this.imgUrl,'')).join(",") : '';
				let formData = JSON.parse(JSON.stringify(row))
				formData.originalName = row.fileUrl[0].label;
				formData.fileUrl = row.fileUrl[0].value;
			  add(formData).then(res => {
					this.onLoad();
					this.$message({
						type: 'success',
						message: '操作成功!',
					});
					done(formData);
				}, error => {
					window.console.log(error);
					loading();
				});
			},
			rowUpdate(row, index, done, loading) {
				// row.fileUrl = row.fileUrl ? row.fileUrl.split(",").map(itm=> itm.replace(this.imgUrl,'')).join(",") : '';
				let formData = JSON.parse(JSON.stringify(row))
				formData.originalName = row.fileUrl[0].label;
				formData.fileUrl = row.fileUrl[0].value;
			  update(formData).then(() => {
			    this.onLoad();
			    this.$message({
			      type: "success",
			      message: "操作成功!"
			    });
			    done();
			  }, error => {
			    loading();
			    console.log(error);
			  });
			},
			handleDelete(row) {
			  this.$confirm("是否确认删除该公告?", {
			    confirmButtonText: "确定",
			    cancelButtonText: "取消",
			    type: "warning"
			  }).then(() => {
					return remove(row.id);
				}).then(() => {
					this.onLoad();
					this.$message({
						type: "success",
						message: "操作成功!"
					});
				});
			},
		}
	}
</script>

<style>
</style>