<template>
  <el-tabs v-model="activeName" class="card">
    <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">
          <el-form ref="make" label-width="130px" :model="addModel" size="mini" :rules="mergeRules">
            <el-form-item :label="$t('map.physicalSegmentName')" prop="sectionCode">
              <el-select v-model="addModel.sectionCode" filterable>
                <el-option
                  v-for="item in PhysicalSectionList"
                  :key="item.code"
                  :label="item.name + ' (' + item.code+ ')'"
                  :value="item.code"
                />
              </el-select>
              <el-button
                :type="field === 'selectSingalCode' ? 'danger' : 'primary'"
                size="small"
                @click="hover('selectSingalCode')"
              >{{ $t('map.activate') }}</el-button>
            </el-form-item>
            <el-form-item :label="$t('map.leftOrRight')" prop="leftOrRight">
              <el-select v-model="addModel.leftOrRight" filterable>
                <el-option
                  v-for="item in SignalLeftOrRightList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('map.directionType')" prop="directionType">
              <el-select v-model="addModel.directionType" filterable>
                <el-option
                  v-for="item in SignalDirectionTypeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('map.signalDirectionTypeX')" prop="directionShowType">
              <el-select v-model="addModel.directionShowType" filterable>
                <el-option
                  v-for="item in SignalDirectionList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('map.positionType')" prop="positionType">
              <el-select v-model="addModel.positionType" filterable>
                <el-option
                  v-for="item in SignalPositionTypeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('map.equipmentStation')" prop="stationCode">
              <el-select v-model="addModel.stationCode" filterable>
                <el-option
                  v-for="item in stationList"
                  :key="item.code"
                  :label="item.name + item.code"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </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 '@/jmap/utils/Uid';
import JTriangle from '@/jmap/utils/JTriangle';
import ConfigList from './config/list';
import { deepAssign } from '@/utils/index';

export default {
    name: 'SignalDraft',
    components: {
        ConfigList
    },
    props: {
        selected: {
            type: Object,
            default: function () {
                return null;
            }
        }
    },
    data() {
        return {
            activeName: 'first',
            SignalDirectionList: [
                { code: '01', name: '向左' },
                { code: '02', name: '向右' }
            ],
            SignalLeftOrRightList: [],
            SignalPotLampTypeList: [],
            SignalLampPostTypeList: [],
            SignalLampPositionTypeList: [],
            SignalDirectionTypeList: [],
            SignalPositionTypeList: [],
            SignalUseTypeList: [],
            failTypes: [
                { code: '00', name: this.$t('map.normal') },
                { code: '01', name: this.$t('map.signalFilamentAlarm') }
            ],
            editModel: {
                code: '',
                name: '',
                uniqueName: '',
                nameShow: false,
                lampPostType: '',
                lampPositionType: '',
                potLampType: '01',
                directionShowType: '',
                directionType: '',
                positionType: '',
                namePosition: { x: 0, y: 0 },
                useType: '',
                stationCode: '',
                offset: 0,
                rotate: 0,
                sectionCode: '',
                guideShow: false,
                buttonShow: false,
                position: { x: 0, y: 0 },
                buttonPosition: { x: 0, y: 0 },
                guidePosition: { x: 0, y: 0 }
            },
            field: '',
            addModel: {
                sectionCode: '',
                directionType: '01',
                directionShowType: '01',
                leftOrRight: '0',
                positionType: '01',
                stationCode: ''
            },
            mergeRules: {
                sectionCode: [
                    { required: true, message: this.$t('rules.selectPhysicalExtentName'), trigger: 'change' }
                ],
                directionType: [
                    { required: true, message: this.$t('map.pleaseSelect') + '' + this.$t('map.directionType'), trigger: 'change' }
                ],
                directionShowType: [
                    { required: true, message: this.$t('map.pleaseSelect') + '' + this.$t('map.directionType'), trigger: 'change' }
                ],
                leftOrRight: [
                    { required: true, message: this.$t('map.pleaseSelect') + '' + this.$t('map.leftOrRight'), trigger: 'change' }
                ],
                positionType: [
                    { required: true, message: this.$t('map.pleaseSelect') + '' + this.$t('map.positionType'), trigger: 'change' }
                ],
                stationCode: [
                    { required: true, message: this.$t('map.pleaseSelect') + '' + this.$t('map.equipmentStation'), trigger: 'change' }
                ]
            }
        };
    },
    computed: {
        ...mapGetters('map', [
            'linkList',
            'signalList',
            'sectionList',
            'stationList',
            'lineCode'
        ]),
        PhysicalSectionList() {
            let list = [];
            if (this.sectionList && this.sectionList.length) {
                list = this.sectionList.filter(elem => { return elem.type === '01' && !elem.isSwitchSection; });
            }
            return list;
        },
        // 物理区段和道岔区段
        signalSectionList() {
            let list = [];
            if (this.sectionList && this.sectionList.length) {
                list = this.sectionList.filter(elem => {
                    return elem.type === '01' || elem.type === '03';
                });
            }
            return list;
        },
        form() {
            return {
                labelWidth: '150px',
                items: {
                    code: {
                        name: '',
                        item: []
                    },
                    draw: {
                        name: this.$t('map.drawData'),
                        item: [
                            { prop: 'code', label: this.$t('map.signalCodeColon'), type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.signalList, change: true, deviceChange: this.deviceChange },
                            { prop: 'name', label: this.$t('map.signalNameColon'), type: 'input' },
                            { prop: 'position', label: this.$t('map.signalPosition'), 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: 'lampPostType', label: this.$t('map.lampPostType'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.SignalLampPostTypeList },
                            { prop: 'lampPositionType', label: this.$t('map.lampPositionType'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.SignalLampPositionTypeList },
                            { prop: 'directionShowType', label: this.$t('map.signalDirectionTypeX'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.SignalDirectionList },
                            { prop: 'positionType', label: this.$t('map.signalPositionType'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.SignalPositionTypeList },
                            { prop: 'rotate', label: this.$t('map.rotateAngle'), type: 'number', min: -90, max: 90, placeholder: this.$t('tip.angle') },
                            { prop: 'namePosition', label: this.$t('map.signalNamePosition'), type: 'coordinate', width: '140px', children: [
                                { prop: 'namePosition.x', firstLevel: 'namePosition', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px' },
                                { prop: 'namePosition.y', firstLevel: 'namePosition', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '25px' }
                            ] },
                            { prop: 'buttonShow', label: this.$t('map.signalButtonShow'), type: 'checkbox' },
                            { prop: 'buttonPosition', label: this.$t('map.signalButtonPosition'), type: 'coordinate', width: '140px', children: [
                                { prop: 'buttonPosition.x', firstLevel: 'buttonPosition', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px' },
                                { prop: 'buttonPosition.y', firstLevel: 'buttonPosition', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '25px' }
                            ] },
                            { prop: 'guideShow', label: this.$t('map.signalGuideShow'), type: 'checkbox' },
                            { prop: 'guidePosition', label: this.$t('map.signalGuidePosition'), type: 'coordinate', width: '140px', children: [
                                { prop: 'guidePosition.x', firstLevel: 'guidePosition', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px' },
                                { prop: 'guidePosition.y', firstLevel: 'guidePosition', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '25px' }
                            ] }
                        ]
                    },
                    map: {
                        name: this.$t('map.mapData'),
                        item: [
                            { prop: 'stationCode', label: this.$t('map.equipmentStation'), type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.stationList },
                            { prop: 'directionType', label: this.$t('map.signalDirectionType'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.SignalDirectionTypeList },
                            { prop: 'uniqueName', label: this.$t('map.signalUniqueName'), type: 'input' },
                            { prop: 'useType', label: this.$t('map.signalUseType'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.SignalUseTypeList },
                            { prop: 'potLampType', label: this.$t('map.potLampType'), type: 'select', optionLabel: 'name', optionValue: 'code', options: this.SignalPotLampTypeList },
                            { prop: 'sectionCode', label: '所属区段:', type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.signalSectionList },
                            { prop: 'offset', label: this.$t('map.signalOffset'), type: 'number', min: 0, placeholder: this.$t('tip.meter') }

                        ]
                    }
                }
            };
        },
        rules() {
            return {
                code: [
                    { required: true, message: this.$t('rules.selectEquipment'), trigger: 'change' }
                ],
                name: [
                    { required: true, message: this.$t('rules.pleaseEnterSemaphoreName'), trigger: 'blur' }
                ],
                uniqueName: [
                    { required: true, message: this.$t('rules.pleaseEnterSignalName'), trigger: 'blur' }
                ],
                offset: [
                    { required: true, message: this.$t('rules.pleaseEnterSignalOffset'), trigger: 'blur' }
                ],
                'position.x': [
                    { required: true, message: this.$t('rules.pleaseEnterSignalPositionX'), trigger: 'blur' }
                ],
                'position.y': [
                    { required: true, message: this.$t('rules.pleaseEnterSignalPositionY'), trigger: 'blur' }
                ],
                'buttonPosition.x': [
                    { required: true, message: this.$t('rules.signalButtonPositionX'), trigger: 'blur' }
                ],
                'buttonPosition.y': [
                    { required: true, message: this.$t('rules.signalButtonPositionY'), trigger: 'blur' }
                ],
                'guidePosition.x': [
                    { required: true, message: this.$t('rules.signalGuidePositionX'), trigger: 'blur' }
                ],
                'guidePosition.y': [
                    { required: true, message: this.$t('rules.signalGuidePositionY'), trigger: 'blur' }
                ]
            };
        }
    },
    watch: {
        selected(val, oldVal) {
            this.deviceSelect(val);
        }
    },
    mounted() {
        this.SignalLeftOrRightList = this.$ConstSelect.SignalLeftOrRightList;

        this.$Dictionary.signalPotLampType().then(list => {
            this.SignalPotLampTypeList = list;
        });

        this.$Dictionary.signalLampPostType().then(list => {
            this.SignalLampPostTypeList = list;
        });

        this.$Dictionary.signalLampPositionType().then(list => {
            this.SignalLampPositionTypeList = list;
        });

        this.$Dictionary.signalDirectionType().then(list => {
            this.SignalDirectionTypeList = list;
        });

        this.$Dictionary.signalPositionType().then(list => {
            this.SignalPositionTypeList = list;
        });

        this.$Dictionary.signalUseType().then(list => {
            this.SignalUseTypeList = list;
        });
    },
    methods: {
        deviceChange(code) {
            this.$emit('setCenter', code);
            this.deviceSelect(this.$store.getters['map/getDeviceByCode'](code));
        },
        deviceSelect(selected) {
            this.$refs.dataform.resetFields();
            this.$refs.make.resetFields();
            if (selected && selected._type.toUpperCase() === 'Signal'.toUpperCase()) {
                this.activeName = 'first';
                this.editModel = deepAssign(this.editModel, selected);
                this.editModel.potLampType = selected.potLampType || '01';
                this.editModel.rotate = selected.rotate || 0; // 角度
            }

            if (this.field.toUpperCase() === 'selectSingalCode'.toUpperCase()) {
                this.addModel.sectionCode = selected.code;
                this.activeName = 'second';
                this.field = '';
                this.$emit('signalSectionCode', '');
            }
        },
        hover(field) {
            this.field = field === this.field ? '' : field;
            this.$emit('signalSectionCode', this.field);
        },
        create() {
            this.$refs['make'].validate((valid) => {
                if (valid) {
                    if (this.addModel.sectionCode) {
                        const uid = getUID('Singal');
                        var model = {
                            _type: 'Signal',
                            code: uid,
                            uniqueName: uid,
                            sectionCode: this.addModel.sectionCode,
                            positionType: this.addModel.positionType,
                            directionType: this.addModel.directionType,
                            directionShowType: this.addModel.directionShowType,
                            nameShow: true,
                            namePosition: { x: 0, y: 0 },
                            buttonShow: true,
                            useType: '01',
                            potLampType: '01',
                            lampPostType: '01',
                            lampPositionType: '01',
                            guideShow: false,
                            stationCode: this.addModel.stationCode
                        };
                        this.sectionList.forEach(elem => {
                            if (elem.code === this.addModel.sectionCode) {
                                model.name = 'Signal_' + elem.name.replace('Section_', '');
                                model.linkCode = elem.code;
                                if (this.addModel.leftOrRight === '0') {
                                    const beg = elem.points[0];
                                    const end = elem.points[0 + 1];
                                    const traingle = new JTriangle(beg, end);
                                    model.rotate = Math.floor(traingle.getAngle());
                                    model.position = { x: elem.points[0].x, y: elem.points[0].y };
                                    model.guidePosition = { x: elem.points[0].x, y: elem.points[0].y };
                                    model.buttonPosition = { x: elem.points[0].x, y: elem.points[0].y };
                                    model.offset = elem.lengthFact && elem.lengthFact > 2 ? 2 : 0;
                                } else {
                                    const r = elem.points.length - 1;
                                    const beg = elem.points[r - 1];
                                    const end = elem.points[r];
                                    const traingle = new JTriangle(beg, end);
                                    model.rotate = Math.floor(traingle.getAngle());
                                    model.position = { x: elem.points[r].x, y: elem.points[r].y };
                                    model.guidePosition = { x: elem.points[r].x, y: elem.points[r].y };
                                    model.buttonPosition = { x: elem.points[r].x, y: elem.points[r].y };
                                    model.offset = elem.lengthFact && elem.lengthFact > 2 ? elem.lengthFact - 2 : 0;
                                }
                            }
                        });

                        this.$emit('updateMapModel', model);
                    } else {
                        this.$messageBox(this.$t('tip.selectedSectionEmpty'));
                    }
                }
            });
        },
        // 修改对象
        edit() {
            this.$refs['dataform'].validate((valid) => {
                if (valid) {
                    const data = Object.assign({_type: 'Signal'}, this.editModel);
                    this.$emit('updateMapModel', data);
                }
            });
        },
        // 删除对象
        deleteObj() {
            const selected = this.$store.getters['map/getDeviceByCode'](this.editModel.code);
            if (selected && selected._type === 'Signal') {
                const _that = this;
                this.$confirm(this.$t('tip.confirmDeletion'), this.$t('tip.hint'), {
                    confirmButtonText: this.$t('tip.confirm'),
                    cancelButtonText: this.$t('tip.cancel'),
                    type: 'warning'
                }).then(() => {
                    _that.$emit('updateMapModel', {...selected, _dispose: true});
                    _that.deviceSelect();
                }).catch(() => {
                    _that.$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%;
	}
</style>
