<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 class="flex_box">
        <el-button type="primary" @click="create">{{ $t('map.createSwitch') }}</el-button>
        <!-- <el-button type="" @click="questionList = []">{{ $t('map.clearHint') }}</el-button> -->
      </div>
      <div style="height: calc(100% - 46px);">
        <!-- <el-scrollbar wrap-class="scrollbar-wrapper">
          <el-card v-if="questionList.length" class="box-card">
            <div v-for="(item, index) in questionList" :key="index" class="text item">{{ item }}</div>
          </el-card>
        </el-scrollbar> -->
      </div>
    </el-tab-pane>
    <el-tab-pane class="view-control" label="生成道岔计轴区段" name="three">
      <div style="height: 100%;">
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <el-form ref="oprt1" :model="fromData" label-width="130px" size="mini" :rules="mergeRules">
            <el-form-item label="关联区段" prop="relevanceSectionList">
              <el-select v-model="fromData.relevanceSectionList" filterable multiple :placeholder="$t('rules.pleaseSelect')">
                <el-option
                  v-for="item in sectionList"
                  :key="item.code"
                  :label="item.name + '(' + item.code + ')'"
                  :value="item.code"
                />
              </el-select>
              <el-button :type="field === 'relevanceSectionList' ? 'danger' : 'primary'" size="small" @click="hover('relevanceSectionList')">{{ $t('map.activate') }}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button type="primary" size="big" @click="createSwitchSectionManual">生成道岔计轴区段</el-button>
              </el-button-group>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { mapGetters } from 'vuex';
import { getUID } from '@/jmap/utils/Uid';
import ConfigList from './config/list';
import { deepAssign } from '@/utils/index';

export default {
    name: 'SwitchDraft',
    components: {
        ConfigList
    },
    props: {
        selected: {
            type: Object,
            default: function () {
                return null;
            }
        }
    },
    data() {
        return {
            activeName: 'first',
            // questionList: [],
            editModel: {
                code: '',
                name: '',
                turnTime: 0,
                nameShow: false,
                namePosition: { x: 0, y: 0 },
                stationCode: '',
                timeoutShow: false,
                sectionACode: '',
                sectionBCode: '',
                sectionCCode: '',
                tp: { x: 0, y: 0 }
            },
            field: '',
            fromData: {
                relevanceSectionList: []
            }
        };
    },
    computed: {
        form() {
            const form = {
                labelWidth: '170px',
                items: {
                    code: {
                        name: '',
                        item: []
                    },
                    draw: {
                        name: this.$t('map.drawData'),
                        item: [
                            { prop: 'code', label: this.$t('map.switchCode'), type: 'select', optionLabel: 'name&&code', optionValue: 'code', options: this.switchList, change: true, deviceChange: this.deviceChange },
                            { prop: 'name', label: this.$t('map.switchName'), type: 'input' },
                            { prop: 'namePosition', label: this.$t('map.switchPosition'), type: 'coordinate', width: '160px', 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: 'tp', label: this.$t('map.switchTp'), type: 'coordinate', width: '160px', children: [
                                { prop: 'tp.x', firstLevel: 'tp', secondLevel: 'x', label: 'x:', type: 'number', labelWidth: '25px' },
                                { prop: 'tp.y', firstLevel: 'tp', 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: 'turnTime', label: this.$t('map.turnTime'), type: 'number', min: 0, max: 1000, placeholder: 's' }
                        ]
                    }
                }
            };
            return form;
        },
        rules() {
            const rules = {
                code: [
                    { required: true, message: this.$t('rules.selectEquipment'), trigger: 'change' }
                ],
                name: [
                    { required: true, message: this.$t('rules.switchName'), trigger: 'blur' }
                ],
                'namePosition.x': [
                    { required: true, message: this.$t('rules.switchNamePointX'), trigger: 'blur' }
                ],
                'namePosition.y': [
                    { required: true, message: this.$t('rules.switchNamePointY'), trigger: 'blur' }
                ],
                turnTime: [
                    { required: true, message: this.$t('rules.switchTurnTime'), trigger: 'blur' }
                ],
                'tp.x': [
                    { required: true, message: this.$t('rules.switchTpX'), trigger: 'blur' }
                ],
                'tp.y': [
                    { required: true, message: this.$t('rules.switchTpY'), trigger: 'blur' }
                ]
            };
            // 清空表单验证提示信息
            this.$nextTick(() => {
                this.$refs.dataform &&
				this.$refs.dataform.clearValidate();
            });

            return rules;
        },
        ...mapGetters('map', [
            'linkList',
            'sectionList',
            'switchList',
            'stationList',
            'lineCode'
        ])
        // switchSectionList() {
        //     let list = [];
        //     if (this.sectionList && this.sectionList.length) {
        //         list = this.sectionList.filter(elem => { return elem.type === '03'; });
        //     }
        //     return list;
        // }
    },
    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 (this.field.toUpperCase() != 'relevanceSectionList'.toUpperCase() && selected && selected._type.toUpperCase() === 'Switch'.toUpperCase()) {
                this.$refs.dataform.resetFields();
                this.activeName = 'first';
                this.editModel = deepAssign(this.editModel, selected);
            } else if (selected && selected._type.toUpperCase() === 'Section'.toUpperCase() && this.field.toUpperCase() === 'relevanceSectionList'.toUpperCase()) {
                this.fromData.relevanceSectionList.push(selected.code);
            }
        },
        hover(field) {
            this.field = field == this.field ? '' : field;
            this.$emit('fieldSelectSwitchSection', this.field);
        },
        findSectionA(pointX, pointY) {
            const list = [];
            this.sectionList.forEach(item => {
                if (item.points[0].x == pointX && item.points[0].y == pointY) {
                    list.push(item);
                }
            });
            return list;
        },
        findSectionB(pointX, pointY) {
            const list = [];
            this.sectionList.forEach(item => {
                if (item.points[item.points.length - 1].x == pointX && item.points[item.points.length - 1].y == pointY) {
                    list.push(item);
                }
            });
            return list;
        },
        checkAddListA(points, code) { // 判断是否添加list
            let flag = false;
            this.sectionList.forEach(section => {
                section.points.forEach((point, index) => {
                    if (index > 0 && section.code != code) {
                        if (point.x == points.x && point.y == points.y) {
                            flag = true;
                        }
                    }
                });

            });
            return flag;
        },
        checkAddListB(points, code) { // 判断是否添加list
            let flag = false;
            this.sectionList.forEach(section => {
                section.points.forEach((point, index) => {
                    if (index == 0 && section.code != code) {
                        if (point.x == points.x && point.y == points.y) {
                            flag = true;
                        }
                    }
                });

            });
            return flag;
        },
        changeSectionAttr() { // 修改区段属性
            const changeSectionList = []; // 改变的区段列表
            this.sectionList.forEach(section => {
                const oneSection = section.points[section.points.length - 1];
                const oneSectionStar = section.points[0];
                let countA = 0;
                let countB = 0;
                this.sectionList.forEach(elem => {
                    const twoSection = elem.points[0];
                    const twoSectionEnd = elem.points[elem.points.length - 1];
                    if (oneSection.x == twoSection.x && oneSection.y == twoSection.y) {
                        countA++;
                        if (countA >= 2) {
                            if (!this.checkAddListA(oneSection, section.code)) { // 右侧关系清空
                                const sectionModel = deepAssign({}, section);
                                sectionModel.rightSectionCode = '';
                                sectionModel.type = '03';
                                const list = this.findSectionA(sectionModel.points[sectionModel.points.length - 1].x, sectionModel.points[sectionModel.points.length - 1].y);
                                list.forEach(elem => {
                                    const sectionModel = deepAssign({}, elem);
                                    sectionModel.leftSectionCode = '';
                                    sectionModel.type = '03';
                                    changeSectionList.push(sectionModel);
                                });
                                changeSectionList.push(sectionModel);
                            }
                        }
                    } else if (oneSectionStar.x == twoSectionEnd.x && oneSectionStar.y == twoSectionEnd.y) {
                        countB++;
                        if (countB >= 2) {
                            if (!this.checkAddListB(oneSectionStar, section.code)) { // 左侧关系清空
                                const sectionModel = deepAssign({}, section);
                                sectionModel.leftSectionCode = '';
                                sectionModel.type = '03';
                                const list = this.findSectionB(sectionModel.points[0].x, sectionModel.points[0].y);
                                list.forEach(elem => {
                                    const sectionModel = deepAssign({}, elem);
                                    sectionModel.rightSectionCode = '';
                                    sectionModel.type = '03';
                                    changeSectionList.push(sectionModel);
                                });
                                changeSectionList.push(sectionModel);
                            }
                        }
                    }
                });
            });
            return changeSectionList;
        },
        create() { // 一键生成道岔
            // this.questionList = []; // 有问题区段列表
            const createArr = []; // 创建model列表
            // const models = []; // 道岔列表
            const changeSectionList = this.changeSectionAttr();
            changeSectionList.forEach(section => {
                if (!section.rightSectionCode) { // 右侧关联关系为空 且 道岔区段
                    const list = this.findSectionA(section.points[section.points.length - 1].x, section.points[section.points.length - 1].y);
                    let sectionB = {};
                    let sectionC = {};
                    if (list.length >= 2) {
                        list.forEach(item => {
                            if (item.points[1].y == section.points[section.points.length - 1].y) { // 是否水平拿第二个点判断
                                sectionB = item;
                            } else {
                                sectionC = item;
                            }
                        });
                        if (section.code && sectionB.code && sectionC.code) {
                            const uname = 'switch_' + section.name.replace('section_', '');
                            const model = {
                                _type: 'Switch',
                                code: getUID('Switch'),
                                name: uname,
                                nameShow: true,
                                timeoutShow: true,
                                sectionACode: section.code,
                                sectionBCode: sectionB.code,
                                sectionCCode: sectionC.code,
                                namePosition: { x: 0, y: 0 },
                                turnTime: 3,
                                tp: { x: 0, y: 0 },
                                intersection: {
                                    x: section.points[section.points.length - 1].x,
                                    y: section.points[section.points.length - 1].y
                                },
                                skew: {
                                    x: sectionC.points[1].x,
                                    y: sectionC.points[1].y
                                }
                            };
                            const swch = this.findSwitchData(model.sectionACode, model.sectionBCode, model.sectionCCode);
                            !swch && createArr.push(model); // 已有的道岔不在创建
                        }
                    }
                }
                if (!section.leftSectionCode) { // 左侧关联关系为空 且 道岔区段
                    const list = this.findSectionB(section.points[0].x, section.points[0].y);
                    let sectionB = {};
                    let sectionC = {};
                    if (list.length >= 2) {
                        list.forEach(item => {
                            if (item.points[item.points.length - 2].y == section.points[0].y) { // 是否水平拿倒数第二个点判断
                                sectionB = item;
                            } else {
                                sectionC = item;
                            }
                        });
                        if (section.code && sectionB.code && sectionC.code) {
                            const uname = 'switch_' + section.name.replace('section_', '');
                            const model = {
                                _type: 'Switch',
                                code: getUID('Switch'),
                                name: uname,
                                nameShow: true,
                                timeoutShow: true,
                                sectionACode: section.code,
                                sectionBCode: sectionB.code,
                                sectionCCode: sectionC.code,
                                namePosition: { x: 0, y: 0 },
                                turnTime: 3,
                                tp: { x: 0, y: 0 },
                                intersection: {
                                    x: section.points[0].x,
                                    y: section.points[0].y
                                },
                                skew: {
                                    x: sectionC.points[sectionC.points.length - 2].x,
                                    y: sectionC.points[sectionC.points.length - 2].y
                                }
                            };
                            const swch = this.findSwitchData(model.sectionACode, model.sectionBCode, model.sectionCCode);
                            !swch && createArr.push(model); // 已有的道岔不在创建
                        }
                    }
                }
            });
            this.$confirm(this.$t('tip.confirmBatchGeneration'), this.$t('tip.hint'), {
                confirmButtonText: this.$t('tip.confirm'),
                cancelButtonText: this.$t('tip.cancel'),
                type: 'warning'
            }).then((res) => {
                const modelsList = this.createSwitchSection(createArr, changeSectionList);
                modelsList.forEach(item => {
                    createArr.push(item);
                });
                this.$emit('updateMapModel', createArr);
            }).catch((error) => {
                console.log(error, '错误信息');
                this.$message( this.$t('tip.cancelGeneration'));
            });
        },
        // 修改对象
        edit() {
            this.$refs['dataform'].validate((valid) => {
                if (valid) {
                    const data = Object.assign({_type: 'Switch'}, this.editModel);
                    this.$emit('updateMapModel', data);
                } else {
                    this.$message('还有属性未填写，修改未生效！');
                }
            });
        },
        // 删除对象
        deleteObj() {
            const models = [];
            const selected = this.$store.getters['map/getDeviceByCode'](this.editModel.code);
            if (selected && selected._type.toUpperCase() === 'Switch'.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(() => {
                    models.push(deepAssign(selected, { _dispose: true }));
                    _that.$emit('updateMapModel', models);
                    _that.deviceSelect();
                }).catch(() => {
                    _that.$message.info(this.$t('tip.cancelGeneration'));
                });
            }
        },
        findSectionDataByLinkCodeAndPoint(code, point) {
            var rtn = null;
            var sectionList = this.sectionList;
            if (sectionList && sectionList.length) {
                for (var i = 0; i < sectionList.length; ++i) {
                    if (code === sectionList[i].linkCode && point) {
                        if (JSON.stringify(sectionList[i].points[0]) === JSON.stringify(point) ||
                                JSON.stringify(sectionList[i].points[sectionList[i].points.length - 1]) === JSON.stringify(point)) {
                            rtn = sectionList[i];
                            break;
                        }
                    }
                }
            }
            return rtn;
        },
        findSwitchData(sectionACode, sectionBCode, sectionCCode) {
            var rtn = null;
            var switchList = this.switchList;
            if (switchList && switchList.length) {
                for (var i = 0; i < switchList.length; ++i) {
                    if (sectionACode === switchList[i].sectionACode &&
                            sectionBCode === switchList[i].sectionBCode &&
                            sectionCCode === switchList[i].sectionCCode) {
                        rtn = switchList[i];
                        break;
                    }
                }
            }
            return rtn;
        },
        findSectionData(sectionList, code) {
            var rtn = null;
            if (sectionList && sectionList.length) {
                for (var i = 0; i < sectionList.length; ++i) {
                    if (code === sectionList[i].code) {
                        rtn = sectionList[i];
                        break;
                    }
                }
            }
            return rtn;
        },
        checkCoverSwitch(checkSwitchList, code) {
            let flag = true;
            checkSwitchList.forEach(elem => {
                if (elem.code == code) {
                    flag = false;
                }
            });
            return flag;
        },
        // 一键生成道岔计轴区段
        createSwitchSection(list, sectionLists) {
            const models = [];
            const switchList = [...this.switchList, ...list];
            if (list && list.length && sectionLists && sectionLists.length) {
                const sectionList = [];
                list.forEach(elem => {
                    const sectionb = this.findSectionData(sectionLists, elem.sectionBCode);
                    const sectiona = this.findSectionData(sectionLists, elem.sectionACode);
                    const sectionc = this.findSectionData(sectionLists, elem.sectionCCode);
                    const parentSectionModel = this.$store.getters['map/getDeviceByCode'](sectiona.parentCode);
                    if (!parentSectionModel) { // 找不到父元素删除
                        let uid;
                        if (!elem['uid']) {
                            uid = getUID('Section');
                            elem['uid'] = uid;
                        }
                        sectiona.parentCode = elem['uid'];
                        sectionb.parentCode = elem['uid'];
                        sectionc.parentCode = elem['uid'];
                        elem['relevanceSectionList'] = elem['relevanceSectionList'] || [elem.sectionACode, elem.sectionBCode, elem.sectionCCode];
                        sectionList.push(elem);
                        switchList.forEach(ele => {
                            const sectiona1 = this.findSectionData(sectionLists, ele.sectionACode);
                            const sectionc1 = this.findSectionData(sectionLists, ele.sectionCCode);
                            const sectionb1 = this.findSectionData(sectionLists, ele.sectionBCode);
                            if (sectionb1.points[sectionb1.points.length - 1].x == sectionb.points[0].x && sectionb1.points[sectionb1.points.length - 1].y == sectionb.points[0].y) {
                                ele['uid'] = uid;
                                elem['relevanceSectionList'] = [elem.sectionACode, elem.sectionBCode, elem.sectionCCode, ele.sectionACode, ele.sectionBCode, ele.sectionCCode];
                                sectiona1.parentCode = uid;
                                sectionb1.parentCode = uid;
                                sectionc1.parentCode = uid;
                                sectionList.forEach((item, index) => {
                                    if (item.code == elem.code) {
                                        sectionList.splice(index, 1);
                                    }
                                });
                            }
                            if (sectiona1.points[sectiona1.points.length - 1].x == sectiona.points[0].x && sectiona1.points[sectiona1.points.length - 1].y == sectiona.points[0].y) {
                                elem['relevanceSectionList'] = [elem.sectionACode, elem.sectionBCode, elem.sectionCCode, ele.sectionACode, ele.sectionBCode, ele.sectionCCode];
                                sectiona1.parentCode = uid;
                                sectionb1.parentCode = uid;
                                sectionc1.parentCode = uid;
                                sectionList.forEach((item, index) => {
                                    if (item.code == elem.code) {
                                        sectionList.splice(index, 1);
                                    }
                                });
                            }
                        });
                    } else {
                        parentSectionModel.relevanceSectionList.push(elem.sectionACode);
                        parentSectionModel.relevanceSectionList.push(elem.sectionBCode);
                        parentSectionModel.relevanceSectionList.push(elem.sectionCCode);
                        models.push(parentSectionModel);
                    }
                    sectiona.relSwitchCode = elem.code;
                    sectionb.relSwitchCode = elem.code;
                    sectionc.relSwitchCode = elem.code;
                    sectiona.isSwitchSection = true;
                    sectionb.isSwitchSection = true;
                    sectionc.isSwitchSection = true;
                    models.push(sectiona);
                    models.push(sectionb);
                    models.push(sectionc);
                });
                sectionList.forEach(elem => {
                    const sectiona = this.findSectionData(sectionLists, elem.sectionACode);
                    const sectionb = this.findSectionData(sectionLists, elem.sectionBCode);
                    const sectionc = this.findSectionData(sectionLists, elem.sectionCCode);
                    if (sectiona && sectionb && sectionc) {
                        let point = {
                            x: sectiona.points[sectiona.points.length - 1].x,
                            y: sectiona.points[sectiona.points.length - 1].y
                        };
                        if (JSON.stringify(sectiona.points[0]) === JSON.stringify(sectionb.points[sectionb.points.length - 1])) {
                            point = { x: sectiona.points[0].x, y: sectiona.points[0].y };
                        }
                        models.push({
                            _type: 'Section',
                            code: elem.uid,
                            name: sectiona.name,
                            type: '04',
                            axleShow: false,
                            namePosition: point,
                            isStandTrack: false,
                            kmRangeRight: '',
                            kmRangeLeft: '',
                            region: '',
                            standTrackName: '',
                            standTrackNamePosition: { x: 0, y: 0 },
                            isReentryTrack: false,
                            reentryTrackName: '',
                            reentryTrackNamePosition: { x: 0, y: 0 },
                            isTransferTrack: false,
                            transferTrackName: '',
                            transferTrackNamePosition: { x: 0, y: 0 },
                            isSegmentation: false,
                            segmentationPosition: { x: 0, y: 0 },
                            isSwitchSection: true,
                            relSwitchCode: '',
                            relevanceSectionList: elem.relevanceSectionList,
                            points: [{ x: 0, y: 0 }, { x: 0, y: 0 }],
                            logicSectionNum: [0],
                            logicSectionShow: false,
                            sepTypeLeft: '00',
                            offsetLeft: 0,
                            sepTypeRight: '00',
                            offsetRight: 0,
                            parentCode: '',
                            stationCode: sectiona.stationCode,
                            trainPosType: sectiona.trainPosType,
                            isCurve: false
                        });
                    }
                });
            }
            return models;
        },
        createSwitchSectionManual() {
            const models = [];
            const uid = getUID('Section');
            this.fromData.relevanceSectionList.forEach(item => {
                const section = deepAssign({}, this.$store.getters['map/getDeviceByCode'](item));
                section.parentCode = uid;
                models.push(section);
            });
            const sectionCode = this.fromData.relevanceSectionList[0];
            const sectiona = deepAssign({}, this.$store.getters['map/getDeviceByCode'](sectionCode));
            models.push({
                _type: 'Section',
                code: uid,
                name: uid,
                type: '04',
                axleShow: false,
                namePosition: {
                    x: sectiona.points[sectiona.points.length - 1].x,
                    y: sectiona.points[sectiona.points.length - 1].y
                },
                isStandTrack: false,
                kmRangeRight: '',
                kmRangeLeft: '',
                region: '',
                standTrackName: '',
                standTrackNamePosition: { x: 0, y: 0 },
                isReentryTrack: false,
                reentryTrackName: '',
                reentryTrackNamePosition: { x: 0, y: 0 },
                isTransferTrack: false,
                transferTrackName: '',
                transferTrackNamePosition: { x: 0, y: 0 },
                isSegmentation: false,
                segmentationPosition: { x: 0, y: 0 },
                isSwitchSection: true,
                relSwitchCode: '',
                relevanceSectionList: this.fromData.relevanceSectionList,
                points: [{ x: 0, y: 0 }, { x: 0, y: 0 }],
                logicSectionNum: [0],
                logicSectionShow: false,
                sepTypeLeft: '00',
                offsetLeft: 0,
                sepTypeRight: '00',
                offsetRight: 0,
                parentCode: '',
                stationCode: sectiona.stationCode,
                trainPosType: sectiona.trainPosType,
                isCurve: false
            });
            this.$emit('updateMapModel', models);
            this.fromData.relevanceSectionList = [];
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";
	.flex_box{
		display: flex;
		justify-content: center;
	}

	.box-card {
		width: calc(100% - 80px);
		margin: 20px auto 0;
		padding: 0 20px;
		.text {
			font-size: 14px;
		}

		.item {
			padding: 6px 0;
		}
	}

	.view-control{
		height: 100%;
	}

	.card {
		height: 100%;
	}

</style>
