<template>
    <div class="default-main">
        <TableHeader>
            <template v-slot:select>
                <el-form-item label="设备类型">
                    <!-- <el-input v-model="tableStore.table.params.searchValue" placeholder="请输入设备类型" /> -->
                    <el-select
                        v-model="tableStore.table.params.devType"
                        clearable
                        @change="devTypeChange"
                        placeholder="请选择设备类型"
                    >
                        <el-option
                            v-for="item in devTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备型号">
                    <el-select v-model="tableStore.table.params.devModel" clearable placeholder="请选择设备型号">
                        <el-option
                            v-for="item in devModelOptionsFilter"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="通讯协议">
                    <el-select v-model="tableStore.table.params.devAccessMethod" clearable placeholder="请选择通讯协议">
                        <el-option label="MQTT" value="mqtt"></el-option>
                        <el-option label="CLD" value="cloud"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="tableStore.table.params.status" clearable placeholder="请选择状态">
                        <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>
            </template>
            <template v-slot:operation>
                <el-button type="primary" @click="downLoadFile" class="ml10" icon="el-icon-Download">
                    模版下载
                </el-button>
                <el-upload
                    style="display: inline-block"
                    action=""
                    accept=".xlsx"
                    class="upload-demo"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="bulkImport"
                >
                    <el-button type="primary" class="ml10" icon="el-icon-Tickets">批量导入</el-button>
                </el-upload>
                <el-button type="primary" class="ml10" @click="add" icon="el-icon-Plus">新增设备</el-button>
            </template>
        </TableHeader>
        <Table ref="tableRef">
            <template v-slot:columns>
                <vxe-column field="name" title="设备名称"></vxe-column>
                <vxe-column field="devType" title="设备类型">
                    <template #default="{ row }">
                        {{
                            devTypeOptions.filter((item: any) => item.value == row.devType)[0] &&
                            devTypeOptions.filter((item: any) => item.value == row.devType)[0].label
                        }}
                    </template>
                </vxe-column>
                <vxe-column field="devModel" title="设备型号">
                    <template #default="{ row }">
                        {{
                            devModelOptions.filter((item: any) => item.value == row.devModel)[0] &&
                            devModelOptions.filter((item: any) => item.value == row.devModel)[0].label
                        }}
                    </template>
                </vxe-column>
                <vxe-column field="devAccessMethod" title="通讯协议">
                    <template #default="{ row }">
                        {{
                            row.devAccessMethod === 'MQTT'
                                ? 'MQTT'
                                : row.devAccessMethod === 'cloud'
                                ? 'CLD'
                                : row.devAccessMethod
                        }}
                    </template>
                </vxe-column>
                <vxe-column field="createTime" title="录入时间"></vxe-column>
                <vxe-column field="createTime" title="网络设备ID"></vxe-column>
                <vxe-column field="status" title="状态">
                    <template #default="{ row }">
                        {{ row.status == 1 ? '未注册' : row.status == 2 ? '注册' : '接入' }}
                    </template>
                </vxe-column>
                <vxe-column title="操作" min-width="340">
                    <template #default="{ row }">
                        <!-- <div class="table-operation"> -->
                        <el-button size="small" type="primary" @click="edit(row)" icon="el-icon-Edit">编辑</el-button>
                        <el-button size="small" type="primary" @click="qrCode(row)" icon="el-icon-Grid">
                            二维码
                        </el-button>
                        <el-button size="small" type="primary" @click="reset(row.ndid)" icon="el-icon-Setting">
                            出厂恢复
                        </el-button>
                        <el-button size="small" type="danger" @click="deletes(row.id)" icon="el-icon-Delete">
                            删除
                        </el-button>

                        <!-- </div> -->
                    </template>
                </vxe-column>
            </template>
        </Table>

        <el-dialog
            :title="dialogTitle"
            v-model="dialogFormVisible"
            :close-on-click-modal="false"
            width="600px"
            :before-close="resetForm"
        >
            <el-form :model="form" label-width="120px" :rules="rules" ref="ruleFormRef">
                <el-form-item label="设备名称:" prop="name">
                    <el-input
                        v-model="form.name"
                        autocomplete="off"
                        clearable
                        placeholder="请输入（项目名称+设备名称）"
                    ></el-input>
                </el-form-item>
                <el-form-item label="网络设备ID:" prop="ndid" class="top">
                    <el-input v-model="form.ndid" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="设备类型:" prop="devType" class="top">
                    <el-select
                        v-model="form.devType"
                        placeholder="请选择"
                        style="width: 100%"
                        @change="formDevTypeChange"
                        clearable
                    >
                        <el-option
                            v-for="item in devTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="设备型号:" prop="devModel" class="top">
                    <el-select v-model="form.devModel" placeholder="请选择" style="width: 100%" clearable>
                        <el-option
                            v-for="item in formDevModelOptionsFilter"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="通讯协议:" prop="devAccessMethod" class="top">
                    <el-select v-model="form.devAccessMethod" placeholder="请选择" style="width: 100%" clearable>
                        <el-option label="MQTT" value="MQTT"></el-option>
                        <el-option label="CLD" value="cloud"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="合同号:" prop="cntractNo" class="top">
                    <el-input v-model="form.cntractNo" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="resetForm">取 消</el-button>
                <el-button type="primary" @click="onSubmit">确 定</el-button>
            </template>
        </el-dialog>

        <div class="qrcode-label">
            <div class="qrcode-label-title">{{ deivce.mac }}</div>
            <img class="qrcode-label-img" alt="二维码加载失败" :src="deivce.qrPath" />
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, computed, reactive } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { queryByCode, queryByid, queryCsDictTree } from '@/api/system-boot/dictTree'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    addEquipmentDelivery,
    deleteEquipmentDelivery,
    editEquipmentDelivery,
    uploadTopo,
    batchImportDevice,
    resetEquipmentDelivery
} from '@/api/cs-system-boot/device'
import html2canvas from 'html2canvas'
defineOptions({
    name: 'govern/log/debug'
})

const devTypeOptions: any = ref([])
const deivce: any = ref({})
const ruleFormRef = ref()
const form = reactive({
    cntractNo: '',
    devAccessMethod: 'mqtt',
    devModel: '',
    devType: '',
    name: '',
    ndid: ''
})
const rules = reactive({
    name: [{ required: true, message: '设备名不能为空', trigger: 'blur' }],
    ndid: [{ required: true, message: '网络设备id不能为空', trigger: 'blur' }],
    devType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
    devModel: [{ required: true, message: '设备型号不能为空', trigger: 'change' }],
    devAccessMethod: [{ required: true, message: '接入方式不能为空', trigger: 'blur' }],
    cntractNo: [{ required: true, message: '合同号不能为空', trigger: 'blur' }]
})
const dialogFormVisible = ref(false)
const dialogTitle = ref('新增设备')

const devModelOptions: any = ref([])
const devModelOptionsFilter = computed(() => {
    return devModelOptions.value.filter((item: any) => {
        if (tableStore.table.params.devType) {
            return item.pid == tableStore.table.params.devType
        } else {
            return true
        }
    })
})
const formDevModelOptionsFilter = computed(() => {
    return devModelOptions.value.filter((item: any) => {
        if (form.devType) {
            return item.pid == form.devType
        } else {
            return true
        }
    })
})

const tableStore = new TableStore({
    url: '/cs-device-boot/EquipmentDelivery/list',
    method: 'POST',
    column: [],
    beforeSearchFun: () => {
        for (let key in tableStore.table.params) {
            if (tableStore.table.params[key] === '') {
                delete tableStore.table.params[key]
            }
        }
    }
})
tableStore.table.params.orderBy = 'desc'
queryByCode('Device_Type').then(res => {
    queryCsDictTree(res.data.id).then(res => {
        devTypeOptions.value = res.data.map((item: any) => {
            return {
                value: item.id,
                label: item.name,
                ...item
            }
        })
    })
    queryByid(res.data.id).then(res => {
        devModelOptions.value = res.data.map((item: any) => {
            return {
                value: item.id,
                label: item.name,
                ...item
            }
        })
    })
})
// 设备类型
const devTypeChange = (e: any) => {
    if (!e) {
        return
    }
    tableStore.table.params.devModel = ''
}
// 下载模版
const downLoadFile = () => {
    window.open(window.location.origin + '/api/cs-device-boot/EquipmentDelivery/getExcelTemplate')
}

// 导入模版
const bulkImport = (e: any) => {
    batchImportDevice(e.raw).then((res: any) => {
        if (res.type === 'application/json') {
            const reader = new FileReader()
            reader.readAsText(res)
            reader.onload = (e: any) => {
                let data = JSON.parse(e.target.result)
                console.log('🚀 ~ batchImportDevice ~ data:', data)
                if (data.code === 'A0000') {
                    ElMessage.success(data.message)
                    tableStore.onTableAction('search', {})
                } else {
                    ElMessage.error(data.message)
                }
            }
        } else {
            ElMessage.error('导入失败!')
            let url = window.URL.createObjectURL(res)
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '导入失败.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        }
    })
}
// 新增
const add = () => {
    dialogFormVisible.value = true
    dialogTitle.value = '新增设备'
}
// 编辑
const edit = (row: any) => {
    dialogFormVisible.value = true
    dialogTitle.value = '编辑设备'
    for (let key in form) {
        form[key] = row[key]
    }
    form.id = row.id
}
// 确认
const onSubmit = () => {
    ruleFormRef.value.validate((valid: any) => {
        if (valid) {
            if (dialogTitle.value == '新增设备') {
                addEquipmentDelivery(form).then(res => {
                    ElMessage.success('新增成功')
                    resetForm()
                    tableStore.onTableAction('search', {})
                })
            } else {
                editEquipmentDelivery(form).then(res => {
                    ElMessage.success('修改成功')
                    resetForm()
                    tableStore.onTableAction('search', {})
                })
            }
        }
    })
}
// 清空表格
const resetForm = () => {
    ruleFormRef.value.resetFields()
    dialogFormVisible.value = false
}
// 二维码
const qrCode = (item: any) => {
    deivce.value = item
    deivce.value.qrPath = localStorage.getItem('STATIC_URL') + deivce.value.qrPath
    setTimeout(() => {
        html2canvas(document.querySelector('.qrcode-label'), {
            useCORS: true
        }).then(canvas => {
            let url = canvas.toDataURL('image/png')
            // 下载图片
            let a = document.createElement('a')
            let event = new MouseEvent('click')
            a.href = url
            a.download = item.mac + '.png'
            a.dispatchEvent(event)
        })
    }, 0)
}
// 出厂设置
const reset = (id: string) => {
    ElMessageBox.confirm('确定该设备恢复出厂吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        resetEquipmentDelivery(id).then(res => {
            ElMessage.success('恢复成功!')
            tableStore.onTableAction('search', {})
        })
    })
}
// 删除
const deletes = (id: string) => {
    ElMessageBox.confirm('确定删除该设备吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteEquipmentDelivery(id).then(res => {
            ElMessage.success('删除成功!')
            tableStore.onTableAction('search', {})
        })
    })
}

const formDevTypeChange = (e: any) => {
    console.log(e)
    if (!e) {
        return
    }
    form.devModel = ''
}
provide('tableStore', tableStore)

onMounted(() => {
    tableStore.index()
})

const addMenu = () => {}
</script>
<style lang="scss" scoped>
.qrcode-label {
    position: absolute;
    top: 0;
    right: 0;
    z-index: -99;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 180px;
    height: 180px;
    padding: 10px;
    background: #fff;
    flex-direction: column;

    .qrcode-label-title {
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: bold;
    }

    .qrcode-label-img {
        width: 140px;
        height: 140px;
    }
}
</style>
