<template>
  <div v-show="show">
    <el-dialog v-dialogDrag :title="$t('map.routePreview')" :visible.sync="show" width="95%" :before-do-close="doClose" append-to-body>
      <div>
        <QueryListPage
          ref="queryListPage"
          :pager-config="pagerConfig"
          :query-form="queryForm"
          :query-list="queryList"
        />
      </div>
      <pre-view-field ref="previewField" :map-info="mapInfo" />
      <protect-detail ref="protectDetail" :map-info="mapInfo" />
    </el-dialog>
    <related ref="related" :map-info="mapInfo" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { listMap, getRouteNewList, delRouteNew, getRouteNewById, putRouteNew, getContinueProtectList, delContinueProtect } from '@/api/jmap/mapdraft';
import ProtectDetail from './protectDetail';
import PreViewField from './preview';
import Related from './related';

export default {
    name: 'RouteDetail',
    components: {
        PreViewField,
        ProtectDetail,
        Related
    },
    props: {
        mapInfo: {
            type: Object,
            default() {
                return null;
            }
        }
    },
    data() {
        return {
            show: false,
            showType: '',
            codeType: '',
            mapList: [],
            RouteNatureTypeList: [],
            RouteAutoTypeList: [],
            SwitchLocateTypeList: [],
            ContinueProtectList: [],
            turnBackList: [
                { label: '是', value: true },
                { label: '否', value: false }
            ],
            pagerConfig: {
                pageSize: 'pageSize',
                pageIndex: 'pageNum'
            },
            queryForm: {
                labelWidth: '120px',
                queryObject: {
                    name: {
                        type: 'text',
                        label: this.$t('map.pathName')
                    },
                    code: {
                        type: 'text',
                        label: '进路code'
                    },
                    stationCode: {
                        type: 'select',
                        label: this.$t('map.routeStationName'),
                        config: {
                            data: []
                        }
                    },
                    startSignalCode: {
                        type: 'select',
                        label: this.$t('map.startingSignalName'),
                        config: {
                            data: []
                        }
                    },
                    endSignalCode: {
                        type: 'select',
                        label: this.$t('map.endingSignalName'),
                        config: {
                            data: []
                        }
                    }
                }
            },
            queryList: {
                query: this.queryFunction,
                afterQuery: this.afterQuery,
                selectCheckShow: false,
                indexShow: true,
                columns: [
                    {
                        title: this.$t('map.pathName'),
                        prop: 'name',
                        width: 180
                    },
                    {
                        title: this.$t('map.code'),
                        prop: 'code',
                        width: 150
                    },
                    {
                        title: this.$t('map.routeStationName'),
                        prop: 'stationCode'
                    },
                    {
                        title: this.$t('map.accessType'),
                        prop: 'turnBack',
                        type: 'tag',
                        columnValue: (row) => { return this.$convertField(row.turnBack, this.turnBackList, ['value', 'label']); },
                        tagType: (row) => { return ''; }

                    },
                    {
                        title: this.$t('map.whetherAutoRoute'),
                        prop: 'flt',
                        type: 'tag',
                        columnValue: (row) => { return this.$convertField(row.flt, this.turnBackList, ['value', 'label']); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        title: this.$t('map.startingSignalName'),
                        prop: 'startSignalCode'
                    },
                    {
                        title: this.$t('map.endingSignalName'),
                        prop: 'endSignalCode'
                    },
                    {
                        type: 'button',
                        title: this.$t('map.continueProtect'),
                        buttons: [
                            {
                                name: this.$t('map.preview'),
                                handleClick: this.overlapSwitchDetail,
                                showControl: (row) => { return row.overlapCode; }
                            }
                        ]
                    },
                    {
                        type: 'button',
                        title: this.$t('map.accessSideTurnoutData'),
                        buttons: [
                            {
                                name: this.$t('map.preview'),
                                handleClick: this.flankProtectionSwitchDetail,
                                showControl: (row) => { return row.routeFlankProtectionList.length > 0; }
                            }
                        ]
                    },
                    {
                        type: 'button',
                        title: this.$t('map.physicalSection'), // 物理区段list
                        buttons: [
                            {
                                name: this.$t('map.preview'),
                                handleClick: this.sectionDetail
                            }
                        ]
                    },
                    {
                        type: 'button',
                        title: this.$t('map.routeRouteTurnoutData'),
                        buttons: [
                            {
                                name: this.$t('map.preview'),
                                handleClick: this.routeSwitchDetail,
                                showControl: (row) => { return row.routeSwitchList.length > 0; }
                            }
                        ]
                    },
                    {
                        title: this.$t('map.hostileData'),
                        prop: 'conflictingSignalList',
                        type: 'tagMore',
                        width: '250',
                        columnValue: (row) => { return this.showConflictingSignalList(row.conflictingSignalList); },
                        tagType: (row) => { return ''; }
                    },
                    {
                        type: 'button',
                        title: this.$t('map.operation'),
                        width: '250',
                        buttons: [
                            {
                                name: this.$t('map.compile'),
                                handleClick: this.edit,
                                showControl: () => { return this.showType !== 'select'; }
                            },
                            {
                                name: '复制',
                                handleClick: this.copyObj,
                                type: 'warning',
                                showControl: () => { return this.showType !== 'select'; }
                            },
                            {
                                name: this.$t('map.deleteObj'),
                                handleClick: this.deleteObj,
                                type: 'danger',
                                showControl: () => { return this.showType !== 'select'; }
                            },
                            {
                                name: this.$t('global.select'),
                                handleClick: this.selectedObj,
                                showControl: () => { return this.showType === 'select'; }
                            }
                        ]
                    }
                ]
            }
        };
    },
    computed: {
        ...mapGetters('map', [
            'signalList',
            'switchList',
            'sectionList',
            'stationList',
            'stationStandList'
        ])
    },
    watch: {
        signalList: function (val, old) {
            const list = [];
            if (val && val.length) {
                for (let i = 0; i < val.length; i++) {
                    list.push({ label: `${val[i].name}(${val[i].code})`, value: val[i].code });
                }
                this.queryForm.queryObject.startSignalCode.config.data = list;
                this.queryForm.queryObject.endSignalCode.config.data = list;
            }
        },
        stationList: function (val, old) {
            const list = [];
            if (val && val.length) {
                for (let i = 0; i < val.length; i++) {
                    if (val[i].centralized) {
                        list.push({ label: val[i].name, value: val[i].code });
                    }
                }
                this.queryForm.queryObject.stationCode.config.data = list;
            }
        }
    },
    mounted() {
        this.$Dictionary.routeNatureType().then(list => {
            this.RouteNatureTypeList = list;
        });

        this.$Dictionary.routeAutoType().then(list => {
            this.RouteAutoTypeList = list;
        });

        this.$Dictionary.switchLocateType().then(list => {
            this.SwitchLocateTypeList = list;
        });
        this.acquireMapList();
    },
    methods: {
        doShow(showType, codeType) {
            this.show = true;
            this.reloadTable();
            if (showType && codeType) {
                this.showType = showType;
                this.codeType = codeType;
            }
        },
        doClose() {
            this.show = false;
        },
        queryFunction(params) {
            if (this.mapInfo && this.mapInfo.id) {
                return getRouteNewList(this.mapInfo.id, params);
            }
        },
        acquireMapList() {
            listMap({ drawWay:true}).then(response => {
                this.mapList = response.data;
            });
        },
        afterQuery(data) {
            if (data && data.list) {
                const that = this;
                const list = data.list;
                if (list) {
                    list.map(elem => {
                        that.$convertSpecifiedField(elem, that.RouteAutoTypeList, 'code', 'name', ['autoType']);
                        that.$convertSpecifiedField(elem, that.RouteNatureTypeList, 'code', 'name', ['natureType']);
                        that.$convertSpecifiedField(elem, that.SwitchLocateTypeList, 'code', 'name', ['overlapSwitchLocateType']);
                        that.$convertSpecifiedField(elem, that.mapList, 'id', 'name', ['mapId']);
                        that.$convertSpecifiedField(elem, that.switchList, 'code', 'name', ['routeOverlapSwitchList']);
                        that.$convertSpecifiedField(elem, that.signalList, 'code', 'name', ['startSignalCode', 'endSignalCode']);
                        that.$convertSpecifiedField(elem, that.stationList, 'code', 'name', ['stationCode']);
                        that.$convertSpecifiedField(elem, that.sectionList, 'code', 'name', ['nearSectionCode', 'autoTriggerSectionCode', 'turnBackSectionCode']);
                    });
                }
            }
            return data;
        },
        async routeOverlap(index, row) { // 延续保护区段数据列表
            if (this.$refs && this.$refs.previewField && row) {
                const sectionDict = {};
                this.sectionList.map(elem => { sectionDict[elem.code] = elem.name; });
                const routeOverlapSectionList = row.routeOverlapSectionList.map(elem => { return {sectionCode : elem}; });
                const fieldList = {
                    id: row.id,
                    mapId: this.$route.params.mapId,
                    title: this.$t('map.routeContinuesToProtectSectorData'),
                    name: row.name,
                    model: {
                        items: [
                            { prop: 'sectionCode', label: this.$t('map.physicalSectionID'), type: 'text' },
                            { prop: 'sectionCode', label: this.$t('map.physicalSectionName'), type: 'select', options: sectionDict }
                        ]
                    }
                };
                this.$refs.previewField.doShow(fieldList, routeOverlapSectionList);
            }
        },
        async sectionDetail(index, row) { // 进路物理区段
            if (this.$refs && this.$refs.previewField && row) {
                const sectionDict = {};
                this.sectionList.map(elem => { sectionDict[elem.code] = elem.name; });
                const routeSectionList = row.routeSectionList.map(elem => { return {sectionCode : elem}; });
                const fieldList = {
                    id: row.id,
                    mapId: this.$route.params.mapId,
                    title: this.$t('map.routePhysicalSectionData'),
                    name: row.name,
                    model: {
                        items: [
                            { prop: 'sectionCode', label: this.$t('map.physicalSectionID'), type: 'text' },
                            { prop: 'sectionCode', label: this.$t('map.physicalSectionName'), type: 'select', options: sectionDict }
                        ]
                    }
                };
                this.$refs.previewField.doShow(fieldList, routeSectionList);
            }
        },
        async overlapSwitchDetail(index, row) { // 延续保护道岔
            if (this.$refs && this.$refs.protectDetail && row) {
                const param = {
                    code: row.overlapCode,
                    pageNum: 10,
                    pageSize:1
                };
                getContinueProtectList(this.$route.params.mapId, param).then(resp => {
                    this.$refs.protectDetail.doShow(resp.data.list[0]);
                }).catch((error) => {
                    console.log(error);
                });
            }
        },
        async flankProtectionSwitchDetail(index, row) { // 进路侧防道岔
            if (this.$refs && this.$refs.previewField && row) {
                const switchDict = {};
                this.switchList.map(elem => { switchDict[elem.code] = elem.name; });
                const fieldList = {
                    id: row.id,
                    mapId: this.$route.params.mapId,
                    title: this.$t('map.routeSideDefenseSwitch'),
                    name: row.name,
                    model: {
                        items: [
                            { prop: 'switchCode', label: this.$t('map.switchID'), type: 'text' },
                            { prop: 'switchCode', label: this.$t('map.switchName'), type: 'select', options: switchDict },
                            { prop: 'switchType', label: this.$t('map.switchType'), type: 'text'}
                        ]
                    }
                };
                row.routeFlankProtectionList.forEach( item => {
                    item.switchType = item.normal ? this.$t('map.normalPosition') : this.$t('map.reversePosition');
                });
                this.$refs.previewField.doShow(fieldList, row.routeFlankProtectionList);
            }
        },
        async routeSwitchDetail(index, row) { // 道岔段数据列表
            if (this.$refs && this.$refs.previewField && row) {
                const switchDict = {};
                this.switchList.map(elem => { switchDict[elem.code] = elem.name; });
                const fieldList = {
                    id: row.id,
                    mapId: this.$route.params.mapId,
                    title: this.$t('map.entryTurnout'),
                    name: row.name,
                    model: {
                        field: 'routeSwitchList',
                        items: [
                            { prop: 'switchCode', label: this.$t('map.switchID'), type: 'text' },
                            { prop: 'switchCode', label: this.$t('map.switchName'), type: 'select', options: switchDict },
                            { prop: 'switchType', label: this.$t('map.switchType'), type: 'text'}
                        ]
                    }
                };
                row.routeSwitchList.forEach( item => {
                    item.switchType = item.normal ? this.$t('map.normalPosition') : this.$t('map.reversePosition');
                });
                this.$refs.previewField.doShow(fieldList, row.routeSwitchList);
            }
        },
        // 保存
        saveRelated(row) {
            putRouteNew(row).then(response => {
                this.$message.success(this.$t('tip.updateSuccessfully'));
            }).catch(() => {
                this.$messageBox('操作异常');
            });
        },
        edit(index, row) {
            this.mapList.forEach(elem => {
                if (elem.name === row.mapId) {
                    const model = {
                        mapId: elem.id,
                        id: row.id
                    };
                    getRouteNewById(model.id).then(response => {
                        const data = response.data;
                        this.$emit('routeSelected', data);
                        this.doClose();
                    });
                }
            });
        },
        copyObj(index, row) {
            this.mapList.forEach(elem => {
                if (elem.name === row.mapId) {
                    const model = {
                        mapId: elem.id,
                        id: row.id
                    };
                    getRouteNewById(model.id).then(response => {
                        const data = response.data;
                        delete data.id;
                        this.$emit('routeSelected', data);
                        this.doClose();
                    });
                }
            });
        },
        deleteObj(index, row) {
            if (row) {
                this.$confirm('是否确认删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delRouteNew(row.id).then(response => {
                        const param = {
                            code: row.overlapCode,
                            pageNum: 10,
                            pageSize:1
                        };
                        getContinueProtectList(this.$route.params.mapId, param).then(resp => {
                            if (resp.data.list[0]) {
                                delContinueProtect(resp.data.list[0].id).then( res => {
                                    this.$message.success('删除成功');
                                });
                            }
                        });
                        this.reloadTable();
                    }).catch(() => {
                        this.$messageBox('删除失败');
                    });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            }
        },
        reloadTable() {
            if (this.queryList && this.queryList.reload) {
                this.queryList.reload();
            }
        },
        selectedObj(index, row) {
            this.$emit('setRouteCode', row, this.codeType);
            this.show = false;
        },
        showConflictingSignalList(data) {
            const nameList = [];
            data.forEach(ele => {
                let signalName = '';
                this.signalList.some(item => {
                    if (item.code === ele.signalCode) {
                        signalName = item.name;
                        return true;
                    }
                });
                let switchName = '';
                ele.switchPositionList.forEach((item, index) => {
                    this.switchList.some(it => {
                        if (it.code === item.switchCode) {
                            const pos = item.normal ? 'N' : 'R';
                            if (index === 0) {
                                switchName = switchName + it.name + pos;
                            } else {
                                switchName = switchName + '/' + it.name + pos;
                            }
                            return true;
                        }
                    });
                });
                if (switchName) {
                    nameList.push(signalName + ' ' + 'WITH' + ' ' + switchName);
                } else {
                    nameList.push(signalName);
                }
            });
            return nameList;
        }
    }
};
</script>
