<template>
  <div>
    <el-drawer
      title="设备管理"
      :visible.sync="show"
      direction="ltr"
      :before-close="doClose"
      custom-class="dialog_box"
      size="43%"
    >
      <div style="margin-bottom: 3px; overflow: hidden; padding: 0 10px;">
        <div class="plc_box">名称: {{ plcInfo.name }}</div>
        <div class="plc_box">状态: <span :style="{'color': plcInfo.status ? 'green' : 'red'}">{{ plcInfo.status ? '在线' : '不在线' }}</span></div>
        <el-button type="text" size="small" class="freshen_box" @click="getList">刷新</el-button>
      </div>
      <el-table :data="tableData" border style="width: 100%; max-height: calc(100% - 24px); overflow: auto;">
        <el-table-column prop="code" label="设备编号" width="180" />
        <el-table-column prop="typeName" label="设备类型" width="180" />
        <el-table-column prop="vrDeviceCode" label="连接设备编码">
          <template slot-scope="scope">
            <div v-if="scope.row.vrDeviceCode" class="flex_box">{{ scope.row.vrDeviceName }}</div>
            <div v-if="!scope.row.vrDeviceCode" class="flex_box">(空)</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button :type="scope.row.buttonShowType ? 'danger' : 'primary'" size="small" @click="handleClick(scope.row, scope.$index)">连接</el-button>
            <el-button size="small" @click="cancel(scope.row, scope.$index)">断开</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import { getAllSimulationList, postSimulationConnectById, putSimulationDisconnectById } from '@/api/simulation.js';
import ConstConfig from '@/scripts/ConstConfig';
import { EventBus } from '@/scripts/event-bus';
import { getSessionStorage } from '@/utils/auth';

export default {
    name: 'Equipment',
    data() {
        return {
            show: false,
            group: '',
            tableData: [],
            typeList: ConstConfig.ConstSelect.projectDeviceTypeList,
            plcInfo: {
                name: '',
                status: ''
            },
            index: 0,
            selected: {},
            typeObj: {
                Section: '区段',
                Signal: '信号机',
                Switch: '道岔',
                Psd: '屏蔽门',
                StationStand: '站台'
            }
        };
    },
    computed: {
        project() {
            return getSessionStorage('project');
        }
    },
    mounted() {
        EventBus.$on('selectDevice', (data) => {
            this.selected = data;
            this.tableData[this.index]['buttonShowType'] = false;
            this.tableData.splice(this.index, 1, this.tableData[this.index]);
            this.$store.dispatch('map/selectDeviceCode', {flag: false, type: ''});
            this.connect(this.tableData[this.index]);
        });
    },
    async beforeDestroy() {
        EventBus.$off('selectDevice');
    },
    methods: {
        async doShow() {
            this.show = true;
            this.group = this.$route.query.group;
            this.getList();
        },
        async getList() {
            try {
                const res = await getAllSimulationList(this.group);
                this.tableData = [];
                res.data.forEach((item, index) => {
                    if (item.type == 'PLC_GATEWAY') {
                        this.plcInfo = {
                            name: 'PLC网关',
                            status: item.online
                        };
                    } else {
                        item.buttonShowType = false;
                        item.typeName = this.typeList.find(el => el.value == item.type).label;
                        if (item.vrDeviceCode && this.$store.getters['map/getDeviceByCode'](item.vrDeviceCode)) {
                            item.vrDeviceName = this.$store.getters['map/getDeviceByCode'](item.vrDeviceCode).name;
                        } else {
                            item.vrDeviceName = item.vrDeviceCode;
                        }
                        if (this.project == 'heb' || this.project == 'designheb') {
                            if (item.type == 'SWITCH') {
                                this.tableData.push(item);
                            }
                        } else {
                            this.tableData.push(item);
                        }
                    }
                });
            } catch (error) {
                console.error(error);
            }
        },
        doClose() {
            this.show = false;
        },
        handleClick(row, index) {
            row.buttonShowType = !row.buttonShowType;
            this.index = index;
            this.tableData.splice(index, 1, row);
            this.$store.dispatch('map/selectDeviceCode', {flag: row.buttonShowType, type: row.type});
        },
        async connect(row) {
            this.$confirm(`您确定连接${this.typeObj[this.selected._type] || '设备'}: ${this.selected.name}, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await postSimulationConnectById(this.group, row.id, this.selected.code);
                    if (res && res.code == 200) {
                        this.$message.success('连接成功!');
                        this.tableData[this.index]['vrDeviceCode'] = this.selected.code;
                        this.tableData[this.index]['vrDeviceName'] = this.selected.name;
                        this.tableData.splice(this.index, 1, this.tableData[this.index]);
                    }
                } catch (error) {
                    console.error(error);
                }
            });
        },
        async cancel(row, index) {
            this.$confirm('您确定将次设备断开, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                if (row.vrDeviceCode) {
                    row.vrDeviceCode = '';
                    row.vrDeviceName = '';
                    this.tableData.splice(index, 1, row);
                    try {
                        const res = await putSimulationDisconnectById(this.group, row.id);
                        if (res && res.code == 200) {
                            this.$message.success('断开成功!');
                        }
                    } catch (error) {
                        console.error(error);
                    }
                }
            });
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.plc_box{
		float: left;
		margin-right: 40px;
		padding: 9px;
	}
	.freshen_box{
		float: right;
	}
	.flex_box{
		float: left;
		margin-right: 5px;
		line-height: 30px;
	}
	/deep/ {
		.el-dialog__wrapper{
			width: 800px;
		}
		.dialog_box{
			height: 100%;
		}
		.el-dialog__body{
			padding-top: 6px;
			height: calc(100% - 54px);
		}
	}
</style>
