<template>
  <el-dialog v-dialogDrag :title="$t('map.routePreview')" :visible.sync="show" width="95%" :before-do-close="doClose">
    <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>
</template>

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

export default {
    name: 'RouteDetail',
    components: {
        PreViewField,
        ProtectDetail
    },
    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')
                    },
                    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'
                    },
                    {
                        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.startingSignalName'),
                        prop: 'startSignalCode'
                    },
                    {
                        title: this.$t('map.endingSignalName'),
                        prop: 'endSignalCode'
                    },
                    // {
                    //     title: '延续保护',
                    //     prop: 'overlapCode'
                    // },
                    {
                        type: 'button',
                        title: '延续保护',
                        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
                            }
                        ]
                    },
                    // {
                    //     type: 'button',
                    //     title: this.$t('map.routeProtectsData'),
                    //     buttons: [
                    //         {
                    //             name: this.$t('map.preview'),
                    //             handleClick: this.routeOverlap
                    //         }
                    //     ]
                    // },

                    {
                        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
                            }
                        ]
                    },
                    {
                        type: 'button',
                        title: this.$t('map.hostileApproachData'),
                        buttons: [
                            {
                                name: this.$t('map.relation'),
                                handleClick: this.conflictingRouteSection
                            }
                        ]
                    },
                    {
                        type: 'button',
                        title: this.$t('map.operation'),
                        width: '200',
                        buttons: [
                            {
                                name: this.$t('map.compile'),
                                handleClick: this.edit,
                                showControl: () => { return this.showType !== 'select'; }
                            },
                            {
                                name: this.$t('map.deleteObj'),
                                handleClick: this.deleteObj,
                                type: 'danger',
                                showControl: () => { return this.showType !== 'select'; }
                            },
                            {
                                name: '选择',
                                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].uniqueName, 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++) {
                    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', 'uniqueName', ['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: '进路延续保护区段数据',
                    name: row.name,
                    model: {
                        items: [
                            { prop: 'sectionCode', label: '物理区段ID', type: 'text' },
                            { prop: 'sectionCode', label: '物理区段名称', 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: '进路物理区段数据',
                    name: row.name,
                    model: {
                        items: [
                            { prop: 'sectionCode', label: '物理区段ID', type: 'text' },
                            { prop: 'sectionCode', label: '物理区段名称', 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: '进路侧防道',
                    name: row.name,
                    model: {
                        items: [
                            { prop: 'switchCode', label: '道岔ID', type: 'text' },
                            { prop: 'switchCode', label: '道岔名称', type: 'select', options: switchDict },
                            { prop: 'switchType', label: '道岔类型', type: 'text'}
                        ]
                    }
                };
                row.routeFlankProtectionList.forEach( item => {
                    item.switchType = item.normal ? '定位' : '反位';
                });
                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: '进路道岔数据',
                    name: row.name,
                    model: {
                        field: 'routeSwitchList',
                        items: [
                            { prop: 'switchCode', label: '道岔ID', type: 'text' },
                            { prop: 'switchCode', label: '道岔名称', type: 'select', options: switchDict },
                            { prop: 'switchType', label: '道岔类型', type: 'text'}
                        ]
                    }
                };
                row.routeSwitchList.forEach( item => {
                    item.switchType = item.normal ? '定位' : '反位';
                });
                this.$refs.previewField.doShow(fieldList, row.routeSwitchList);
            }
        },
        async conflictingRouteSection(index, row) { // 敌对进路列表
            if (this.$refs && this.$refs.previewField && row) {
                const sectionDict = {};
                this.sectionList.map(elem => { sectionDict[elem.code] = elem.name; });
                const conflictingRouteList = row.conflictingRouteList.map(elem => { return {sectionCode : elem}; });
                const fieldList = {
                    id: row.id,
                    mapId: this.$route.params.mapId,
                    title: '敌对进路数据',
                    name: row.name,
                    model: {
                        items: [
                            { prop: 'sectionCode', label: '物理区段ID', type: 'text' },
                            { prop: 'sectionCode', label: '物理区段名称', type: 'select', options: sectionDict }
                        ]
                    }
                };
                this.$refs.previewField.doShow(fieldList, conflictingRouteList);
            }
        },
        // 保存
        saveRelated(row) {
            putRouteNew(row).then(response => {
                this.$message.success('更新成功');
            }).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();
                    });
                }
            });
        },
        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;
        }
    }
};
</script>
