<template>
    <el-drawer size="65%" :modal-append-to-body="false" :destroy-on-close="true" :before-close="closeDialog"
        v-model="visible" title="设备管理">
        <el-card class="top-title">
            <span>通讯名称：{{ formData.driver_name }}</span>
            <span>设备数量：{{ propertiesData.length }}</span>
        </el-card>
        <div class="top-btn">
            <el-button type="primary" size="large" @click="manageData">
                新增设备
            </el-button>
            <div>
                <el-button type="primary" @click="importData"> 导入 </el-button>
                <el-button type="primary" @click="exportData"> 导出 </el-button>
            </div>
        </div>
        <el-table :data="propertiesData" height="640" style="width: 100%" border stripe
            :header-cell-style="{ background: '#F6F7FC' }">
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="device_name" label="设备名称" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="slave_id" label="设备ID" align="center" show-overflow-tooltip>
            </el-table-column>

            <el-table-column prop="device_description" label="设备描述" align="center" show-overflow-tooltip>

            </el-table-column>
            <el-table-column label="操作" align="center" width="180" show-overflow-tooltip>
                <template #default="scope">
                    <el-button size="large" @click="editData(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" size="large" @click="delData(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <AddSet :type="type" :formData="formData1" :setData="setData" :dialogVisible="dialogVisible1" v-if="dialogVisible1"
            @dialogClose="dialogVisible1 = false" @dialogSuccess="dialogSuccess1">
        </AddSet>
        <ExportDevice :formData="formData1" :dialogVisible="dialogVisible2" v-if="dialogVisible2"
            @dialogClose="dialogVisible2 = false" @dialogSuccess="dialogSuccess2"></ExportDevice>
    </el-drawer>
</template>
<script>
import axios from "axios";
import { onMounted, reactive, ref, toRefs, computed, nextTick } from "vue";
import infoApi from "@/api/infoApi.js";
import { ElMessage, ElMessageBox } from "element-plus";
import AddSet from "@/components/AddSet.vue";
import ExportDevice from "@/components/ExportDevice.vue";
export default {
    components: {
        AddSet,
        ExportDevice
    },
    props: ["formData", "dialogVisible", "qudongOptions"],
    emits: ["dialogClose", "dialogSuccess"],
    setup(props, ctx) {
        const state = reactive({
            propertiesData: [],
            formData1: {},
            setData: {},
            dialogVisible1: false,
            type: 'I',
            driverInfo: {},
            dialogVisible2:false
        });
        const visible = computed(() => {
            return props.dialogVisible;
        });

        onMounted(() => {
            getSet();
        });

        const getSet = async () => {
            state.propertiesData = [];
            const parm = {
                driver_name: props.formData.driver_name
            }
            const res = await infoApi.getSet(parm);
            if (res.code == 0) {
                state.driverInfo = res.data;
                let devices = res.data.devices
                if (devices) {
                    for (let key in devices) {
                        if (devices.hasOwnProperty(key)) {
                            state.propertiesData.push(devices[key]);
                        }
                    }
                    state.propertiesData = state.propertiesData.sort((a, b) => {
                        return (a.device_name > b.device_name ? 1 : -1)
                    });
                }
            } else {
                ElMessage.error(res.data || res.message || "请求失败");
            }
        };
        const closeDialog = () => {
            ctx.emit("dialogClose");
        };

        const delData = (item) => {
            ElMessageBox.confirm("确定删除该数据?", "删除设备", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    let param = {
                        driver_name: props.formData.driver_name,
                        device_name: item.device_name
                    }
                    const res = await infoApi.delSet(param);
                    if (res.code == 0) {
                        ElMessage.success(res.data || res.message || "删除成功");
                        getSet();
                    } else {
                        ElMessage.error(res.data || res.message || "请求失败");
                    }
                })
                .catch(() => {
                    ElMessage.info("已取消删除");
                });
        }

        const manageData = () => {
            state.dialogVisible1 = true;
            state.formData1 = props.formData;
            state.type = 'I';
            state.setData = {
                device_name: '',
                slave_id: 1,
                device_description: ''
            }
        }

        const editData = (item) => {
            state.dialogVisible1 = true;
            state.formData1 = props.formData;
            state.type = 'U';
            state.setData = JSON.parse(JSON.stringify(item));
        }

        const dialogSuccess1 = () => {
            state.dialogVisible1 = false;
            getSet();
        };

        const dialogSuccess2 = () => {
            state.dialogVisible2 = false;
            getSet();
        }

        const importData = () => {
            state.formData1 = props.formData;
            state.dialogVisible2 = true;
        }

        const exportData = () => {
            axios({
                method: "post",
                url: '/driver',
                headers: {
                    "action": 54211,
                    'driver_name': props.formData.driver_name
                },
                responseType: 'blob',
            }).then((response) => {
                let fileName = response.headers['content-disposition'].split('filename=')[1];
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `${decodeURI(fileName.split('"')[1])}`);
                document.body.appendChild(link);
                link.click();
            }).catch();
        }


        return {
            ...toRefs(state),
            visible,
            closeDialog,
            delData,
            manageData,
            dialogSuccess1,
            importData,
            exportData,
            editData,
            dialogSuccess2
        };
    },
};
</script>
<style lang="scss" scoped>
.top-title {
    width: 100%;

    ::v-deep .el-card__body {
        width: 100%;
        display: flex;
        justify-content: space-between;
        font-weight: 800;
        font-size: 16px;
    }
}

.top-btn {
    width: 100%;
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
}

.btns {
    padding: 15px 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
}

.flex-center {
    display: flex;
    justify-content: center;
    padding: 10px 0;
    cursor: pointer;
}
</style>
  