<template>
  <el-tabs v-model="activeName" class="card" @tab-click="handleClick">
    <el-tab-pane class="view-control" :label="$t('map.property')" name="first" :lazy="lazy">
      <div class="view-control-content">
        <config-list ref="dataform" :form="form" :form-model="editModel" :rules="rules">
          <div v-if="editModel.type == 'StationTurnBack'" class="card-box">
            <div class="card_title">站后折返数据</div>
            <div>
              <el-table :data="editModel.optionList" border style="width: 100%">
                <el-table-column prop="id" label="编号" width="100px" />
                <el-table-column prop="label" label="描述" width="250px" />
                <el-table-column fixed="right" label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" @click.native.prevent="deleteOverlab(editModel.optionList, scope.$index)">移出</el-button>
                    <el-button type="text" size="small" @click.native.prevent="editOverlab(editModel.optionList, scope.$index)">编辑</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-card class="box-card" shadow="never">
                <div slot="header" class="clearfix">
                  <span style="font-size: 12px;">{{ cardTitle }}</span>
                  <el-button v-if="cardMode === 'generate'" style="float: right; padding: 3px 0" type="text" @click="generateOverlab">生成</el-button>
                  <el-button-group v-else-if=" cardMode === 'edit'" style="float: right;">
                    <el-button type="text" style="padding:3px 3px" @click="updateOverlab">修改</el-button>
                    <el-button type="text" style="padding:3px 0" @click="cancelOverlab">取消</el-button>
                  </el-button-group>
                </div>
                <div>
                  <el-form ref="hostileForm" :model="addBackModel" :rules="addBackRules" label-width="135px" size="mini" style="margin-top: 15px;padding-right: 10px;">
                    <el-form-item label="类型:" prop="type">
                      <el-select v-model="addBackModel.type" clearable :filterable="true">
                        <el-option v-for="item in turnBackList" :key="item.value" :label="item.name" :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="描述:" prop="label">
                      <el-input v-model="addBackModel.label" type="text" maxlength="30" :show-word-limit="true" />
                    </el-form-item>
                    <el-form-item v-if="addBackModel.type != 'NONE'" label="折返轨:" prop="sectionList">
                      <el-select v-model="addBackModel.sectionList" clearable multiple filterable>
                        <el-option v-for="item in sectionList" :key="item.code" :label="`${item.name}(${item.code})`" :value="item.code" />
                      </el-select>
                      <el-button :type="field === 'sectionCode1' ? 'danger' : 'primary'" @click="hover('sectionCode1')">激活</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-card>
            </div>
          </div>
        </config-list>
      </div>
      <div class="button_box">
        <el-button-group class="map-draft-group">
          <el-button type="primary" size="small" @click="edit">{{ $t('map.updateObj') }}</el-button>
          <el-button type="danger" size="small" @click="deleteObj">{{ $t('map.deleteObj') }}</el-button>
        </el-button-group>
      </div>
    </el-tab-pane>
    <el-tab-pane class="view-control" :label="$t('map.newConstruction')" name="second" :lazy="lazy">
      <div class="view-control-content">
        <config-data ref="make" :form="formMake" :form-model="addModel" :rules="createRules" />
      </div>
      <div class="button_box">
        <el-button-group class="map-draft-group">
          <el-button type="primary" size="small" @click="create">{{ $t('map.create') }}</el-button>
        </el-button-group>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { mapGetters } from 'vuex';
import { getUID } from '@/jmapNew/utils/Uid';
import ConfigList from './config/list';
import ConfigData from './config/data';
import { deepAssign } from '@/utils/index';
import { getRouteNewList, getAutoReentryList } from '@/api/jmap/mapdraft';

export default {
    name: 'AutoMaticRoute',
    components: {
        ConfigList,
        ConfigData
    },
    props: {
        selected: {
            type: Object,
            default: function () {
                return null;
            }
        }
    },
    data() {
        return {
            activeName: 'first',
            lazy: true,
            autoList: [],
            field: '',
            turnBackList: [
                { name: '按计划执行', value: 'NONE' },
                { name: '仅某个折返轨', value: 'ONLY' },
                { name: '等价折返', value: 'EQUAL' },
                { name: '优先/次之', value: 'FIRST' }
            ],
            typeList: [
                { name: '自动折返', value: 'AutoTurnBack' },
                { name: '计轴复位', value: 'AxleReset' },
                { name: '自动进路', value: 'AutomaticRoute' },
                { name: '引导总锁', value: 'GuideLock' },
                { name: '全线临时限速', value: 'LimitControl' },
                { name: '站后折返', value: 'StationTurnBack' }
            ],
            cardMode: 'generate',
            addBackModel: {
                id: '',
                type: '',
                label: '',
                sectionList: [],
                parentIndex: 0
            },
            editModel: {
                code: '',
                type: '',
                name: '',
                show: true, // 站后折返显示
                subtitleName: '',
                optionList: [], // 战后折返列表
                automaticRouteCode: '', // 关联自动进路code
                cycleCode: '', // 自动折返关联code
                stationCode: '', // 所属设备集中站
                position: {
                    x: 0,
                    y: 0
                }
            },
            addModel: {
                code: '',
                type: '',
                name: '',
                subtitleName: '',
                automaticRouteCode: '', // 关联自动进路code
                cycleCode: '', // 自动折返关联code
                stationCode: '', // 所属设备集中站
                position: {
                    x: 0,
                    y: 0
                }
            },
            rules: {
                code: [
                    { required: true, message: this.$t('rules.pleaseSelectEncoding'), trigger: 'change' }
                ],
                name: [
                    { required: true, message: this.$t('rules.pleaseEnterStatusSignal'), trigger: 'blur' }
                ],
                'position.x': [
                    { required: true, message: this.$t('rules.trainPositionX'), trigger: 'blur' }
                ],
                'position.y': [
                    { required: true, message: this.$t('rules.trainPositionY'), trigger: 'blur' }
                ]
            },
            addBackRules: {
                type: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ],
                label: [
                    { required: true, message: '请填写描述', trigger: 'blur' }
                ],
                sectionList: [
                    { required: true, message: '请选择站台轨', trigger: 'change' }
                ]
            }
        };
    },
    computed: {
        ...mapGetters('map', [
            'automaticRouteButtonList',
            'cycleButtonList',
            'tempSpeedLimitList',
            'axleCounterResetButtonList',
            'totalGuideLockButtonVOList',
            'stationList',
            'sectionList',
            'tbStrategyList'
        ]),
        cardTitle() {
            if (this.cardMode === 'generate') {
                return '生成数据';
            } else if (this.cardMode === 'edit') {
                return '编辑数据';
            } else {
                return '';
            }
        },
        form() {
            const form = {
                labelWidth: '150px',
                items: {
                    code: {
                        name: '',
                        item: []
                    },
                    draw: {
                        name: this.$t('map.drawData'),
                        item: [
                            { prop:'type', label: this.$t('map.functionButtonType'), type: 'select', optionLabel: 'name', optionValue: 'value', options: this.typeList, change: true, deviceChange: this.typeChange },
                            { prop: 'code', label: `${this.$t('map.code')}`, type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.selectLists, change: true, deviceChange: this.deviceChange },
                            { prop: 'name', label: this.$t('map.buttonMainName'), type: 'input' },
                            { prop: 'show', label: '是否显示:', type: 'checkbox', isHidden: !this.isTurnBackShow },
                            { prop: 'subtitleName', label: this.$t('map.buttonViceName'), type: 'input', isHidden: !this.isHiddensubtitleNameVO },
                            { prop: 'position', label: this.$t('map.textPoints'), type: 'coordinate', width: '140px', children: [
                                { prop: 'position.x', firstLevel: 'position', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '20px' },
                                { prop: 'position.y', firstLevel: 'position', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '20px' }
                            ] },
                            { prop:'automaticRouteCode', label: this.$t('map.automaticRouteCode'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.autoList, isHidden: !this.isHiddenAutomaticRoute, change: true, deviceChange: this.changeEditStation },
                            { prop:'cycleCode', label: this.$t('map.cycleCode'), type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.autoList, isHidden: !this.isHiddenMapCycleButtonVO, change: true, deviceChange: this.changeEditStation },
                            { prop:'stationCode', label: '所属车站', type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.stationList, disabled: this.isDisabledStation, isHidden: !this.isHiddenStation }
                        ]
                    }
                }
            };
            return form;
        },
        formMake() {
            const form = {
                labelWidth: '150px',
                items: [
                    { prop:'type', label: this.$t('map.functionButtonType'), type: 'select', optionLabel: 'name', optionValue: 'value', options: this.typeList, change: true, deviceChange: this.typeChange },
                    { prop: 'name', label: this.$t('map.buttonMainName'), type: 'input' },
                    { prop: 'position', label: this.$t('map.textPoints'), type: 'coordinate', width: '140px', children: [
                        { prop: 'position.x', firstLevel: 'position', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px' },
                        { prop: 'position.y', firstLevel: 'position', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '25px' }
                    ] },
                    { prop:'automaticRouteCode', label: this.$t('map.automaticRouteCode'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.autoList, isHidden: !this.isHiddenCreateAutomaticRoute, change: true, deviceChange: this.changeStation },
                    { prop:'cycleCode', label: this.$t('map.cycleCode'), type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.autoList, isHidden: !this.isHiddenCreateMapCycleButtonVO, change: true, deviceChange: this.changeStation },
                    { prop:'stationCode', label: '所属车站', type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.stationList, disabled: this.isDisabledCreateStation, isHidden: !this.isHiddenCreateStation }
                ]
            };
            return form;
        },
        createRules: function () {
            return {
                type: [
                    { required: true, message: this.$t('rules.selectFunctionType'), trigger: 'change' }
                ],
                name: [
                    { required: true, message: this.$t('rules.pleaseInputName'), trigger: 'blur' }
                ],
                'position.x': [
                    { required: true, message: this.$t('rules.trainPositionX'), trigger: 'blur' }
                ],
                'position.y': [
                    { required: true, message: this.$t('rules.trainPositionY'), trigger: 'blur' }
                ]
            };
        },
        isHiddenAutomaticRoute() {
            return this.editModel.type === 'AutomaticRoute';
        },
        isHiddenMapCycleButtonVO() {
            return this.editModel.type == 'AutoTurnBack';
        },
        isTurnBackShow() {
            return this.editModel.type == 'StationTurnBack';
        },
        isHiddensubtitleNameVO() {
            return this.editModel.type != 'StationTurnBack';
        },
        isDisabledStation() {
            return this.editModel.type == 'AutoTurnBack' || this.editModel.type == 'AutomaticRoute';
        },
        isHiddenStation() {
            return this.editModel.type == 'AutoTurnBack' || this.editModel.type == 'GuideLock' || this.editModel.type == 'AxleReset' || this.editModel.type == 'StationTurnBack';
        },

        isHiddenCreateAutomaticRoute() {
            return this.addModel.type == 'AutomaticRoute';
        },
        isHiddenCreateMapCycleButtonVO() {
            return this.addModel.type == 'AutoTurnBack';
        },
        isDisabledCreateStation() {
            return this.addModel.type == 'AutoTurnBack' || this.addModel.type == 'AutomaticRoute';
        },
        isHiddenCreateStation() {
            return this.addModel.type == 'AutoTurnBack' || this.addModel.type == 'GuideLock' || this.addModel.type == 'AxleReset' || this.addModel.type == 'StationTurnBack';
        }
    },
    mounted() {
    },
    methods: {
        setStation(data) {
            if (data.automaticRouteCode) {
                this.changeEditStation(data.automaticRouteCode);
            }
            if (data.cycleCode) {
                this.changeEditStation(data.cycleCode);
            }
        },
        clearInfo() {
            this.addModel.automaticRouteCode = '';
            this.addModel.cycleCode = '';
            this.addModel.concentrateStationList = '';
            this.editModel = {
                code: '',
                type: '',
                name: '',
                show: true, // 站后折返显示
                subtitleName: '',
                optionList: [], // 战后折返列表
                automaticRouteCode: '', // 关联自动进路code
                cycleCode: '', // 自动折返关联code
                stationCode: '', // 所属设备集中站
                position: {
                    x: 0,
                    y: 0
                }
            };
        },
        typeChange(type) { // 根据类型来选择功能按钮列表
            this.$refs.dataform && this.$refs.dataform.resetFields();
            this.$refs.make && this.$refs.make.resetFields();

            this.clearInfo();
            this.addModel.type = type;
            this.editModel.type = type;
            this.handleTypes(type);
        },
        handleTypes(type) {
            switch (type) {
            case 'AutoTurnBack':
                this.selectLists = this.cycleButtonList;
                this.getAutoTurnBackList();
                break;
            case 'AxleReset':
                this.selectLists = this.axleCounterResetButtonList;
                break;
            case 'AutomaticRoute':
                this.selectLists = this.automaticRouteButtonList;
                this.getAutoMaticList();
                break;
            case 'LimitControl':
                this.selectLists = this.tempSpeedLimitList;
                break;
            case 'GuideLock':
                this.selectLists = this.totalGuideLockButtonVOList;
                break;
            case 'StationTurnBack':
                this.selectLists = this.tbStrategyList;
                break;
            }
        },
        changeStation(code) { // 选择对应的所属设备集中站
            this.autoList.forEach(elem => {
                if (elem.code == code) {
                    this.addModel.stationCode = elem.stationCode;
                }
            });
        },
        changeEditStation(code) { // 选择对应的所属设备集中站
            this.autoList.forEach(elem => {
                if (elem.code == code) {
                    this.editModel.stationCode = elem.stationCode;
                }
            });
        },
        deviceChange(code) {
            this.$emit('setCenter', code);
            this.deviceSelect(this.$store.getters['map/getDeviceByCode'](code));
        },
        handleClick() {
            this.getAutoMaticList();
        },
        deviceSelect(selected) {
            if (selected && selected._type.toUpperCase() == 'AutomaticRoute'.toUpperCase() || selected._type.toUpperCase() == 'AutoTurnBack'.toUpperCase() || selected._type.toUpperCase() == 'AxleReset'.toUpperCase() || selected._type.toUpperCase() == 'LimitControl'.toUpperCase() || selected._type.toUpperCase() == 'GuideLock'.toUpperCase() || selected._type.toUpperCase() == 'StationTurnBack'.toUpperCase()) {
                this.handleTypes(selected._type);
                this.$refs.dataform && this.$refs.dataform.resetFields();
                this.$refs.make && this.$refs.make.resetFields();
                this.activeName = 'first';
                this.editModel = deepAssign(this.editModel, selected);
                this.editModel.type = selected._type;
                this.$nextTick(() => {
                    this.setStation(selected);
                });
            } else if (selected._type.toUpperCase() === 'Section'.toUpperCase() && this.field.toUpperCase() === 'sectionCode1'.toUpperCase()) {
                if (!this.addBackModel.sectionList.includes(selected.code)) {
                    this.addBackModel.sectionList.push(selected.code);
                }
            }
        },
        async getAutoMaticList() { // 获取自动信号列表
            const params = {
                pageSize: 9999,
                pageNum: 1
            };
            const resp = await getRouteNewList(this.$route.params.mapId, params);
            this.autoList = [];
            resp.data && resp.data.list && resp.data.list.forEach(elem => {
                if (elem.flt) {
                    this.autoList.push(elem);
                }
            });
        },
        async getAutoTurnBackList() { // 获取自动折返列表
            const params = {
                pageSize: 9999,
                pageNum: 1
            };
            const resp = await getAutoReentryList(this.$route.params.mapId, params);
            this.autoList = [];
            resp.data && resp.data.list && resp.data.list.forEach(elem => {
                this.autoList.push(elem);
            });
        },
        // 创建对象
        create() {
            this.$refs.make.validate((valid) => {
                if (valid) {
                    const uid = getUID(this.addModel.type, this.selectLists); // 根据类型写 uid 前缀命名
                    const model = {
                        _type: this.addModel.type,
                        code: uid,
                        name: this.addModel.name,
                        subtitleName: this.addModel.subtitleName,
                        show: true,
                        position: {
                            x: this.addModel.position.x,
                            y: this.addModel.position.y
                        },
                        optionList: [],
                        automaticRouteCode: this.addModel.automaticRouteCode, // 关联自动进路code
                        cycleCode: this.addModel.cycleCode, // 自动折返关联code
                        stationCode: this.addModel.stationCode // 所属设备集中站
                    };
                    this.$emit('updateMapModel', model);
                    this.$refs.make.resetForm();
                }
            });
        },
        // 修改对象
        edit() {
            this.$refs['dataform'].validate((valid) => {
                if (valid) {
                    const data = Object.assign({_type: this.editModel.type}, this.editModel);
                    this.$emit('updateMapModel', data);
                }
            });
        },
        // 删除对象
        deleteObj() {
            const selected = this.$store.getters['map/getDeviceByCode'](this.editModel.code);
            if (selected && selected._type.toUpperCase() === 'AutomaticRoute'.toUpperCase() || selected._type.toUpperCase() === 'AutoTurnBack'.toUpperCase() || selected._type.toUpperCase() === 'AxleReset'.toUpperCase() || selected._type.toUpperCase() == 'LimitControl'.toUpperCase()) {
                this.$confirm(this.$t('tip.confirmDeletion'), this.$t('tip.hint'), {
                    confirmButtonText: this.$t('tip.confirm'),
                    cancelButtonText: this.$t('tip.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.$emit('updateMapModel', {...selected, _dispose: true});
                    this.$refs.dataform && this.$refs.dataform.resetFields();
                }).catch(() => {
                    this.$message.info(this.$t('tip.cancelledDelete'));
                });
            }
        },
        hover(field) {
            this.field = field === this.field ? '' : field;
            if (this.field) {
                this.$emit('deviceSelect', 'ControlDraft');
            } else {
                this.$emit('deviceSelect', '');
            }
        },
        deleteOverlab(list, index) {
            list.splice(index, 1);
            this.cardMode = 'generate';
        },
        editOverlab(list, index) {
            this.addBackModel = deepAssign({}, list[index]);
            this.addBackModel.parentIndex = index;
            this.cardMode = 'edit';
        },
        updateOverlab() { // 修改数据
            this.$refs.hostileForm.validate((valid) => {
                if (valid) {
                    const data = {
                        id: this.addBackModel.id,
                        type: this.addBackModel.type,
                        label: this.addBackModel.label,
                        sectionList: this.addBackModel.type == 'NONE' ? [] : this.addBackModel.sectionList
                    };
                    this.editModel.optionList.splice(this.addBackModel.parentIndex, 1, data);
                    this.$refs.hostileForm.resetFields();
                    this.cardMode = 'generate';
                    this.addBackModel.sectionList = [];
                }
            });
        },
        generateOverlab() { // 生成数据
            this.$refs.hostileForm.validate((valid) => {
                if (valid) {
                    const id = this.createUid(this.editModel.optionList); // 根据类型写 uid 前缀命名
                    this.editModel.optionList.push({
                        id: id,
                        type: this.addBackModel.type,
                        label: this.addBackModel.label,
                        sectionList: this.addBackModel.type == 'NONE' ? [] : this.addBackModel.sectionList
                    });
                    this.$refs.hostileForm.resetFields();
                    this.addBackModel.sectionList = [];
                }
            });
        },
        cancelOverlab() {
            this.$refs.hostileForm.resetFields();
            this.cardMode = 'generate';
        },
        createUid(list) {
            if (list.length) {
                let num = Number(list[list.length - 1].id);
                return ++num;
            } else {
                return 1;
            }
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";
	.card {
		height: 100%;
	}
    .coordinate {
        overflow: hidden;

        .title {
            text-align: right;
            font-size: 14px;
            color: #606266;
            line-height: 40px;
            padding: 0 12px 0 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            line-height: 28px;
            width: 160px;
            font-weight: bold;
            display: block;
            float: left;
        }
    }

    .map-draft-group {
        color: #3E44BE;
    }
    .card-box{
        border: 1px solid #ccc;
        padding: 10px;
        padding-top: 18px;
        box-sizing: border-box;
        position: relative;
        margin-bottom: 15px;

        &:last-child{
            margin-bottom: 0;
        }

        .card_title {
            position: absolute;
            left: 10px;
            top: -8px;
            background: #fff;
            padding: 0px 5px;
        }
        }
</style>
