<template>
	<el-dialog :title="$t('Projectx skin editor')" width="70%" :visible.sync="visible"
	           :close-on-click-modal="false"
	           :append-to-body="true"
	           :show-close="false"
	           fullscreen
	           custom-class="flex-dialog px-skin-editor-dialog"
	>
		<div class="wrapper">
			<div class="header">
				<el-select class="env-select" size="mini" v-model="env" @change="changeEnv">
					<el-option v-for="(item, key) in pxEnvs" :key="key" :label="item" :value="key"></el-option>
				</el-select>
				<span class="px-project-name">{{ pxProjectName }}</span>
				<span v-if="env==='prod'&&isProd">
					<span style="padding-left:10px;">QA人员:</span>
					<el-select class="env-select" size="mini" v-model="qa" placeholder="请选择QA人员" @change="changeQA">
						<el-option v-for="item in QAList" :key="item.id" :label="item.name" :value="item.pid"></el-option>
					</el-select>
				</span>
			</div>
			<el-table class="mock-table" :data="skins" height="100%" stripe size="mini">
				<el-table-column
					prop="id"
					label="ID"
					width="100">
				</el-table-column>
				<el-table-column
					:label="$t('Type')"
					width="100">
					<template slot-scope="scope">
						<span>{{ tplTypes[scope.row.type - 1] }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="name"
					:label="$t('Name')">
				</el-table-column>
				<el-table-column width="240">
					<div class="operate-wrapper" slot-scope="scope">
						<el-button
							size="mini" plain
							type="primary"
							@click="editItem(scope.row)"
						>{{ $t('Edit') }}
						</el-button>
						<el-button
							size="mini" plain
							type="success"
							@click="copyUrl(scope.row)"
						>{{ $t('Copy url') }}
						</el-button>
						<el-popconfirm :title="$t('Are you sure to delete this item?')"
						               @onConfirm="deleteItem(scope.row)"
						               placement="top">
							<el-button
								slot="reference"
								size="mini" plain
								type="danger"
							>{{ $t('Delete') }}
							</el-button>
						</el-popconfirm>
					</div>
				</el-table-column>
			</el-table>
		</div>
		<div slot="footer" class="dialog-footer">
			<div>
				<el-dropdown trigger="click" @command="onAdd" placement="top" size="small">
					<el-button size="mini" icon="el-icon-plus" type="primary">{{ $t('Add') }}</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item v-for="(type, index) of tplTypes" :command="index" :key="index">{{ type }}
						</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>

				<px-config-popover @save="onSavePxConfig"/>
			</div>
			<div>
				<el-button size="mini" @click="onClose">{{ $t('Close') }}</el-button>
			</div>
		</div>
		<px-skin-editor ref="pxSkinEditor" @input="onSaveSkin"/>
	</el-dialog>
</template>

<script>
import {mapGetters, mapMutations, mapActions} from 'vuex'
import EnabledSetter from "../components/EnabledSetter";
import MonacoEditor from "vue-monaco";
import PxConfigPopover from "../components/PxConfigPopover";
import {getSkins, saveSkin,} from "../../../api/polaris";
import {playWaiting, pxHostMapping} from "../../../utils";
import copy from "copy-to-clipboard";
import PxSkinEditor from "./PxSkinEditor";
import {getDevPersons} from "../../../api/editor";

export default {
	name: "PxSkinEditorDialog",
	components: {PxSkinEditor, PxConfigPopover, MonacoEditor, EnabledSetter},
	data() {
		return {
			visible: false,
			pxEnvs: this.$t("pxEnvs"),
			tplTypes: this.$t("tplTypes"),
			pxProjectName: '',
			skins: [],
			env: 'dev',
			QAList: [],
			qa: null,
			isProd: null
		}
	},
	computed: {
		...mapGetters(["options", 'project'])
	},
	methods: {
		hasIndex() {
			return this.skins.find(v => v.type === "1");
		},
		show() {
			this.visible = true;
		},
		onClose() {
			this.visible = false;
		},
		onAdd(type) {
			if (type === 0 && this.hasIndex()) {
				this.$message({message: this.$t('Index page exists'), type: "warning"});
			} else {
				this.$refs.pxSkinEditor.edit(0, {type: (type + 1).toString()}, this.pxProjectName);
			}
		},
		editItem(skin) {
			this.$refs.pxSkinEditor.edit(1, skin, this.pxProjectName);
		},
		copyUrl(skin) {
			const {id, type} = skin;
			let pxPid = this.options.pxEnv[this.env];
			const url = `${pxHostMapping[this.env]}/projectx/${pxPid}/${
				type === "1" ? "index" : id
			}.html`;
			copy(url);
			this.$message({
				message: this.$t('Copy url success'),
				type: "success"
			});
		},
		changeQA(pid) {
			console.log(this.qa)
		},
		deleteItem(skin) {
			try {
				this.saveSkin(skin, 2);
			} catch (e) {
				throw new Error(e.message);
			}
		},
		async onSaveSkin(skin, operate) {
			try {
				await this.saveSkin(skin, operate);
				let oldSkin = this.skins.find(s => s.id === skin.id);
				oldSkin.name = skin.name;
				oldSkin.html = skin.html;
				this.$refs.pxSkinEditor.onSaveSuccess();
			} catch (e) {
				throw new Error(e.message);
			}
		},
		async changeEnv(e) {
			await this.getSkinsList();
		},
		onSavePxConfig() {
			this.getSkinsList();
		},
		async getSkinsList() {
			const {env} = this;

			const {pxEnv} = this.options;
			const pxPid = this.pxPid = pxEnv[env];

			this.QAList = await getDevPersons()
			this.QAList = this.QAList.filter((item) => {
				return item.level == 1
			})
			console.log(this.qa)
			this.qa = this.QAList[0].pid

			if (!pxPid) {
				this.$message({
					message: this.$t('Please config projectID', {env}),
					type: "error"
				});
				return;
			}
			try {
				const data = await getSkins(pxPid, env);
				this.isProd = data.isProd
				this.pxProjectName = data.name;
				this.skins = data.skins;
			} catch (e) {
				this.invalidTicketNotice();
			}
		},
		async invalidTicketNotice() {
			const {env} = this;
			this.pxProjectName = '';
			this.skins = [];
			await this.$confirm(this.$t('SSO is invalid'), this.$t('Alert'), {
				confirmButtonText: this.$t('To Verify'),
				cancelButtonText: this.$t('Close'),
			});
			window.open('/sso/login?env=' + env, '_blank');
		},
		async saveSkin(skin, operate) {
			const {
				env,
				pxPid,
			} = this;
			const {id, html, name, type} = skin;
			const params = {
				projectId: pxPid,
				operate: operate + 1,
				type,
				id,
				html,
				name,
				env,
				isProd: true,
				qas: [this.qa],
				publishType: 3,
				remarks: '项目迭代',
			};
			const {ret} = await playWaiting(saveSkin(params), this.$t('In processing'));
			if (ret.success !== false) {

				this.$message({
					message: this.$t('Operate success'),
					type: "success"
				});
			} else {
				this.$message({message: ret.message, type: "error"});
			}
			if (operate !== 1) {
				this.getSkinsList();
			}
		},
		...mapMutations([
			'modifyMocks',
		]),
		...mapActions([
			'setMockServeEnabled',
		]),
	}
}
</script>

<style scoped>

</style>