<template>
    <div class="app-container" v-if="!isShow">
        <el-form
            :model="queryForm"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="68px"
            v-show="showSearch"
        >
            <el-form-item label="关键字" prop="keyWord">
                <el-input
                    v-model="queryForm.keyWord"
                    clearable
                    placeholder="请输入关键字"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="small" @click="handleQuery"
                    >搜索</el-button
                >
                <el-button type="primary" size="small" @click="addIOT"
                    >添加设备</el-button
                >
                <!-- <el-button type="primary" size="small" @click="downloadQRCord"
                    >下载二维码</el-button
                > -->
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <right-toolbar
                :showSearch.sync="showSearch"
                @queryTable="getList"
            ></right-toolbar>
        </el-row>

        <el-table
            :data="tableData"
            style="width: 100%"
            border
            @selection-change="selectionChange"
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
                type="index"
                label="序号"
                align="center"
                width="55"
                :index="
                    indexContinuation(queryParams.pageNum, queryParams.pageSize)
                "
            />
            <el-table-column
                label="设备类型"
                prop="iotTypeName"
                align="center"
            />
            <el-table-column label="设备编号" prop="iotCode" align="center" />
            <el-table-column label="设备状态" prop="iotStatus" align="center">
                <template v-slot="{ row }">
                    <el-tag size="mini" v-if="row.iotStatus == 0" type="success"
                        >在线</el-tag
                    >
                    <el-tag size="mini" v-else type="danger">离线</el-tag>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="prCode" label="二维码" align="center">
                <template v-slot="{ row }">
                    <el-button type="text" size="small" @click="showQrCode(row)"
                        >查看</el-button
                    >
                </template>
            </el-table-column> -->
            <el-table-column label="状态" align="center">
                <template v-slot="{ row }">
                    <el-tag
                        v-if="row.bindStatus == 0"
                        type="success"
                        size="mini"
                        >已绑定</el-tag
                    >
                    <el-tag v-else type="warning" size="mini">未绑定</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template v-slot="{ row }">
                    <el-button
                        type="text"
                        size="small"
                        @click="handleCheck(row)"
                        icon="el-icon-view"
                        >记录</el-button
                    >
                    <el-button
                        type="text"
                        size="small"
                        @click="handleEdit(row)"
                        icon="el-icon-edit-outline"
                        v-if="row.bindStatus == 1"
                        >修改</el-button
                    >
                    <el-button
                        type="text"
                        size="small"
                        style="color: red"
                        @click="handleDelete(row)"
                        v-if="row.bindStatus == 1"
                        icon="el-icon-delete"
                    >
                        删除
                    </el-button>
                    <el-button
                        type="text"
                        size="small"
                        style="color: red"
                        @click="handleUnbind(row)"
                        v-if="row.bindStatus == 0"
                        icon="el-icon-connection"
                    >
                        解绑
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 二维码弹框 -->
        <el-dialog
            title="查看二维码"
            :visible.sync="uploadOpen"
            width="500px"
            append-to-body
        >
            <div style="text-align: center">
                <div class="qrCodeImg">
                    <div id="qrcode" class="qrcode" ref="codeItem"></div>
                </div>
                <div class="maCode">二维码编号：{{ rowObj.qrCode }}</div>
            </div>
            <div
                slot="footer"
                class="dialog-footer"
                style="text-align: center"
            ></div>
        </el-dialog>

        <!-- 添加/修改 设备弹框 -->
        <el-dialog
            :title="title"
            :visible.sync="IOTOpen"
            width="500px"
            append-to-body
        >
            <el-form
                :model="IOTForm"
                ref="IOTForm"
                label-width="120px"
                size="small"
                :rules="rules"
            >
                <el-form-item label="设备类型: " prop="iotType">
                    <el-select
                        v-model="IOTForm.iotType"
                        filterable
                        clearable
                        placeholder="请选择设备类型"
                        style="width: 280px"
                    >
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :value="item.iotTypeId + ''"
                            :label="item.iotTypeName"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备编号: " prop="iotCode">
                    <el-input
                        v-model="IOTForm.iotCode"
                        clearable
                        placeholder="请输入设备编号"
                        style="width: 280px"
                    />
                </el-form-item>
                <!-- 修改设备状态: 使用Switch开关 -->
                <el-form-item label="设备状态: " prop="iotStatus" v-if="isEdit">
                    <el-switch
                        v-model="IOTForm.iotStatus"
                        active-text="在线"
                        inactive-text="离线"
                        :active-value="0"
                        :inactive-value="1"
                    />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="IOTOpen = false">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
    <div v-else>
        <BindDetails ref="bindDetails" :isShow="isShow" :iotId="iotId" />
    </div>
</template>

<script>
import BindDetails from './component/BindDetails'
import QRCode from 'qrcodejs2'
import {
    addOrUpdate,
    getIotList,
    deleteIotById,
    getRecordListAll,
    unbindIot,
    selectList,
} from '@/api/store/iotManagement.js'
export default {
    name: 'IOTequipment',
    components: {
        BindDetails,
    },
    data() {
        return {
            isShow: false,
            showSearch: true, // 是否显示搜索
            uploadOpen: false, // 二维码弹框
            rowObj: {},
            qrCode: '',
            qrUrl: this.globalUrl.qrUrl,
            queryForm: {
                keyWord: '',
            },
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            tableData: [],
            IOTForm: {
                iotType: '',
                iotCode: '',
                iotStatus: '',
            },
            options: [
                // {
                //     value: '125',
                //     label: '定位设备',
                // },
                // {
                //     value: '126',
                //     label: '检测设备',
                // },
            ],
            title: '',
            IOTOpen: false,
            // 校验
            rules: {
                iotType: [
                    {
                        required: true,
                        message: '请选择设备类型',
                        trigger: 'change',
                    },
                ],
                iotCode: [
                    {
                        required: true,
                        message: '请输入11位的设备编号',
                        trigger: 'blur',
                        min: 11,
                        max: 11,
                    },
                    // {
                    //     required: true,
                    //     message: '请输入设备编号',
                    //     trigger: 'blur',
                    // },
                    // {
                    //     // 限制输入字母数字 短横线(-) 下划线(_)
                    //     pattern: /^[a-zA-Z0-9_-]+$/,
                    //     message: '请输入11位的正确设备编码',
                    //     trigger: 'blur',
                    //     min: 11,
                    //     max: 11,
                    // },
                ],
            },
            isEdit: false,
            iotId: undefined,
        }
    },
    created() {
        this.getList()
    },
    methods: {
        handleQuery() {
            console.log('🚀 ~ handleQuery ~ 查询:', this.queryForm.keyWord)
            this.getList()
        },
        getList() {
            const params = {
                keyWord: this.queryForm.keyWord || '',
                pageNum: this.queryParams.pageNum,
                pageSize: this.queryParams.pageSize,
            }
            console.log('🚀 ~ getList ~ 获取列表', params)

            getIotList(params)
                .then((res) => {
                    this.tableData = res.rows
                    this.total = res.total
                })
                .catch((err) => {
                    console.log('🚀 ~ getList ~ err:', err)
                })
        },
        // 获取设备类型
        async getDeviceType() {
            try {
                const res = await selectList()
                this.options = res.data
            } catch (err) {
                console.log('🚀 ~ getIotType ~ err:', err)
            }
            // 接口()
            //   .then(res => {
            //     this.options = res.data
            //   })
            //   .catch(err => {
            //     console.log('🚀 ~ getDeviceType ~ err:', err)
            //   })
        },
        addIOT() {
            this.title = '添加设备'
            this.IOTOpen = true
            this.isEdit = false
            this.getDeviceType()
            this.$nextTick(() => {
                this.IOTForm = {
                    iotType: '',
                    iotCode: '',
                }
                this.$refs.IOTForm.resetFields()
            })
        },
        downloadQRCord() {
            this.$confirm('是否下载二维码？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                // this.$message({
                //   type: 'success',
                //   message: '下载成功',
                // })
            })
        },
        showQrCode(row) {
            console.log(row)
            if (row.qrCode == null) {
                this.$message.error('当前设备没有二维码')
                return
            }
            this.rowObj = row
            this.uploadOpen = true
            this.qrCode = row.qrCode
            let str = this.qrUrl + row.qrCode
            console.log('🚀 ~ showQrCode ~ str:', str)
            this.$nextTick(() => {
                this.$refs.codeItem.innerHTML = ''
                var qrcode = new QRCode(this.$refs.codeItem, {
                    text: str, //二维码内容
                    width: 256,
                    height: 256,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H,
                })
                // console.log('🚀 ~ showQrCode ~ qrcode:', qrcode)
            }, 500)
        },
        handleCheck(row) {
            console.log('🚀 ~ handleCheck ~ 记录:', row)
            this.isShow = true
            this.iotId = row.iotId
        },
        handleEdit(row) {
            console.log('🚀 ~ handleEdit ~ 修改:', row)
            // 修改IOT设备
            this.title = '修改设备'
            this.IOTOpen = true
            this.isEdit = true
            this.getDeviceType()
            this.$nextTick(() => {
                this.$refs.IOTForm.resetFields()
                this.IOTForm = {
                    iotId: row.iotId,
                    iotType: row.iotType,
                    iotCode: row.iotCode,
                    iotStatus: row.iotStatus,
                }
            })
        },
        handleDelete(row) {
            console.log('🚀 ~ handleDelete ~ 删除:', row)
            // 弹框提示
            this.$confirm('是否删除该设备？', '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    // 删除
                    deleteIotById(row.iotId).then((res) => {
                        // 提示
                        this.$message({
                            type: 'success',
                            message: '删除成功',
                        })
                        this.getList()
                    })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },
        handleUnbind(row) {
            try {
                const params = {
                    id: undefined,
                    iotId: row.iotId,
                    maCode: '',
                    typeId: undefined,
                }
                console.log('🚀 ~ handleUnbind ~ 解绑', row)
                this.$confirm('确定解绑设备吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(async () => {
                        let { data } = await getRecordListAll({
                            iotId: params.iotId,
                        })
                        console.log('🚀 ~ .then ~ res:', data)
                        data.forEach((item) => {
                            if (!item.unBindTime) {
                                params.maCode = item.maCode
                                params.typeId = item.typeId
                                params.id = item.id
                            }
                        })
                        console.log('🚀 ~ .then ~ maCode:', params)
                        await unbindIot(params)
                        this.$message.success('解绑成功')
                        this.getList()
                    })
                    .catch((err) => {
                        console.log('🚀 ~ handleUnbind ~ err:', err)
                        this.$message.info('已取消解绑')
                    })
            } catch (err) {
                console.log('🚀 ~ handleUnbind ~ error', err)
            }
        },
        selectionChange(val) {
            console.log('🚀 ~ selectionChange ~ val:', val)
        },
        // 确认提交
        submit() {
            this.$refs.IOTForm.validate((valid) => {
                if (valid) {
                    console.log('🚀 ~ submit ~ 确认提交', this.IOTForm)
                    let params = {}
                    if (this.isEdit) {
                        // 修改
                        params = {
                            ...this.IOTForm,
                        }
                    } else {
                        // 添加
                        params = {
                            ...this.IOTForm,
                        }
                    }
                    addOrUpdate(params)
                        .then((res) => {
                            this.IOTOpen = false
                            // 提示 isEdit ? '修改成功' : '添加成功'
                            this.$message({
                                type: 'success',
                                message: this.isEdit ? '修改成功' : '添加成功',
                            })
                            this.getList()
                        })
                        .catch((err) => {
                            console.log('🚀 ~ submit ~ err:', err)
                        })
                }
            })
        },
    },
}
</script>

<style lang="scss" scoped>
.qrCodeImg {
    display: flex;
    align-items: center;
    justify-content: center;
}
.maCode {
    margin-top: 15px;
    font-size: 18px;
}
</style>
