<template>
	<div class="content-main">
		<el-form inline class="search-content">
			<el-row>
				<el-form-item label="模板名称:">
					<el-input
						auto-complete="off"
						placeholder="请输入"
						clearable
						style="width: 180px"
						v-model="searchForm.xmmbmc"
					></el-input>
				</el-form-item>
				<el-form-item label="项目阶段:">
					<el-input
						auto-complete="off"
						placeholder="请输入"
						clearable
						style="width: 180px"
						v-model="searchForm.xmjd"
					></el-input>
				</el-form-item>
				<el-form-item>
					<div class="search-button">
						<span class="search-line"></span>
						<el-button
							type="primary"
							size="small"
							class="iconfont iconchaxun"
							@click="getList"
							>&nbsp;查询</el-button
						>
						<el-button
							type="primary"
							size="small"
							class="iconfont iconzhongzhi"
							@click="reset"
							>&nbsp;重置</el-button
						>
					</div>
				</el-form-item>
			</el-row>
		</el-form>
		<el-row class="solid"></el-row>
		<div class="addBtnBg">
			<el-button
				type="primary"
				@click="showDialog(null, 'add')"
				class="iconfont iconxinzeng"
				>新增</el-button
			>
		</div>
		<el-table border :data="tableData" style="margin-top: 20px">
			<el-table-column
				type="index"
				sortable
				label="序号"
				width="80"
				align="center"
			>
				<template slot-scope="scope">
					<span>{{ scope.$index + 1 }}</span>
				</template>
			</el-table-column>
			<el-table-column
				align="center"
				show-overflow-tooltip
				sortable
				label="模板名称"
				prop="xmmbmc"
			></el-table-column>
			<el-table-column
				align="center"
				show-overflow-tooltip
				sortable
				label="项目阶段"
				prop="xmjd"
			></el-table-column>
			<el-table-column
				align="center"
				show-overflow-tooltip
				sortable
				label="发布时间"
				prop="xmfbsjFormat"
			></el-table-column>
			<el-table-column align="center" label="操作">
				<template slot-scope="scope">
					<el-tooltip
						class="item"
						effect="light"
						content="查看"
						placement="top"
					>
						<el-button
							type="primary"
							size="small"
							class="operate_show_btn iconfont iconchakan2"
							@click="showDialog(scope.row, 'see')"
						></el-button>
					</el-tooltip>
					<el-tooltip
						class="item"
						effect="light"
						content="修改"
						placement="top"
						v-if="buttonNameList.indexOf('修改') > -1"
					>
						<el-button
							type="primary"
							size="small"
							class="operate_edit_btn iconfont iconxiugai"
							@click="showDialog(scope.row, 'edit')"
						></el-button>
					</el-tooltip>
					<el-tooltip
						class="item"
						effect="light"
						content="删除"
						placement="top"
						v-if="buttonNameList.indexOf('删除') > -1"
					>
						<el-button
							type="primary"
							size="small"
							class="operate_delete_btn iconfont iconshanchu"
							@click="removeInfo(scope.row)"
						></el-button>
					</el-tooltip>
				</template>
			</el-table-column>
		</el-table>
		<el-row class="pagination-wrap">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page.sync="pageForm.pageNum"
				:page-sizes="[10, 20, 30, 40, 50]"
				:page-size="pageForm.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageForm.total"
			></el-pagination>
		</el-row>
		<el-dialog
			title="项目模板下载"
			:visible.sync="dialogVisible"
			width="80%"
			:before-close="handleClose"
			:close-on-click-modal="false"
		>
			<el-form
				label-width="140px"
				:model="ruleForm"
				:rules="rules"
				ref="ruleForm"
			>
				<el-row>
					<el-form-item label="项目模板名称:" prop="xmmbmc">
						<el-input
							placeholder="请输入"
							v-model="ruleForm.xmmbmc"
							:disabled="editable"
						></el-input>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="项目阶段:" prop="xmjd">
						<el-input
							placeholder="请输入"
							v-model="ruleForm.xmjd"
							:disabled="editable"
						></el-input>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="模板简介:">
						<el-input
							placeholder="请输入"
							type="textarea"
							:rows="3"
							v-model="ruleForm.xmmbjj"
							:disabled="editable"
						></el-input>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="模板附件:">
						<el-upload
							:before-upload="beforeUpload"
							class="upload-demo"
							:action="actionUrl"
							:on-preview="handlePreview"
							:on-remove="handleRemove"
							:before-remove="beforeRemove"
							:limit="1"
							:on-exceed="handleExceed"
							:on-success="handleSuccess"
							:file-list="templateFileList"
						>
							<el-button
								type="primary"
								size="small"
								:disabled="editable"
								v-if="!editable"
								>点击上传</el-button
							>
						</el-upload>
						<!-- <div
							class="fileList"
							v-for="(item, index) in this.templateFileList"
							:key="index"
							v-if="item.status == 1"
						>
							<i
								class="close"
								@click="deleteFile(index)"
								v-if="!editable"
							></i>
							<span
								class="name"
								@click="downLoadFile(item.fileId)"
							>
								{{ item.fileName }}
							</span>
						</div> -->
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="项目发布人:" prop="xmfbr">
						<el-input
							placeholder="请输入发布人"
							disabled
							v-model="ruleForm.xmfbr"
						></el-input>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="项目发布时间:" prop="xmfbsj">
						<el-input
							placeholder="请输入发布时间"
							disabled
							v-model="ruleForm.xmfbsjFormat"
						></el-input>
					</el-form-item>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button
					type="primary"
					class="iconfont iconfabu"
					@click="saveInfo('ruleForm')"
					v-if="!editable"
					>发布</el-button
				>
				<el-button
					type="primary"
					class="iconfont iconfanhui"
					@click="handleClose"
					>返回</el-button
				>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { fileApi } from '@/api'
import { authorityControl } from '@/api/login/login'
import {
	projectTemplatePage,
	getProjectTemplate,
	saveProjectTemplate,
	updateProjectTemplate,
	removeProjectTemplate,
} from '@/api/projectManagement/index'
import { getNowDate, dateTimeFormat } from '@/utils/utils'
let _file = []
export default {
	name: 'projectDownload',
	data() {
		return {
			searchForm: {
				mbmc: '',
				xmjd: '',
			},
			pageForm: {
				pageNum: 1,
				pageSize: 10,
				total: 1,
			},
			// 表格数据
			tableData: [],
			// 弹窗控制
			dialogVisible: false,
			// 表单控制
			editable: false,
			// 提交form
			ruleForm: {},
			// 表单验证
			rules: {
				// 项目模板名称
				xmmbmc: [
					{
						required: true,
						message: '请输入标题',
						trigger: 'blur',
					},
				],
				// 项目阶段
				xmjd: [
					{
						required: true,
						message: '请输入阶段',
						trigger: 'blur',
					},
				],
				// 项目发布人
				xmfbr: [
					{
						required: true,
						message: '请输入阶段',
						trigger: 'change',
					},
				],
				// 项目发布时间
				xmfbsj: [
					{
						required: true,
						message: '请输入阶段',
						trigger: 'change',
					},
				],
				// 模板附件
				// templateFileList: [{
				// 	required: true,
				// 	message: '请上传附件',
				// 	trigger: 'change',
				// }],
			},
			// 用户名
			orgName: '',
			// 当前时间
			nowTime: '',
			// 模板附件
			templateFileList: [],
			// 文件上传路径
			actionUrl: fileApi + '/file/upload',
			buttonNameList: [],
		}
	},
	methods: {
		getButtonList(menuCode, userCode) {
			let codeData = {
				resourceCode: menuCode,
				userId: userCode,
			}
			authorityControl(codeData).then((res) => {
				let buttonNameList = []
				res.data.forEach((item) => {
					this.buttonNameList.push(item.resourceName)
				})
			})
		},
		beforeUpload(file) {
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				this.$message.error('上传文件大小不能超过 200MB!')
			}
			return isLt200M
		},
		handleRemove(file) {
			if (!file.fileId) {
				return
			}
			if (file.sjId) {
				this.templateFileList[0].status = 0
				_file = [...this.templateFileList]
			}
			this.templateFileList.length = 0
		},
		handlePreview(file) {
			window.open(`${fileApi}/file/download?id=${file.fileId}`)
		},
		handleExceed(files, fileList) {
			this.$message.warning(
				`当前限制选择 1 个文件，本次选择了 ${
					files.length
				} 个文件，共选择了 ${files.length + fileList.length} 个文件`
			)
		},
		beforeRemove(file, fileList) {
			if (!file.fileId) {
				return
			}
			return this.$confirm(`确定移除 ${file.name}？`, '提示')
		},
		// 获取上传返回信息
		handleSuccess(res, file) {
			let obj = {
				fileId: res.data.id,
				fileName: res.data.name,
				name: res.data.name,
				status: 1,
			}
			this.templateFileList = []
			this.templateFileList.push(obj)
			console.log(this.templateFileList)
		},
		// 文件下载
		downLoadFile(id) {
			window.open(`${fileApi}/file/download?id=${id}`)
		},
		// 删除文件
		deleteFile(index) {
			this.templateFileList[index].status = 0
		},
		// 分页页数
		handleSizeChange(val) {
			this.pageForm.pageSize = val
			this.getList()
		},
		// 分页每页显示几个
		handleCurrentChange(val) {
			this.pageForm.pageNum = val
			this.getList()
		},
		handleClose() {
			this.dialogVisible = false
			this.getList()
		},
		// 列表查询
		getList(type) {
			if (type != 'start') {
				//非初始化调用：查询、分页
				sessionStorage.setItem(
					'searchData',
					JSON.stringify(this.searchForm)
				)
				sessionStorage.setItem(
					'pageData',
					JSON.stringify(this.pageForm)
				)
			} else {
				//初始化分两种情况，详情页等返回后的初始化，以及第一次进入此菜单的初始化
				if (JSON.parse(sessionStorage.getItem('searchData'))) {
					//详情页返回后，将对应查询条件和分页的字段赋值，页面回显参数
					this.searchForm = JSON.parse(
						sessionStorage.getItem('searchData')
					)
					this.pageForm = JSON.parse(
						sessionStorage.getItem('pageData')
					)
				} else {
					//第一次进去此菜单时，保存上方默认的data
					sessionStorage.setItem(
						'searchData',
						JSON.stringify(this.searchForm)
					)
					sessionStorage.setItem(
						'pageData',
						JSON.stringify(this.pageForm)
					)
				}
			}
			let data = {
				pageSize: this.pageForm.pageSize,
				pageNum: this.pageForm.pageNum,
				xmmbmc: this.searchForm.xmmbmc,
				xmjd: this.searchForm.xmjd,
			}
			projectTemplatePage(data)
				.then((res) => {
					if (res.infoCode === 200) {
						this.tableData = res.data.list
						this.pageForm.total = res.data.total
						// 列表fbsj字段截取
						this.tableData.forEach((item, index) => {
							if (item.xmfbsj) {
								let dtime = item.xmfbsj.replace('+0800', '')
								item.xmfbsj = new Date(dtime).toISOString()
								item.xmfbsjFormat = dateTimeFormat(item.xmfbsj)
							}
						})
						console.log(
							'项目模板下载this.tableData:',
							this.tableData
						)
					} else {
						this.$message({
							type: 'error',
							message: res.msg,
						})
					}
				})
				.catch((err) => {
					console.log(err)
				})
		},
		// 重置
		reset() {
			this.searchForm = {}
			this.pageForm = {
				pageNum: 1,
				pageSize: 10,
				total: 1,
			}
			this.getList()
		},
		// 查看框弹出
		showDialog(row, type) {
			this.dialogVisible = true
			if (type == 'add' || type == 'edit') {
				this.editable = false
			}
			if (type == 'see') {
				this.editable = true
			}
			if (row != null) {
				let data = {
					xmmbId: row.xmmbId,
				}
				getProjectTemplate(data).then((res) => {
					console.log(
						'模板下载查看/修改data:',
						res.data.templateFileList
					)
					if (res.infoCode === 200 && res.data) {
						this.ruleForm = res.data
						this.templateFileList = res.data.templateFileList
						this.templateFileList.forEach((file) => {
							console.log('file,fi', file.fileName)
							if (file && file.fileName) {
								file.name = file.fileName
							}
						})
						let dtime = this.ruleForm.xmfbsj.replace('+0800', '')
						this.ruleForm.xmfbsj = new Date(dtime).toISOString()
						this.ruleForm.xmfbsjFormat = dateTimeFormat(
							this.ruleForm.xmfbsj
						)
					} else {
						this.$message({
							type: 'error',
							message: res.msg,
						})
					}
				})
			} else {
				this.ruleForm = {
					xmmbmc: '',
					xmjd: '',
					xmmbjj: '',
					templateFileList: [],
					xmfbr: this.orgName,
					xmfbsj: dateTimeFormat(new Date()),
					xmfbsjFormat: dateTimeFormat(new Date()),
				}
				this.templateFileList = []
			}
		},
		// 保存发布
		saveInfo(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.ruleForm.templateFileList = [
						...this.templateFileList,
						..._file,
					]
					if (this.ruleForm.xmmbId) {
						let data = this.ruleForm
						updateProjectTemplate(data).then((res) => {
							if (res.infoCode === 200) {
								this.$message({
									type: 'success',
									message: '更新成功!',
								})
							} else {
								this.$message({
									type: 'error',
									message: '更新失败!',
								})
							}
							this.handleClose()
						})
					} else {
						this.ruleForm.xmfbsj = new Date().toISOString()
						let data = this.ruleForm
						saveProjectTemplate(data).then((res) => {
							if (res.infoCode === 200 && res.data) {
								this.ruleForm = res.data
								this.$message.success('发布成功!')
							} else {
								this.$message({
									type: 'error',
									message: res.msg,
								})
							}
							this.handleClose()
						})
					}
				}
			})
		},
		// 删除列表
		async removeInfo(row) {
			let isOk = await this.$confirm(
				'此操作将删除当前信息,是否继续',
				'提示'
			)
			if (!isOk) return
			let data = {
				xmmbId: row.xmmbId,
			}
			removeProjectTemplate(data).then((res) => {
				if (res.infoCode === 200) {
					this.$message({
						type: 'success',
						message: '删除成功!',
					})
				} else {
					this.$message({
						type: 'error',
						message: '删除失败!',
					})
				}
				this.getList()
			})
		},
	},
	created() {
		this.getButtonList(
			sessionStorage.getItem('resourceCode'),
			sessionStorage.getItem('userCode')
		)
		this.getList('start')
		this.orgName = sessionStorage.getItem('orgName')
		this.nowTime =
			String(new Date().getFullYear()) +
			'-' +
			String(new Date().getMonth() + 1) +
			'-' +
			String(new Date().getDate())
	},
}
</script>

<style lang="scss" scoped>
// .content-main {
// 	margin: 10px 10px 0 10px;
// 	padding: 10px;
// 	// height: calc(100vh - 251px);
// 	border: 1px #f4f5f8 solid;
// 	background-color: #fff;
// }

.pagination-wrap {
	margin-top: 20px;
	text-align: right;
}

.solid {
	margin-top: 10px;
	margin-bottom: 10px;
	border-top: 1px #75b5fa dashed;
}

.search-content {
	padding: 10px 0;
	.el-form-item {
		margin-bottom: 0;
	}
}

.applyList-action {
	padding: 10px;
	text-align: left;
	background: #edf5fd;
	margin-top: 10px;
}

.fileList {
	position: relative;
	margin-top: 7px;
	height: 25px;
	line-height: 25px;
	&:hover .name {
		color: #409eff;
	}
	.name {
		cursor: pointer;
		color: #606266;
		transition: color 0.3s;
	}
	.close {
		position: absolute;
		top: 50%;
		right: 7px;
		margin-top: -7px;
		width: 14px;
		height: 14px;
		cursor: pointer;
		z-index: 1;
		&:after,
		&:before {
			position: absolute;
			top: 50%;
			left: 50%;
			margin-top: -5px;
			content: '';
			width: 1px;
			height: 10px;
			background-color: #606266;
		}
		&:after {
			transform: rotate(45deg);
		}
		&:before {
			transform: rotate(-45deg);
		}
	}
}
</style>
