<template>
  <div v-show="dialogVisible">
    <el-dialog v-dialogDrag title="请确认联锁配置项" :visible.sync="dialogVisible" fullscreen :before-close="handleClose" center :close-on-click-modal="false" :z-index="2000" append-to-body>
      <div style="overflow-y: scroll;" :style="{height: height+ 'px'}">
        <el-card style="margin-top: 10px">
          <div slot="header" style="font-weight: bold;text-align: center;">
            <span>联锁配置项</span>
          </div>
          <el-table :data="roadData" style="width: 100%;">
            <el-table-column prop="configKey" label="key" />
            <el-table-column prop="configValue" label="value">
              <template slot-scope="scope">
                <div v-if="scope.row.type === 'input'">
                  <div v-if="!scope.row.focus" style="width: 100%;cursor: pointer;" @click="changeFocus(scope.row, '1')">{{ scope.row.configValue }}</div>
                  <el-input v-if="scope.row.focus" v-model="scope.row.configValue" size="mini" style="width: 100%" @blur="changeFocus(scope.row, '0')" />
                </div>
                <div v-else-if="scope.row.type === 'number'">
                  <div v-if="!scope.row.focus" style="width: 100%;cursor: pointer" @click="changeFocus(scope.row, '1')">{{ scope.row.configValue }}</div>
                  <el-input-number v-if="scope.row.focus" v-model="scope.row.configValue" size="mini" style="width: 100px;" :min="0" controls-position="right" @blur="changeFocus(scope.row, '0')" />
                </div>
                <div v-else-if="scope.row.type === 'boolean'">
                  <el-radio v-model="scope.row.configValue" :label="trueValue">是</el-radio>
                  <el-radio v-model="scope.row.configValue" :label="falseValue">否</el-radio>
                </div>
                <div v-else-if="scope.row.type === 'select'">
                  <el-select v-model="scope.row.configValue" size="mini" style="width: 80px;">
                    <el-option
                      v-for="item in scope.row.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
                <div v-else-if="scope.row.type === 'multiple'">
                  <div v-if="!scope.row.focus" style="width: 100%;cursor: pointer;height: 20px;" @click="changeFocus(scope.row, '1')">
                    <template v-for="(item, i) in scope.row.configValue">
                      <el-tag :key="i" size="mini">{{ getMultipleName(item, scope.row.options) }}</el-tag>
                    </template>
                  </div>
                  <el-select v-if="scope.row.focus" v-model="scope.row.configValue" size="mini" multiple placeholder="请选择">
                    <el-option
                      v-for="item in scope.row.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="描述" />
          </el-table>
        </el-card>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="save">{{ $t('global.confirm') }}</el-button>
        <el-button :loading="loading" @click="dialogVisible = false">{{ $t('global.cancel') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { saveMap, generateCI } from '@/api/jmap/mapdraft';
import { mapGetters } from 'vuex';
import { EventBus } from '@/scripts/event-bus';
export default {
    name: 'Config',
    components: {
        // EditConfig
    },
    props: {
        type: {
            type: String,
            default() {
                return '';
            }
        }
    },
    data() {
        return {
            loading: false,
            dialogVisible: false,
            index: 0,
            trueValue: true,
            falseValue: false,
            id: '',
            height: 800,
            roadData: [],
            focus: false,
            booleanList: ['upRight', 'lockFirst', 'switchSingleHandle', 'signalApproachOnlyOne', 'signalApproachOnlyNpSwitch',
                'routeNameUseEndOppositeSignalName', 'generateTbRoute', 'tbRouteNameUseEndOppositeSignalName', 'routeSignalAlwaysGreen',
                'routeApartByOverlap', 'overlapOnlySwitch', 'overlapSwitchNpOnly', 'overlapSignalOppositeSwitchNpOnly',
                'generateCycle', 'routeButton', 'likeHa1', 'getNearlySignal', 'overlapSettingByTrigger', 'generateFls', 'signalApproachNotPassPreSignal',
                'generateDestination', 'ctcOverlapOnlyTurnBackStationLock'
            ],
            multipleList: ['sharingECStations'],
            selectList: [],
            numberList: ['overlapReleaseTime', 'routeReleaseTime', 'overlapMinLen'],
            optionsMap: {
                // upRight: [{label: 'right', value: 'right'}, {label: 'left', value: 'left'}]
            },
            remarkMap: {
                lockFirst: '是否先锁闭——办理过程直接先锁闭区段',
                upRight: '上行是否向右',
                switchSingleHandle: '道岔区段状态改变按单个道岔处理',
                signalApproachOnlyOne: '信号机接近区段是否只取最近的一个',
                signalApproachOnlyNpSwitch: ' 信号机接近区段是否仅考虑定位道岔',
                routeNameUseEndOppositeSignalName: '进路名称是否使用终端信号机同区段反向信号机名称命名，否则使用终端信号机命名',
                generateTbRoute: '是否生成折返进路',
                tbRouteNameUseEndOppositeSignalName: '折返进路名称是否使用终端信号机反向信号机名称',
                routeSignalAlwaysGreen: '进路始端防护信号机是否总是绿灯,否则根据进路中有无反位道岔生成绿灯或黄灯',
                routeApartByOverlap: '多个延续保护路径生成多条进路,否则生成一条进路',
                overlapOnlySwitch:'延续保护是否只构建道岔',
                overlapMinLen:'延续保护最小长度',
                overlapSwitchNpOnly: '延续保护道岔是否只构建定位道岔',
                overlapSignalOppositeSwitchNpOnly: '延续保护道岔在防护信号机与所属区段方向相反时，是否只构建定位道岔',
                overlapReleaseTime: '默认延续保护解锁时间',
                routeReleaseTime: '默认进路解锁时间',
                generateCycle: '是否生成自动折返',
                routeButton: '是否生成进路结束按钮',
                likeHa1: '是否类似哈尔滨一号线，联锁分为ATP信号、地面信号、引导信号',
                getNearlySignal: '生成进路信号按钮，进路信号按钮是否取最近的一个信号机',
                overlapSettingByTrigger: '延续保护的建立方式：是-通过触发建立，否-随进路建立',
                generateFls: '是否生成侧防：是-生成侧防，不要联动道岔，否-不生成侧防，用联动道岔',
                signalApproachNotPassPreSignal:'信号机接近区段不跨过前方同向信号机',
                generateDestination: '是否生成目的地码定义（泰雷兹）',
                sharingECStations: '共享紧急关闭效果的车站',
                ctcOverlapOnlyTurnBackStationLock: 'CTC列车进路延续保护仅折返站处锁闭'
            }
        };
    },
    computed: {
        ...mapGetters('map', [
            'stationList'
        ])
    },
    mounted() {
    },
    methods: {
        async show() {
            this.optionsMap.sharingECStations = [];
            this.stationList.forEach(item => {
                this.optionsMap.sharingECStations.push({ value: item.code, label: item.name });
            });
            this.dialogVisible = true;
            this.height = document.documentElement.clientHeight - 180;
            const map = this.$store.state.map.map;
            this.getList(map.generateConfig);
        },
        changeFocus(row, flag) {
            if (flag === '0') {
                this.$set(row, 'focus', false);
            } else {
                this.$set(row, 'focus', true);
            }
        },
        getMultipleName(value, options) {
            const obj = options.find(item => {
                return item.value === value;
            });
            return (obj || {}).label;
        },
        async getList(data) {
            try {
                if (data) {
                    const keys = Object.keys(data);
                    this.roadData = [];
                    keys.forEach(key => {
                        let type = 'input';
                        let options = [];
                        if (this.booleanList.indexOf(key) >= 0) {
                            type = 'boolean';
                        } else if (this.selectList.indexOf(key) >= 0) {
                            type = 'select';
                            options = this.optionsMap[key];
                        } else if (this.numberList.indexOf(key) >= 0) {
                            type = 'number';
                        } else if (this.multipleList.indexOf(key) >= 0) {
                            type = 'multiple';
                            options = this.optionsMap[key];
                        } else {
                            type = 'input';
                        }
                        const param = {
                            configKey: key,
                            configValue: data[key],
                            type: type,
                            options: options,
                            remark: this.remarkMap[key]
                        };
                        this.roadData.push(param);
                    });
                } else {
                    this.roadData = [];
                }
            } catch (error) {
                console.log(error);
            }
        },
        handleClose(done) {
            if (done) {
                done();
            } else {
                this.dialogVisible = false;
            }
        },
        addModel() {
            this.$refs.addConfig.show();
        },
        editModel(item, index) {
            this.$refs.editConfig.show(item);
            this.index = index;
        },
        save() {
            this.loading = true;
            const map = this.$store.state.map.map;
            this.$store.dispatch('map/saveMapDeviceDefaultRelations').then(() => {
                const param = {};
                this.roadData.forEach(item => {
                    param[item.configKey] = item.configValue;
                });
                saveMap(Object.assign(map, {generateConfig: param, mapId: this.$route.params.mapId})).then(response => {
                    this.dialogVisible = false;
                    this.loading = false;
                    this.$confirm('生成联锁关系会删除旧的联锁关系，是否继续生成', {
                        confirmButtonText: '继续',
                        cancelButtonText: this.$t('tip.cancel'),
                        type: 'warning',
                        beforeClose: (action, instance, done) => {
                            if (action === 'confirm' && instance.confirmButtonText === '继续') {
                                instance.confirmButtonLoading = true;
                                instance.confirmButtonText = '生成中...';
                                generateCI(this.$route.params.mapId).then(resp => {
                                    instance.confirmButtonLoading = false;
                                    instance.confirmButtonText = '确定';
                                    instance.dangerouslyUseHTMLString = true;
                                    instance.message = `
										<strong>生成并保存联锁关系成功！</strong><br/>
										<span>生成自动信号数据${resp.data.autoSignalCount}条；</span><br/>
										<span>生成进路数据${resp.data.routeCount}条；</span><br/>
										<span>生成延续保护数据${resp.data.overlapCount}条；</span><br/>
										<span>生成自动折返数据${resp.data.cycleCount}条；</span><br/>
										<span>生成交路数据${resp.data.routingCount}条；</span><br/>
										<span>生成站间运行等级数据${resp.data.stationRunlevelCount}条；</span>`;
                                    instance.type = 'success';
                                    instance.showCancelButton = false;
                                    EventBus.$emit('successCI');
                                }).catch((error)=> {
                                    if (error.code === 500045) {
                                        this.$message.error('生成并保存联锁关系失败:地图基础信息有误');
                                    } else {
                                        this.$message.error('生成并保存联锁关系失败！');
                                    }
                                    instance.confirmButtonLoading = false;
                                    done();
                                });
                            } else {
                                done();
                                instance.dangerouslyUseHTMLString = false;
                                instance.showCancelButton = true;
                            }
                        }
                    }).then(() => {});
                }).catch(() => {
                    this.loading = false;
                    this.$messageBox(this.$t('map.updateFailed'));
                });
            });
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .icon_font{
        font-size: 18px;
        margin-left: 15px;
        cursor: pointer;
    }
    .flex_box{
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

</style>

