<template>
    <div class="default-main">
        <TableHeader>
            <template #select>
                <el-form-item label="设备类型">
                    <!-- <el-input maxlength="32" show-word-limit    v-model.trim="tableStore.table.params.searchValue" placeholder="请输入设备类型" /> -->
                    <el-select v-model.trim="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.trim="tableStore.table.params.devModel" filterable 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.trim="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.trim="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"></Table>

        <el-dialog :title="dialogTitle" v-model.trim="dialogFormVisible" :close-on-click-modal="false"
            :before-close="resetForm" draggable width="40%">
            <el-form :model="form" label-width="120px" :rules="rules" ref="ruleFormRef">
                <el-form-item label="设备名称" prop="name">
                    <el-input maxlength="32" show-word-limit v-model.trim="form.name" autocomplete="off" clearable
                        placeholder="请输入（项目名称+设备名称）"></el-input>
                </el-form-item>
                <el-form-item label="网络设备ID" prop="ndid" class="top">
                    <el-input maxlength="32" show-word-limit v-model.trim="form.ndid" autocomplete="off"
                        placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="设备类型" prop="devType" class="top">
                    <el-select v-model.trim="form.devType" placeholder="请选择" @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.trim="form.devModel" filterable placeholder="请选择" 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.trim="form.devAccessMethod" placeholder="请选择" 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 maxlength="32" show-word-limit v-model.trim="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" :loading="loading">确定</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, nextTick } 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,
    batchImportDevice,
    resetEquipmentDelivery,
    governDeviceRegister,
    portableDeviceRegister,
    portableDeviceAccess,
    getExcelTemplate
} from '@/api/cs-system-boot/device'
import html2canvas from 'html2canvas'
import { fullUrl } from '@/utils/common'

defineOptions({
    name: 'govern/log/debug'
})
const loading = ref(false)

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([])
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 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: [
        { title: '设备名称', field: 'name' },
        {
            title: '设备类型',
            field: 'devType',
            formatter: row => {
                return devTypeOptions.value.filter((item: any) => item.value == row.cellValue)[0]?.label
            }
        },
        {
            title: '设备型号',
            field: 'devModel',
            formatter: row => {
                return devModelOptions.value.filter((item: any) => item.value == row.cellValue)[0]?.label
            }
        },
        {
            title: '通讯协议',
            field: 'devAccessMethod',
            formatter: row => {
                return row.cellValue === 'MQTT' ? 'MQTT' : row.cellValue === 'cloud' ? 'CLD' : row.cellValue
            }
        },
        { title: '录入时间', field: 'createTime', sortable: true },
        { title: '网络设备ID', field: 'ndid' },
        {
            title: '状态',
            field: 'status',
            width: 100,
            render: 'tag',
            custom: {
                1: 'warning',
                2: 'success',
                3: 'primary',
                4: 'primary'
            },
            replaceValue: {
                1: '未注册',
                2: '注册',
                3: '接入',
                4: '已取消'
            }
            // formatter: row => {
            //     return row.cellValue == 1 ? '未注册' : row.cellValue == 2 ? '注册' : '接入'
            // },
        },
        {
            title: '操作', fixed: 'right',
            align: 'center',
            width: '180',
            render: 'buttons',
            buttons: [
                {
                    name: 'edit',
                    title: '编辑',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',

                    click: async row => {
                        dialogFormVisible.value = true
                        dialogTitle.value = '编辑设备'
                        for (let key in form) {
                            form[key] = row[key]
                        }
                        form.id = row.id
                    }
                },
                {
                    name: 'del',
                    title: '删除',
                    type: 'danger',
                    icon: 'el-icon-Delete',
                    render: 'basicButton',
                    click: row => {
                        ElMessageBox.confirm('确定删除该设备吗?', '提示', {
                            confirmButtonText: '确认',
                            cancelButtonText: '取消',
                            type: 'warning'
                        })
                            .then(() => {
                                deleteEquipmentDelivery(row.id).then(res => {
                                    ElMessage.success('删除成功!')
                                    tableStore.onTableAction('search', {})
                                })
                            })
                            .catch(e => { })
                    }
                }
            ]
        }
    ],
    beforeSearchFun: () => {
        for (let key in tableStore.table.params) {
            if (tableStore.table.params[key] === '') {
                delete tableStore.table.params[key]
            }
        }
    }
})
tableStore.table.params.orderBy = 'desc'

// 设备类型
const devTypeChange = (e: any) => {
    if (!e) {
        return
    }
    tableStore.table.params.devModel = ''
}
// 下载模版
const downLoadFile = () => {
    getExcelTemplate().then(res => {
        let blob = new Blob([res], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = url
        link.download = '设备导入模版.xlsx' // 设置下载的文件名
        document.body.appendChild(link)
        link.click() //执行下载
        document.body.removeChild(link)
        ElMessage.success('下载成功')
    })
}

// 导入模版
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)
                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 onSubmit = () => {
    ruleFormRef.value.validate((valid: any) => {
        if (valid) {
            loading.value = true
            if (dialogTitle.value == '新增设备') {
                addEquipmentDelivery(form).then(res => {
                    ElMessage.success('新增成功')
                    resetForm()
                    tableStore.onTableAction('search', {})
                }).finally(() => {
                    loading.value = false
                })
            } else {
                editEquipmentDelivery(form).then(res => {
                    ElMessage.success('修改成功')
                    resetForm()
                    tableStore.onTableAction('search', {})
                }).finally(() => {
                    loading.value = false
                })
            }
        }
    })
}
// 清空表格
const resetForm = () => {
    ruleFormRef.value.resetFields()
    dialogFormVisible.value = false
    nextTick(() => {
        // 模拟待编辑数据
        let user = {
            cntractNo: '',
            devAccessMethod: 'mqtt',
            devModel: '',
            devType: '',
            name: '',
            ndid: ''
        }
        Object.assign(form, user)
    })
}

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

onMounted(() => {
    setTimeout(() => {
        tableStore.index()
    }, 100)
})

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>
