﻿<template>
  <el-tabs v-model="activeName" class="card">
    <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>
      <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">
        <el-button
          icon="el-icon-plus"
          circle
          size="small"
          style="position: absolute; right: 50px; top: 0px; z-index: 10;"
          class="point-button"
          @click="addModelList"
        />
        <el-form ref="make" label-width="140px" :model="addModel" size="mini" :rules="mergeRules">
          <el-form-item label="距区段高度:" prop="positionY">
            <el-input-number v-model="addModel.positionY" />
          </el-form-item>
          <el-table :data="addModel.modelList" style="width: 100%">
            <el-table-column label="计轴区段" prop="sectionName" width="160">
              <template slot-scope="scope">
                <el-select v-model="scope.row.sectionCode" filterable size="mini" placeholder="请选择">
                  <el-option
                    v-for="item in PhysicalSectionList"
                    :key="item.code"
                    :label="item.name + '(' + item.code +')'"
                    :value="item.code"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="车站名称">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stationName" placeholder="请输入内容" size="mini" />
              </template>
            </el-table-column>
            <el-table-column label="控制模式">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.control" />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">{{ $t('map.deleteObj') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </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-tab-pane class="view-control" :label="$t('map.batchSettings')" name="three" :lazy="lazy">
      <div style="height: 100%;overflow:auto">
        <el-form ref="oprt" :model="allModel" label-width="130px" size="mini">
          <el-form-item label="车站字体大小:" prop="nameFont">
            <el-font v-model="allModel.nameFont" :placeholder="this.$t('tip.stationFont')" />
          </el-form-item>
          <el-form-item label="公里标字体大小:" prop="kmPostFont">
            <el-font v-model="allModel.kmPostFont" :placeholder="this.$t('tip.stationFont')" />
          </el-form-item>
          <el-form-item label="车站Y坐标:" prop="positionY">
            <el-input-number v-model="allModel.positionY" />
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" @click="batchSettings">{{ $t('global.set') }}</el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import ElFont from '@/views/components/font/index';
import { mapGetters } from 'vuex';
import { getUID } from '@/jmapNew/utils/Uid';
import ConfigList from './config/list';
import { deepAssign } from '@/utils/index';
import getModel from './models.js';

export default {
    name: 'StationDraft',
    components: {
        ConfigList,
        ElFont
    },
    props: {
        selected: {
            type: Object,
            default: function () {
                return null;
            }
        }
    },
    data() {
        return {
            activeName: 'first',
            lazy: true,
            // field: '',
            chargeStation:[],
            relStationList: [], // 车站列表
            controlled:false,
            editModel: getModel('Station'),
            addModel: {
                modelList: [],
                positionY: 0
            },
            skins: [],
            mergeRules: {
                positionY: [
                    { required: true, message: '请输入高度值', trigger: 'blur' }
                ]
            },
            allModel: {
                nameFont: '',
                kmPostFont: '',
                positionY: 0
            }
        };
    },
    computed: {
        ...mapGetters('map', [
            'stationList',
            'sectionList',
            'zcList',
            'lineCode',
            'stationStandList'
        ]),
        form() {
            return {
                labelWidth: '130px',
                items: {
                    code: {
                        name: '',
                        item: []
                    },
                    draw: {
                        name: this.$t('map.drawData'),
                        item: [
                            { prop: 'code', label: this.$t('map.stationCode'), type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.stationList, deviceChange: this.deviceChange },
                            { prop: 'name', label: this.$t('map.stationName'), type: 'input' },
                            { prop: 'number', label: this.$t('map.stationNumber'), type: 'input' },
                            { prop: 'position', label: this.$t('map.stationPosition'), type: 'coordinate', width: '120px', 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: 'visible', label: this.$t('map.stationstandShowName'), type: 'checkbox' },
                            { prop: 'nameFont', label: this.$t('map.stationNameFont'), type: 'font', placeholder: this.$t('tip.stationFont') },
                            { prop: 'nameFontColor', label: this.$t('map.stationNameFontColor'), type: 'color' },
                            { prop: 'subheadDisplay', label: this.$t('map.subheadDisplay'), type: 'checkbox' },
                            { prop: 'subhead', label: this.$t('map.subhead'), type: 'input', isHidden:!this.editModel.subheadDisplay },
                            { prop: 'subheadFont', label: this.$t('map.subheadFont'), type: 'font', isHidden:!this.editModel.subheadDisplay },
                            { prop: 'subheadFontColor', label: this.$t('map.subheadFontColor'), type: 'color', isHidden:!this.editModel.subheadDisplay },
                            { prop: 'subheadPosition', label: this.$t('map.subheadPosition'), type: 'coordinate', width: '120px', isHidden:!this.editModel.subheadDisplay, children: [
                                { prop: 'subheadPosition.x', firstLevel: 'subheadPosition', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px' },
                                { prop: 'subheadPosition.y', firstLevel: 'subheadPosition', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '25px' }
                            ] },

                            { prop: 'depot', label: this.$t('map.isParkingArea'), type: 'checkbox' },
                            { prop: 'reentry', label: this.$t('map.isReentryStation'), type: 'checkbox' }, // 是否折返车站
                            { prop: 'smallRouting', label: '是否小交路:', type: 'checkbox', isHidden:!this.isReentry },

                            { prop: 'kilometerPosition', label: '公里标偏移坐标:', type: 'coordinate', width: '120px', children: [
                                { prop: 'kilometerPosition.x', firstLevel: 'kilometerPosition', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px' },
                                { prop: 'kilometerPosition.y', firstLevel: 'kilometerPosition', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '25px' }
                            ] },
                            { prop: 'kmRange', label: this.$t('map.stationKmRange'), type: 'number', min: 0, placeholder: this.$t('tip.meter') },
                            { prop: 'kmPost', label: this.$t('map.stationKmPost'), type: 'input' },
                            { prop: 'kmPostFont', label: this.$t('map.stationKmPostFont'), type: 'font', placeholder: this.$t('tip.kilometerFont') },
                            { prop: 'kmPostFontColor', label: this.$t('map.stationKmPostFontColor'), type: 'color' },
                            { prop: 'createControlMode', label: '控制模式:', type: 'checkbox' },
                            { prop: 'controlModePoint', label: this.$t('map.stationControlPosition'), type: 'coordinate', width: '120px', isHidden:!this.editModel.createControlMode, children: [
                                { prop: 'controlModePoint.x', firstLevel: 'controlModePoint', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px'},
                                { prop: 'controlModePoint.y', firstLevel: 'controlModePoint', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '25px'}
                            ] },
                            { prop: 'createTurnBack', label: '按图折返:', type: 'checkbox' },
                            { prop: 'turnBackPoint', label: '按图折返坐标:', type: 'coordinate', width: '120px', isHidden: !this.isPointsShow, children: [
                                { prop: 'turnBackPoint.x', firstLevel: 'turnBackPoint', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px' },
                                { prop: 'turnBackPoint.y', firstLevel: 'turnBackPoint', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '25px' }
                            ] }
                        ]
                    },
                    map: {
                        name: this.$t('map.mapData'),
                        item: [
                            { prop: 'ciStation', label: this.$t('map.isCIStation'), type: 'checkbox'},
                            { prop: 'centralized', label: this.$t('map.centralized'), type: 'checkbox', disabled:this.controlled },
                            { prop: 'zcCode', label: this.$t('map.zcCode'), type: 'select', optionLabel: 'code&&name', optionValue: 'code', options: this.zcList, isHidden: !this.isZcCode, disabled:true },
                            { prop: 'chargeStationCodeList', label: '管理车站列表:', type: 'multiSelect', optionLabel: 'name', optionValue: 'code', options: this.chargeStation, isHidden: !this.isZcCode },
                            { prop: 'relStationCodeList', label: '联锁站关联车站:', type: 'multiSelect', optionLabel: 'name', optionValue: 'code', options: this.relStationList, isHidden: !this.idCiStation},
                            { prop: 'runPlanName', label: this.$t('map.stationRunPlanName'), type: 'input' }
                        ]
                    }
                }
            };
        },
        rules() {
            return {
                code: [
                    { required: true, message: this.$t('rules.selectEquipment'), trigger: 'change' }
                ],
                name: [
                    { required: true, message: this.$t('rules.stationName'), trigger: 'blur' }
                ],
                kmRange: [
                    { required: true, message: this.$t('rules.stationKmRange'), trigger: 'blur' }
                ],
                kmPost: [
                    { required: true, message: this.$t('rules.stationKmPost'), trigger: 'blur' }
                ],
                'position.x': [
                    { required: true, message: this.$t('rules.pleaseEnterXCoordinate'), trigger: 'blur' }
                ],
                'position.y': [
                    { required: true, message: this.$t('rules.pleaseEnterYCoordinate'), trigger: 'blur' }
                ]
            };
        },
        PhysicalSectionList() {
            return this.sectionList.filter(elem => { return elem.type === '01' && !elem.switchSection; });
        },

        isPointsShow() {
            return this.editModel.createTurnBack;
        },
        isZcCode() {
            return this.editModel.centralized;
        },
        idCiStation() {
            return this.editModel.ciStation;
        },
        isReentry() {
            return this.editModel.reentry;
        }
    },
    methods: {
        deviceChange(code) {
            this.$emit('setCenter', code);
            this.deviceSelect(this.$store.getters['map/getDeviceByCode'](code));
        },
        deviceSelect(selected) {
            if (selected && selected._type.toUpperCase() === 'Station'.toUpperCase()) {
                this.editModel = getModel('Station');
                this.$refs.dataform && this.$refs.dataform.resetFields();
                this.activeName = 'first';
                this.editModel = deepAssign(this.editModel, selected);
                // 被控制的车站数据
                const beCentralizedStation = {};
                this.relStationList = JSON.parse(JSON.stringify(this.stationList));
                this.stationList.forEach(data=>{
                    if (data.centralized) {
                        data.chargeStationCodeList.forEach(charge=>{
                            beCentralizedStation[charge] = data.code;
                        });
                    }
                    if (data.ciStation && data.code != this.selected.code) {
                        const arr = data.relStationCodeList || [];
                        arr.forEach(stationCode => {
                            this.relStationList.forEach((data, index) => {
                                if (data.code == stationCode) {
                                    this.relStationList.splice(index, 1);
                                }
                            });
                        });
                    }
                });
                // 筛选数据 去掉已经是集中站的数据，去掉自己本身，去掉被别的集中站选中的数据
                this.chargeStation = this.stationList.filter(data=>{
                    return !data.centralized && data.code != this.editModel.code && !(beCentralizedStation[data.code] && beCentralizedStation[data.code] != this.editModel.code);
                });
                this.controlled = !!beCentralizedStation[selected.code];
            }
        },
        // 选择管理车站
        changeChargeStation(list) {
            let lists = [];
            if (list.length > 0) {
                this.chargeStation.forEach(station=>{
                    lists = lists.concat(this.setStationStand(station, ''));
                    list.forEach(each=>{
                        switch (each) {
                        case station.code: {
                            lists = lists.concat(this.setStationStand(station, this.editModel.code));
                            break;
                        }
                        }
                    });
                });
            } else {
                // 没有选中数据，直接将其他车站设置为非控制
                lists = lists.concat(this.modifyChargeStation());
            }
            return lists;
        },
        changeCentralized(data) {
            let list = [];
            if (!data) { // 将当前车站选为非集中站
                this.editModel.chargeStationCodeList = [];
                const arr = this.modifyChargeStation();
                const arr1 = this.setStationStand(this.editModel, '');
                list = [...arr, ...arr1];
            } else {
                list = list.concat(this.setStationStand(this.editModel, this.editModel.code));
            }
            return list;
        },
        modifyChargeStation() {
            let list = [];
            this.chargeStation.forEach(station=>{
                list = list.concat(this.setStationStand(station, ''));
            });
            return list;
        },
        // 设置站台 {设备集中站}
        setStationStand(station, code) {
            const list = [];
            this.stationStandList.forEach(elem=>{
                if (elem.stationCode == station.code) {
                    const stationStand = deepAssign({}, elem);
                    stationStand.deviceStationCode = code;
                    list.push(stationStand);
                }
            });
            return list;
        },
        create() {
            this.$refs['make'].validate((valid) => {
                if (valid) {
                    if (this.addModel.modelList.length) {
                        const models = [];
                        this.addModel.modelList.forEach((item) => {
                            const uid = getUID('Station', [...this.stationList, ...models]);
                            const stationModel = getModel('Station');
                            const data = {
                                code: uid,
                                name: item.stationName,
                                createControlMode: item.control
                            };
                            const model = Object.assign(stationModel, data);
                            const sectionModel = this.$store.getters['map/getDeviceByCode'](item.sectionCode);
                            const last = sectionModel.points.length - 1;
                            model.position = {
                                x: sectionModel.points[0].x + (sectionModel.points[last].x - sectionModel.points[0].x) / 2,
                                y: sectionModel.points[0].y - this.addModel.positionY
                            };
                            if (item.control) {
                                model.controlModePoint = {
                                    x: sectionModel.points[0].x + (sectionModel.points[last].x - sectionModel.points[0].x) / 2,
                                    y: sectionModel.points[0].y - this.addModel.positionY + 30
                                };
                            }
                            models.push(model);
                        });
                        this.$emit('updateMapModel', models);
                        this.addModel = {
                            modelList: [],
                            positionY: 0
                        };
                    } else {
                        this.$message('请添加数据');
                    }
                }
            });
        },
        // 修改对象
        edit() {
            this.$refs['dataform'].validate((valid) => {
                if (valid) {
                    const list = this.changeChargeStation(this.editModel.chargeStationCodeList);
                    let centralizedList = [];
                    if (this.editModel.centralized != this.selected.centralized) {
                        centralizedList = this.changeCentralized(this.editModel.centralized);
                    }
                    const models = [this.editModel, ...list, ...centralizedList];
                    this.$emit('updateMapModel', models);
                }
            });
        },
        // 删除对象
        deleteObj() {
            const selected = this.$store.getters['map/getDeviceByCode'](this.editModel.code);
            if (selected && selected._type == 'Station') {
                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'));
                });
            }
        },
        // 批量设置
        batchSettings() {
            const models = [];
            this.stationList.forEach(station => {
                const model = deepAssign({}, station);
                model.nameFont = this.allModel.nameFont;
                model.kmPostFont = this.allModel.kmPostFont;
                model.position.y = this.allModel.positionY;
                models.push(model);
            });
            this.$emit('updateMapModel', models);
        },
        handleDelete(index, row) {
            this.addModel.modelList.splice(index, 1);
        },
        addModelList() {
            this.addModel.modelList.push({
                sectionCode: '',
                sectionName: '',
                stationName: `车站 ${this.addModel.modelList.length + 1}`,
                control: false
            });
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";
	.card {
		height: 100%;
	}
</style>
