<template>
	<div class="home">
		<div class="editor-name" style="font-weight: bold">{{editor.name}}
			<span class="editor-version">{{editor.version}}</span>
		</div>
		<main>
			<div class="project-list">
				<el-form :inline="true" class="filter-bar" size="mini" @submit.native.prevent>
					<el-form-item>
						<el-input v-model="searchWord" :placeholder="$t('Search')" @change="search" @clear="search" clearable>
							<el-button slot="append" icon="el-icon-search"/>
						</el-input>
					</el-form-item>
					<el-form-item>
						<el-checkbox
							v-model="onlyMine"
							size="mini">{{$t('Only mine')}}
						</el-checkbox>
					</el-form-item>
				</el-form>
				<div class="table">
					<el-table
						:data="projects.projects"
						:empty-text="$t('No projects')"
						height="100%"
						stripe
					>
						<el-table-column label="ID" prop="id" width="140px"></el-table-column>
						<el-table-column
							:label="$t('Projects')">
							<template slot-scope="scope">
								<div class="project-info">
									<span class="project-name">{{scope.row.name}}</span>
									<el-tag size="mini" :type="editor.operator === scope.row.operator ? 'success' : 'info'">{{scope.row.operator}}</el-tag>
									<el-tag size="mini" type="warning">{{$timeFormat(scope.row.update_time)}}</el-tag>
								</div>
							</template>
						</el-table-column>
						<el-table-column
							fixed="right"
							width="100">
							<template slot-scope="scope">
								<el-dropdown size="small" trigger="click" split-button @click="selectProject(scope.row)"
								             @command="(command)=>{onMoreMenu(command, scope.row)}">
									<i class="el-icon-edit"></i>{{$t('Edit')}}
									<el-dropdown-menu slot="dropdown">
										<el-dropdown-item command="edit" icon="el-icon-edit">{{$t('Edit')}}</el-dropdown-item>
										<el-dropdown-item command="history" icon="el-icon-coin">{{$t('History')}}</el-dropdown-item>
										<el-dropdown-item command="duplicate" icon="el-icon-document-copy">{{$t('Duplicate')}}
										</el-dropdown-item>
										<el-dropdown-item command="export" icon="icon-download">{{$t('Export')}}</el-dropdown-item>
										<el-dropdown-item command="delete" icon="el-icon-delete" v-if="showDeleteButton">{{$t('Delete')}}
										</el-dropdown-item>
									</el-dropdown-menu>
								</el-dropdown>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
			<div class="bottom-bar">
				<div>
					<el-button size="small" type="primary" @click="showCreateProjectDialog()">{{$t('Create')}}</el-button>
					<el-button size="small" @click="importProject()">{{$t('Import')}}</el-button>
				</div>
				<el-pagination
					@current-change="handleCurrentChange"
					:current-page.sync="currentPage"
					:page-size="pageSize"
					layout="prev, pager, next, jumper"
					:total="projects.projectCount">
				</el-pagination>
			</div>
			<create-project-dialog ref="createProjectDialog" @success="onCreateProject"/>
			<duplicate-project-dialog ref="duplicateProjectDialog" @success="onDuplicateProject"/>
			<project-history-dialog ref="projectHistoryDialog" @select-history-project="onSelectProject"/>
		</main>
	</div>
</template>

<script>
	import {mapState, mapActions} from 'vuex'
	import CreateProjectDialog from "./Home/CreateProjectDialog";
	import {playWaiting, readTextFile, saveAs, selectFile} from "../utils";
	import DuplicateProjectDialog from "./Home/DuplicateProjectDialog";
	import {PROJECT_PAGE_SIZE} from "../config";
	import ProjectHistoryDialog from "./Home/ProjectHistoryDialog";
	import ElFormItem from "../components/inputs/form-item";
	import db from "../utils/db-storage";

	export default {
		name: "Home",
		components: {ElFormItem, ProjectHistoryDialog, DuplicateProjectDialog, CreateProjectDialog},
		data() {
			return {
				currentPage: 1,
				pageSize: PROJECT_PAGE_SIZE,
				searchWord: '',
				onlyMine: true,
			}
		},
		mounted() {
			playWaiting(this.prepare(), this.$t('Preparing')).catch(e => {});
		},
		computed: {
			showDeleteButton() {
				return localStorage.getItem('---zeroing-editor-delete-button');
			},
			...mapState([
				'projects',
				'editor',
			]),
		},
		watch: {
			onlyMine() {
				this.handleCurrentChange(1);
			}
		},
		methods: {
			prepare() {
				return Promise.all([
					db.open('store'),
					this.updateEnv(),
					this.handleCurrentChange(1),
				])
			},
			showCreateProjectDialog() {
				this.$refs.createProjectDialog.show();
			},
			importProject() {
				selectFile((files) => {
					readTextFile(files[0])
						.then(
							txt => {
								let data = JSON.parse(txt);
								return playWaiting(this.createProject(data), this.$t('Importing project'));
							}
						)
				});
			},
			async onMoreMenu(command, project) {
				switch (command) {
					case 'edit':
						this.selectProject(project);
						break;
					case 'history':
						this.selectFromHistory(project);
						break;
					case 'duplicate':
						this.showDuplicateProjectDialog(project);
						break;
					case 'export':
						this.exportProject(project);
						break;
					case 'delete':
						this.onDeleteProject(project);
						break;
				}
			},
			async exportProject({id}) {
				const project = await playWaiting(this.fetchProject(id), this.$t('Exporting project'));
				saveAs(new Blob([JSON.stringify(project)]), project.name + '.json');
			},
			showDuplicateProjectDialog(project) {
				this.$refs.duplicateProjectDialog.show(project);
			},
			selectProject(row, event) {
				this.editProject(row.id);
			},
			selectFromHistory(row, event) {
				this.$refs.projectHistoryDialog.show(row)
			},
			async onDeleteProject(project, event) {
				this.$confirm(this.$t('This action will permanently delete project', {projectName: project.name}), this.$t('Alert'), {
					confirmButtonText: this.$t('Confirm'),
					cancelButtonText: this.$t('Cancel'),
					type: 'warning'
				}).then(
					() => {
						playWaiting(this.deleteProject(project.id), this.$t('Deleting')).catch(e => {
						});
					},
					() => {
					}
				)
			},
			onCreateProject(projectID) {
				this.editProject(projectID);
			},
			onDuplicateProject(projectID) {
				this.editProject(projectID);
			},
			async onSelectProject(project, dataUrl) {
				if(await this.localVersionExist(project.id)){
					this.$message({
						message: this.$t('Unsaved version found locally, can not open from history'),
						type: 'warning'
					});
				}else{
					this.$router.push({name: 'editor', params: {projectID: project.id, project, dataUrl}});
				}
			},
			editProject(projectID) {
				this.$router.push({name: 'editor', params: {projectID}});
			},
			async search() {
				this.handleCurrentChange(1);
			},
			async handleCurrentChange(page) {
				const loading = this.$loading({
					lock: true,
					text: this.$t('In processing'),
				});
				this.currentPage = page;
				let keyword = this.searchWord;
				await this.fetchProjects({keyword, currentPage: page, pageSize: this.pageSize, onlyMine: this.onlyMine});
				loading.close();
			},
			...mapActions([
				'fetchProjects',
				'fetchProject',
				'fetchHistory',
				'createProject',
				'deleteProject',
				'updateEnv',
				'localVersionExist',
			]),
		},
	}
</script>

<style>

</style>
