<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="form" :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.batchOperation')" name="three">
      <div style="height: 100%">
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <div style="text-align:center;">
            <el-button type="danger" size="big" @click="removeTrainWindow">{{ $t('map.deleteTrainWindow') }}</el-button>
            <el-button type="primary" size="big" style="margin-top:10px" @click="createTrainWindow">{{ $t('map.createTrainWindow') }}</el-button>
          </div>
        </el-scrollbar>
      </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: 'TrainWindowDraft',
    components: {
        ConfigList
    },
    props: {
        selected: {
            type: Object,
            default: function () {
                return null;
            }
        }
    },
    data() {
        return {
            activeName: 'first',
            mapData: null,
            editModel: {
                code: '',
                point: {
                    x: 0,
                    y: 0
                },
                width: 0,
                height: 0,
                sectionCode: '',
                isReversal: false
            },
            rules: {
                code: [
                    { required: true, message: this.$t('rules.pleaseReSelectDevice'), trigger: 'blur' }
                ],
                'point.x': [
                    { required: true, message: this.$t('rules.trainPositionX'), trigger: 'blur' }
                ],
                'point.y': [
                    { required: true, message: this.$t('rules.trainPositionY'), trigger: 'blur' }
                ],
                width: [
                    { required: true, message: this.$t('rules.trainWindowWidth'), trigger: 'blur' }
                ],
                height: [
                    { required: true, message: this.$t('rules.trainWindowHeight'), trigger: 'blur' }
                ],
                sectionCode: [
                    { required: true, message: this.$t('rules.trainWindowSectionCode'), trigger: 'change' }
                ]

            }
        };
    },
    computed: {
        ...mapGetters('map', [
            'sectionList',
            'trainWindowList'
        ]),
        filterSectionList() {
            let list = [];
            if (this.sectionList && this.sectionList.length) {
                list = this.sectionList.filter(elem => { return !(elem.type == '03' && elem.parentCode); });
            }
            return list;
        },
        form() {
            const form = {
                labelWidth: '120px',
                items: {
                    code: {
                        name: '',
                        item: []
                    },
                    draw: {
                        name: this.$t('map.drawData'),
                        item: [
                            { prop: 'code', label: this.$t('map.trainWindowCode'), type: 'select', optionLabel: 'code', optionValue: 'code', options: this.trainWindowList, change: true, deviceChange: this.deviceChange },
                            { prop: 'width', label: this.$t('map.trainWindowWidth'), type: 'number', min: 0, placeholder: 'px' },
                            { prop: 'height', label: this.$t('map.trainWindowHeight'), type: 'number', min: 0, placeholder: 'px' },
                            { prop: 'point', label: this.$t('map.trainWindowPoints'), type: 'coordinate', width: '110px', children: [
                                { prop: 'point.x', firstLevel: 'point', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '20px', disabled: false },
                                { prop: 'point.y', firstLevel: 'point', secondLevel: 'y', label: 'y:', type: 'number', labelWidth: '20px', disabled: false }
                            ] }
                        ]
                    },
                    map: {
                        name: this.$t('map.mapData'),
                        item: [
                            { prop: 'sectionCode', label: this.$t('map.trainWindowSectionCode'), type: 'select', optionLabel: 'code&&name', optionValue: 'code', options: this.filterSectionList },
                            { prop: 'isReversal', label: '车头翻转', type: 'checkbox' }
                        ]
                    }
                }
            };
            return form;
        },
        style() {
            return this.$jlmap.style;
        }
    },
    watch: {
        selected: function (val, oldVal) {
            this.deviceSelect(val);
        }
    },
    methods: {
        filterSections(query, item) {
            return item.pinyin.indexOf(query) > -1;
        },
        deviceChange(code) {
            this.$emit('setCenter', code);
            this.deviceSelect(this.$store.getters['map/getDeviceByCode'](code));
        },
        deviceSelect(selected) {
            if (selected && selected._type.toUpperCase() === 'TrainWindow'.toUpperCase()) {
                this.$refs.form.resetFields();
                this.activeName = 'first';
                this.editModel = deepAssign(this.editModel, selected);
            }
        },
        createModel(opts) {
            const model = {
                _type: 'TrainWindow',
                code: getUID('TrainWindow'),
                trainWindowShow: true,
                point: {},
                isReversal: false
            };

            if (opts) {
                var width = this.style.trainWindowWidth;
                var height = this.style.trainWindowHeight;
                const section = opts.section;
                if (section) {
                    if (section.type !== '03' && opts.triangle) {
                        model.point = opts.triangle.middlePoint();
                        if (opts.triangle.getCosRate() == 1 && opts.triangle.absx < width) {
                            width = opts.triangle.absx;
                        }

                        if (opts.triangle.getCosRate() !== 0 && opts.triangle.getCosRate() !== 1) {
                            model.point.x = section.points[0].x;
                            model.point.y = section.points[section.points.length - 1].y;
                        }
                    } else {
                        model.point = {
                            x: section.namePosition.x,
                            y: section.namePosition.y
                        };
                    }

                    const distance = (this.style.trainDistance + this.style.trainConflictR * 2 + height);
                    let offsetx = 0;
                    let offsety = 0;
                    if (opts.triangle) {
                        if (opts.triangle.getCosRate() == 1 || opts.triangle.getCosRate() == 0) {
                            offsetx = distance * opts.triangle.getSinRate();
                            offsety = distance * opts.triangle.getCosRate();
                        } else {
                            offsetx = distance;
                            offsety = distance;
                        }
                    } else {
                        offsetx = 0;
                        offsety = distance;
                    }
                    if (section.trainPosType == '01') {
                        model.point.y = model.point.y - height - offsety;
                        model.point.x = model.point.x - offsetx;
                    } else {
                        model.point.x = model.point.x + offsetx;
                        model.point.y = model.point.y + offsety;
                    }
                    model.sectionCode = section.code;
                    model.height = height;
                    model.width = width;
                }
            }
            return model;
        },
        // 一键删除车次窗
        removeTrainWindow() {
            this.$confirm(this.$t('tip.confirmDeletion'), this.$t('tip.hint'), {
                confirmButtonText: this.$t('tip.confirm'),
                cancelButtonText: this.$t('tip.cancel'),
                type: 'warning'
            }).then(() => {
                const remove = [];
                if (this.trainWindowList && this.trainWindowList.length) {
                    this.trainWindowList.forEach(elem => {
                        remove.push({
                            _type: 'TrainWindow',
                            code: elem.code,
                            _dispose: true
                        });
                    });
                    this.$emit('updateMapModel', remove);
                }
            }).catch(() => {
                this.$message.info(this.$t('tip.cancelledDelete'));
            });
        },
        // 一键创建车次窗
        createTrainWindow() {
            const models = [];
            const collection = this.sectionList;

            const remove = []; // 清空所有车次窗
            if (this.trainWindowList && this.trainWindowList.length) {
                this.trainWindowList.forEach(elem => {
                    remove.push({
                        _type: 'TrainWindow',
                        code: elem.code,
                        _dispose: true
                    });
                });
                this.$emit('updateMapModel', remove);
            }

            if (collection && collection.length) {
                collection.forEach(elem => {
                    if (elem.type !== '03' && !elem.isSwitchSection && (
                        elem.logicSectionNum.length == 0 || elem.logicSectionNum.length == 1 && elem.logicSectionNum[0] == 0)) {
                        const triangle = new JTriangle(elem.points[0], elem.points[elem.points.length - 1]);
                        models.push(this.createModel({
                            triangle: triangle,
                            section: elem
                        }));
                    } else if (elem.type === '03' && elem.isSwitchSection) {
                        models.push(this.createModel({
                            section: elem
                        }));
                    }
                });
            }

            this.$emit('updateMapModel', models);
        },
        // 修改对象
        edit() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    const data = Object.assign({_type: 'TrainWindow'}, this.editModel);
                    this.$emit('updateMapModel', data);
                }
            });
        },
        // 删除对象
        deleteObj() {
            const selected = this.$store.getters['map/getDeviceByCode'](this.editModel.code);
            if (selected && selected._type.toUpperCase() === 'TrainWindow'.toUpperCase()) {
                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>
