<template>
  <el-tabs v-model="activeName" class="card" @tab-click="handleClick">
    <el-tab-pane class="view-control" :label="$t('map.property')" name="first">
      <div style="height: calc(100% - 46px);">
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <config-list ref="dataform" :form="form" :form-model="editModel" :rules="rules" />
        </el-scrollbar>
      </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">
      <div style="height: calc(100% - 46px);">
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <config-data ref="make" :form="formMake" :form-model="addModel" :rules="createRules" />
        </el-scrollbar>
      </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',
            autoList: [],
            typeList: [
                { name: '自动折返', value: 'MapCycleButtonVO' },
                { name: '计轴复位', value: 'AxleReset' },
                { name: '自动进路', value: 'AutomaticRoute' },
                { name: '引导总锁', value: 'GuideLock' },
                { name: '全线临时限速', value: 'LimitControl' }
            ],
            editModel: {
                code: '',
                type: '',
                name: '',
                subtitleName: '',
                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' }
                ]
            }
        };
    },
    computed: {
        ...mapGetters('map', [
            'automaticRouteButtonList',
            'cycleButtonList',
            'tempSpeedLimitList',
            'axleCounterResetButtonList',
            'totalGuideLockButtonVOList',
            'stationList'
        ]),
        form() {
            const form = {
                labelWidth: '150px',
                items: {
                    code: {
                        name: '',
                        item: []
                    },
                    draw: {
                        name: this.$t('map.drawData'),
                        item: [
                            { prop:'type', label: '功能类型:', type: 'select', optionLabel: 'name', optionValue: 'value', options: this.typeList, disabled: true },
                            { 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: '按钮主名称:', type: 'input' },
                            { prop: 'subtitleName', label: '按钮副名称:', type: 'input' },
                            { prop: 'position', label: '坐标:', 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: '自动进路code:', type: 'select', optionLabel: 'name', optionValue: 'code', options: this.autoList, isHidden: !this.isHiddenAutomaticRoute, change: true, deviceChange: this.ChangeStation },
                            { prop:'cycleCode', label: '自动折返进路code:', type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.autoList, isHidden: !this.isHiddenMapCycleButtonVO, change: true, deviceChange: this.ChangeStation },
                            { 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: '功能类型:', type: 'select', optionLabel: 'name', optionValue: 'value', options: this.typeList, change: true, deviceChange: this.typeChange },
                    { prop: 'name', label: '按钮主名称:', type: 'input' },
                    { prop: 'position', label: '坐标:', 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: '自动进路code:', type: 'select', optionLabel: 'name', optionValue: 'code', options: this.autoList, isHidden: !this.isHiddenCreateAutomaticRoute, change: true, deviceChange: this.ChangeStation },
                    { prop:'cycleCode', label: '自动折返进路code:', 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: '请选择功能类型', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入名称', 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 == 'MapCycleButtonVO';
        },
        isDisabledStation() {
            return this.editModel.type == 'MapCycleButtonVO' || this.editModel.type == 'AutomaticRoute';
        },
        isHiddenStation() {
            return this.editModel.type == 'MapCycleButtonVO' || this.editModel.type == 'AutomaticRoute' || this.editModel.type == 'AxleReset';
        },

        isHiddenCreateAutomaticRoute() {
            return this.addModel.type == 'AutomaticRoute';
        },
        isHiddenCreateMapCycleButtonVO() {
            return this.addModel.type == 'MapCycleButtonVO';
        },
        isDisabledCreateStation() {
            return this.addModel.type == 'MapCycleButtonVO' || this.addModel.type == 'AutomaticRoute';
        },
        isHiddenCreateStation() {
            return this.addModel.type == 'MapCycleButtonVO' || this.addModel.type == 'AutomaticRoute' || this.addModel.type == 'AxleReset';
        }
    },
    watch: {
        selected(val, oldVal) {
            this.deviceSelect(val);
        }
    },
    mounted() {

    },
    methods: {
        typeChange(type) { // 根据类型来选择功能按钮列表
            this.$refs.dataform.resetFields();
            this.$refs.make.resetFields();
            this.addModel.automaticRouteCode = '';
            this.addModel.cycleCode = '';
            this.addModel.concentrateStationList = '';
            this.addModel.type = type; // 上面清除掉重新赋值
            this.handleTypes(type);
        },
        handleTypes(type) {
            switch (type) {
            case 'MapCycleButtonVO':
                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;
            }
        },
        ChangeStation(code) { // 选择对应的所属设备集中站
            this.autoList.forEach(elem => {
                if (elem.code == code) {
                    this.addModel.stationCode = elem.stationCode;
                }
            });
        },
        deviceChange(code) {
            this.$emit('setCenter', code);
            this.deviceSelect(this.$store.getters['map/getDeviceByCode'](code));
        },
        handleClick() {
            this.getAutoMaticList();
        },
        deviceSelect(selected) {
            this.$refs.dataform.resetFields();
            this.$refs.make.resetFields();
            if (selected && selected._type.toUpperCase() == 'AutomaticRoute'.toUpperCase() || selected._type.toUpperCase() == 'MapCycleButtonVO'.toUpperCase() || selected._type.toUpperCase() == 'AxleReset'.toUpperCase() || selected._type.toUpperCase() == 'LimitControl'.toUpperCase()) {
                this.activeName = 'first';
                this.editModel = deepAssign(this.editModel, selected);
                this.editModel.type = selected._type;
            }
        },
        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 models = [];
                    const model = {
                        _type: this.addModel.type,
                        code: uid,
                        name: this.addModel.name,
                        subtitleName: this.addModel.subtitleName,
                        position: {
                            x: this.addModel.position.x,
                            y: this.addModel.position.y
                        },
                        automaticRouteCode: this.addModel.automaticRouteCode, // 关联自动进路code
                        cycleCode: this.addModel.cycleCode, // 自动折返关联code
                        stationCode: this.addModel.stationCode // 所属设备集中站
                    };
                    models.push(model);
                    this.$emit('updateMapModel', models);
                    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() === 'MapCycleButtonVO'.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.resetFields();
                }).catch(() => {
                    this.$message.info(this.$t('tip.cancelledDelete'));
                });
            }
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";
	.view-control{
		height: 100%;
	}

	.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;
    }
</style>
