<template>
  <div class="reminder-drag">
    <div ref="drapBox" class="reminder-box" :style="{width: width + 'px'}">
      <el-container class="actionPane">
        <el-header style="height: 50px;">
          <el-row class="actionList">
            <span class="titleStyle">{{ $t('scriptRecord.scriptRecordTitle') }}</span>
            <span class="titleStyle">( {{ $t('scriptRecord.language') }}: {{ $route.query.lang=="en"?$t('scriptRecord.english'):$t('scriptRecord.chinese') }} )</span>
          </el-row>
        </el-header>
        <el-main style="padding-top:10px;padding-bottom:10px;">
          <add-role ref="addRole" :group="group" @refresh="refresh" />
          <add-action ref="addAction" :group="group" :size="size" @create="create" @setDisabled="setDisabled" />
          <get-action ref="getAction" :group="group" :size="size" @setAction="setAction" />
        </el-main>
        <el-card class="scriptFooter">
          <el-button-group class="button-group">
            <el-button v-if="isPause" type="primary" :disabled="executeDisabled" @click="pauseScript">{{ $t('scriptRecord.drivingPause') }}</el-button>
            <el-button v-else type="primary" :disabled="executeDisabled" @click="executePlayScript">{{ $t('scriptRecord.recoverAndExecute') }}</el-button>
            <el-button type="danger" @click="dumpScenesData">{{ $t('scriptRecord.resetScript') }}</el-button>
            <el-button type="primary" :disabled="backDisabled" @click="saveScenesStage">{{ $t('scriptRecord.saveBackground') }}</el-button>
            <el-button type="success" :loading="isSavingScript" @click="saveScenesData">{{ $t('scriptRecord.saveData') }}</el-button>
          </el-button-group>
        </el-card>
      </el-container>
    </div>
  </div>
</template>
<script>
import Vue from 'vue';
import AddAction from '../scriptRecord/addAction';
import GetAction from '../scriptRecord/getAction';
import AddRole from '../scriptRecord/addRole';
import {getDraftScriptByGroupNew} from '@/api/script';
import {saveScriptScenes, saveScriptScenesNew, saveScriptData, saveScriptDataNew, dumpScriptData, dumpScriptDataNew, updateMapLocation, updateMapLocationNew, scriptPause, simulationPause, executeScript, executeScriptNew} from '@/api/simulation';

export default {
    name: 'TipScriptRecord',
    components: {
        GetAction,
        AddRole,
        AddAction
    },
    props: {
        group: {
            type: String,
            required: true
        },
        width: {
            type: Number || String,
            required: true
        }
    },
    data() {
        return {
            title: this.$t('scriptRecord.scriptRecordTitle'),
            isShrink: false,
            mapLocation: {},
            autoSaveScript: null,
            isSavingScript: false,
            isPause: true,
            executeDisabled: false,
            backDisabled: false,
            size: {
                width: 350,
                height: window.innerHeight - 342
            }
        };
    },
    computed:{
        drawWay() {
            const drawWay = this.$route.query.drawWay;
            return drawWay && JSON.parse(drawWay);
        }
    },
    watch: {
        '$store.state.scriptRecord.bgSet': function (val) {
            this.backDisabled = val;
        },
        '$store.state.app.windowSizeCount': function() {
            this.size = { width: 350, height: window.innerHeight - 342};
        },
        width: function(val) {
            this.size = { width: val / 2 - 20, height: window.innerHeight - 342};
        }
    },
    mounted() {
        // this.initAutoSaveScript();
        if (this.drawWay) {
            getDraftScriptByGroupNew(this.group).then(response=>{
                this.backDisabled = response.data.bgSet;
                this.$store.dispatch('scriptRecord/updateBgSet', response.data.bgSet);
            });
        } else {
            this.backDisabled = this.$store.state.scriptRecord.bgSet;
        }

    },
    beforeDestroy() {
        this.clearAutoSave();
        this.$store.dispatch('scriptRecord/updateBgSet', false);
    },
    methods: {
        setIsParse(isPause) {
            this.isPause = isPause;
        },
        setDisabled(data) {
            this.executeDisabled = !data;
        },
        initAutoSaveScript() {
            const timeout = 1000 * 20;
            this.clearAutoSave(this.autoSaveScript);
            this.autoSaveScript = setInterval(this.saveScenesData, timeout);
        },
        clearAutoSave() {
            if (this.autoSaveScript) {
                clearInterval(this.autoSaveScript);
                this.autoSaveScript = null;
            }
        },
        pauseScript() {
            if (this.drawWay) {
                simulationPause(this.group).then(resp => {
                    this.$store.dispatch('scriptRecord/updateSimulationPause', true);
                }).catch(() => {
                    this.$messageBox(this.$t('scriptRecord.pauseFail'));
                });
            } else {
                scriptPause(this.group).then(resp => {
                    this.$store.dispatch('scriptRecord/updateSimulationPause', true);
                }).catch(() => {
                    this.$messageBox(this.$t('scriptRecord.pauseFail'));
                });
            }

        },
        executePlayScript() {
            if (this.drawWay) {
                executeScriptNew(this.group).then(resp => {
                    this.$store.dispatch('scriptRecord/updateSimulationPause', false);
                }).catch(() => {
                    this.$messageBox(this.$t('scriptRecord.recoverFail'));
                });
            } else {
                executeScript(this.group).then(resp => {
                    this.$store.dispatch('scriptRecord/updateSimulationPause', false);
                }).catch(() => {
                    this.$messageBox(this.$t('scriptRecord.recoverFail'));
                });
            }

        },
        saveScenesStage() {
            const data = Vue.prototype.$jlmap.$options;
            const group = this.$route.query.group;
            const dataZoom = {scale: data.scaleRate, x: data.offsetX, y: data.offsetY};
            if (this.drawWay) {
                saveScriptScenesNew(this.group).then(resp => {
                    updateMapLocationNew(group, dataZoom).then(response=>{
                        this.$store.dispatch('scriptRecord/updateBgSet', true);
                        this.$message.success(this.$t('scriptRecord.saveBackgroundSuceess'));
                    }).catch(error => {
                        this.$messageBox(`${this.$t('scriptRecord.updateLocationFail')}: ${error.message}`);
                    });
                }).catch((error) => {
                    this.$messageBox(`${this.$t('scriptRecord.saveBackgroundFail')}: ${error.message}`);
                });
            } else {
                saveScriptScenes(this.group).then(resp => {
                    updateMapLocation(group, dataZoom).then(response=>{
                        this.$store.dispatch('scriptRecord/updateBgSet', true);
                        this.$message.success(this.$t('scriptRecord.saveBackgroundSuceess'));
                    }).catch(error => {
                        this.$messageBox(`${this.$t('scriptRecord.updateLocationFail')}: ${error.message}`);
                    });
                }).catch((error) => {
                    this.$messageBox(`${this.$t('scriptRecord.saveBackgroundFail')}: ${error.message}`);
                });
            }

        },
        saveScenesData() {
            this.isSavingScript = true;
            if (this.drawWay) {
                saveScriptDataNew(this.group).then(resp => {
                    this.$message.success(this.$t('scriptRecord.saveDataSucess'));
                    this.isSavingScript = false;
                    // this.initAutoSaveScript();
                }).catch(error => {
                    this.$messageBox(`${this.$t('scriptRecord.saveDataFail')}: ${error.message}`);
                    this.isSavingScript = false;
                    if (error.code === 40004 || error.code === 40005 || error.code === 40003) {
                        this.clearAutoSave();
                    } else {
                        // this.initAutoSaveScript();
                    }
                });
            } else {
                saveScriptData(this.group).then(resp => {
                    this.$message.success(this.$t('scriptRecord.saveDataSucess'));
                    this.isSavingScript = false;
                    // this.initAutoSaveScript();
                }).catch(error => {
                    this.$messageBox(`${this.$t('scriptRecord.saveDataFail')}: ${error.message}`);
                    this.isSavingScript = false;
                    if (error.code === 40004 || error.code === 40005 || error.code === 40003) {
                        this.clearAutoSave();
                    } else {
                        // this.initAutoSaveScript();
                    }
                });
            }
        },
        dumpScenesData() {
            this.clearAutoSave();
            const group = this.group;
            this.$confirm(this.$t('scriptRecord.clearDataTip'), this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                if (this.drawWay) {
                    dumpScriptDataNew(group).then(resp => {
                        this.$parent.$refs['display'].$refs['menuScript'].resetBeginTime();
                        this.$refs['getAction'].loadInitData();
                        this.$refs['addRole'].initData();
                        this.$refs['addAction'].initData();
                        this.$refs['addAction'].resetData();
                        // this.initAutoSaveScript();
                        this.$store.dispatch('scriptRecord/updateBgSet', false);
                        this.$message.success(this.$t('scriptRecord.resetDataSuccess'));
                    }).catch(() => {
                        this.$messageBox(this.$t('scriptRecord.resetDataFail'));
                    });
                } else {
                    dumpScriptData(group).then(resp => {
                        this.$parent.$refs['display'].$refs['menuScript'].resetBeginTime();
                        this.$refs['getAction'].loadInitData();
                        this.$refs['addRole'].initData();
                        this.$refs['addAction'].initData();
                        this.$refs['addAction'].resetData();
                        // this.initAutoSaveScript();
                        this.$store.dispatch('scriptRecord/updateBgSet', false);
                        this.$message.success(this.$t('scriptRecord.resetDataSuccess'));
                    }).catch(() => {
                        this.$messageBox(this.$t('scriptRecord.resetDataFail'));
                    });
                }

            }).catch(() => {
                // this.initAutoSaveScript();
            });
        },
        refresh() {
            this.$refs['addAction'].initData();
        },
        create() {
            this.$refs['getAction'].loadInitData();
        },
        setAction(row) {
            this.$refs['addAction'].doShow(row);
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";
	.reminder-drag{
		width: 100%;
		height: 100%;
	}

    .reminder-box {
        position: absolute;
        float: left;
        left: 0px;
        top:0px;
        height: 100%;
        background-color: #fff;
        overflow: hidden;
        z-index: 10;
        font-size: 18px;

        .actionPane{
            height: 100%;
        }

        .button-group{
            margin: 8px;
            float: right;
        }

        .actionList{
            margin-top: 10px;
            font-size: 15px;
            padding-top: 5px;
            border-bottom: 1px #ccc solid;
            height: 35px;
        }
        .titleStyle{
            margin-left:5px;
        }

        .icon {
            float: right;
            margin-right: 10px;
            cursor: pointer;
            background-color: #f3f3f3;
            border-radius: 50%;
        }

        /deep/ {
            .el-tree-node__content {
                margin-bottom: 4px;
            }

            .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
                background-color: #d6e5f7;
            }
        }
    }
</style>
