<template>
    <div class="DeviceInfo">
        <el-row :gutter="20">
            <el-col :span="2">
                <span style="line-height:32px;">工具栏:</span>
            </el-col>
            <el-col :span="4">
                <el-cascader
                    :options="deviceTypeTree"
                    :props="{ checkStrictly: true, children: 'childs', label: 'nodeName' ,value:'id'}"
                    v-model="formData.categoryId"
                    @change="cascaderChange"
                    clearable
                    placeholder="请选择要查看的类型"
                >
                    <template slot-scope="{ node, data }">
                        <span>{{ data.nodeName }}</span>
                        <!-- <span v-if="!node.isLeaf">({{ data.childs.length }})</span> -->
                    </template>
                </el-cascader>
            </el-col>
            <el-col :span="8">
                <el-button @click="add" type="primary" icon="el-icon-document-add">新增</el-button>
            </el-col>
        </el-row>
        <hr style="border-top: 2px solid #eee;margin: 10px 0;" />
        <el-row>
            <el-table :data="deviceList.content" empty-text="请在上面选择要查看的类型">
                <el-table-column prop="id" label="序号" width="120px"></el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
                <el-table-column prop="deviceNo" label="设备序列号"></el-table-column>
                <el-table-column prop="status" label="设备状态"></el-table-column>
                <el-table-column prop="description" label="描述"></el-table-column>
                <el-table-column label="最后一次">
                    <template slot-scope="scope">
                        <span>{{ new Date(scope.row.updated).toLocaleDateString() }}</span>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="mount(scope.row)" type="text" size="small">挂载</el-button>
                        <el-button @click="look(scope.row)" type="text" size="small">查看</el-button>
                        <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                        <el-popconfirm title="是否删除此设备的信息？" @onConfirm="del(scope.row)">
                            <el-button slot="reference" type="text" size="small">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-row type="flex" justify="end">
                <el-col :span="8" class="pagination">
                    <el-pagination
                        @current-change="pageChange"
                        background
                        layout="prev, pager, next"
                        :page-count="deviceList.totalPages"
                    ></el-pagination>
                </el-col>
            </el-row>
        </el-row>

        <!-- 设备信息新建、编辑 -->
        <el-dialog :title="isAdd?'新增设备信息':'编辑设备信息'" :visible.sync="isShowDialog" append-to-body>
            <el-form :model="formData" ref="addDeviceForm" :rules="rules" label-width="120px">
                <el-form-item label="名称：" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入名称"></el-input>
                </el-form-item>

                <el-form-item label="设备序列号：" prop="deviceNo">
                    <el-input v-model="formData.deviceNo" placeholder="设备序列号"></el-input>
                </el-form-item>

                <el-form-item label="配置信息：">
                    <el-input
                        v-model="formData.meta"
                        placeholder="请输入JSON格式的配置信息"
                        type="textarea"
                        :rows="3"
                        :autosize="{ minRows: 4 }"
                    ></el-input>
                </el-form-item>

                <el-form-item label="状态：">
                    <el-select v-model="formData.status" placeholder="请选择">
                        <el-option label="链接中" :value="0"></el-option>
                        <el-option label="链接中" :value="1"></el-option>
                        <el-option label="链接中" :value="2"></el-option>
                        <el-option label="链接中" :value="3"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="描述：">
                    <el-input
                        type="textarea"
                        :rows="2"
                        v-model="formData.description"
                        placeholder="输入描述"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="isShowDialog=false">取 消</el-button>
                <el-button type="primary" @click="submitForm('addDeviceForm')">保 存</el-button>
            </div>
        </el-dialog>

        <!-- 设备挂载dialog -->
        <el-dialog title="设备挂载" :visible.sync="show" append-to-body>
            <mountForm _ref="mountForm" @cancel="show=false" :rowData="rowData"/>
        </el-dialog>
        
    </div>
</template>

<script>
import { mapActions } from "vuex";

import mountForm from "@/components/mountForm/mountForm";

// 新增设备 表单验证规则
const rules = {
    name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
    deviceNo: [{ required: true, message: "请输入设备序列号", trigger: "blur" }]
};

// 设备树 code
const deviceTypeCode = "device-type";

// 每页数据条数
const pageSize = 10;

const formDataInit = {
    name: "",
    categoryId: null,
    deviceNo: "",
    meta: "",
    status: "",
    description: ""
};
// 设备挂载formData 初始化
const mountformInit = {
    id: null,
    areaId: null,
    areaName: null,
    meta: null
};

export default {
    name: "DeviceInfo",
    data() {
        return {
            show: false,
            rowData: {},
            id: "",
            deviceTypeTree: [],
            deviceList: [],
            isShowDialog: false,
            formData: formDataInit,
            configItems: 2, // 配置项的通道配置项数
            isAdd: true,
            rules,
            pageSize,
            page: 1
        };
    },
    components:{
        mountForm
    },
    created() {
        // 获取设备信息 树
        this.getTreeByCode(deviceTypeCode);
        // this.getTreeByCode(arearCode);

        if (this.formData.categoryId) {
            let categoryId = this.formData.categoryId;
            let data = {
                categoryId: categoryId[categoryId.length - 1],
                pageSize,
                page: this.page
            };
            this.getDeviceList(data);
        }
    },
    methods: {
        ...mapActions(["fetch"]),
        // 表格 的 挂载
        mount(row) {
            this.rowData = row
            this.show = true
        },

        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.save();
                } else {
                    return false;
                }
            });
        },
        // 通过code获取树
        getTreeByCode(code) {
            this.fetch({
                api: "/publics/treenode/getTreeByCode",
                method: "POST",
                data: { code }, //目前只有一个组织,其他参数调整钟
                success: res => {
                    this.id = res.id;
                    this.getDeviceTree(res.id);
                    
                },
                fail: err => {
                    console.log(err);
                    if (err.errCode == "request_not_authorize") {
                        this.$message({
                            message: "请重新登录",
                            type: "warning"
                        });
                    }
                }
            });
        },
        // 获取设备列表 page pageSize
        getDeviceList(data) {
            this.fetch({
                api: "/device/device/list",
                method: "POST",
                data,
                success: res => {
                    this.deviceList = res;
                },
                fail: err => {
                    if (err.errCode == "request_not_authorize") {
                        this.$message({
                            message: "请重新登录",
                            type: "warning"
                        });
                    }
                    console.log(err);
                }
            });
        },

        // 请求 拿到设备树
        getDeviceTree(parentId) {
            this.fetch({
                api: "/publics/treenode/listNodeByParent",
                method: "POST",
                data: {
                    parentId,
                    hasSub: true
                },
                success: res => {
                    this.deviceTypeTree = res;
                },
                fail: err => {
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },

        look(row) {
            this.$router.push({
                path: "deviceHumiture",
                query: row
            });
        },

        
        // 新增的保存按钮
        save() {
            if (this.formData.meta instanceof Object) {
                this.formData.meta = JSON.stringify(this.formData.meta);
            }
            let categoryId = this.formData.categoryId;
            if (categoryId instanceof Array && categoryId.length >= 0) {
                this.formData.categoryId = categoryId[categoryId.length - 1];
            }
            let api = this.isAdd
                ? "/device/device/add"
                : "/device/device/update";
            this.fetch({
                api,
                data: this.formData,
                success: res => {
                    let categoryId = this.formData.categoryId;
                    if (categoryId instanceof Object) {
                        categoryId = categoryId[categoryId.length - 1];
                    }
                    let data = {
                        categoryId,
                        pageSize,
                        page: this.page
                    };
                    this.getDeviceList(data); //重新加载
                    // this.isShowDialog = false;
                    this.$message.success(
                        this.isAdd ? "添加设备数据成功！" : "修改设备数据成功！"
                    );
                    this.isShowDialog = false;
                },
                fail: err => {
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        // 请求删除
        reqDelete(id) {
            this.fetch({
                api: "/device/delete",
                data: { id },
                success: res => {
                    let categoryId = this.formData.categoryId;
                    if (categoryId instanceof Object) {
                        categoryId = categoryId[categoryId.length - 1];
                    }
                    let data = {
                        categoryId,
                        pageSize,
                        page: this.page
                    };
                    this.getDeviceList(data); //重新加载
                },
                fail: err => {
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        add() {
            // 没选中设备类型 就 return
            if (!this.formData.categoryId) {
                this.$message.warning("请选择要为某个类型添加设备！");
                return;
            }
            this.isAdd = true;
            if (this.formData.id) delete this.formData.id;
            this.isShowDialog = true;
        },
        // header级联选择器选中 时
        cascaderChange(value) {
            console.log(value);
            let data = {
                categoryId: value[value.length - 1],
                pageSize,
                page: this.page
            };
            this.getDeviceList(data);
        },
        // 编辑
        edit(row) {
            this.isAdd = false;
            this.isShowDialog = true;
            this.formData = row;
            if (this.formData.meta instanceof Object) {
                this.formData.meta = JSON.stringify(row.meta, null, 2);
            }
        },
        // 删除
        del(row) {
            this.reqDelete(row.id);
        },
        pageChange(p) {
            console.log(p);
            this.page = p;
            let categoryId = this.formData.categoryId;
            if (categoryId instanceof Object) {
                categoryId = categoryId[categoryId.length - 1];
            }
            let data = {
                categoryId,
                pageSize,
                page: p
            };
            this.getDeviceList(data);
        }
    }
};
</script>

<style lang="scss" scoped>
.DeviceInfo {
    .dialog {
        .item_row {
            display: flex;
        }
    }
}

.pagination {
    margin-top: 20px;
}
</style>