<template>
    <!-- 设备 -->
    <div class="ba-user-container">
        <el-container class="defaultContainer">
            <el-aside class="defaultAside">
                <el-main class="treeMain">
                    <el-tree
                        style="max-width: 600px; margin-top: 2.2%"
                        :data="userData"
                        :props="defaultProps"
                        node-key="id"
                        @node-click="handleNodeClick"
                    />
                </el-main>
            </el-aside>
            <el-container class="defaultMainContainer">
                <el-header class="defaultHeader">
                    <el-space>
                        <el-input v-model="headerForm.searchFor"></el-input>
                        <el-radio-group v-model="headerForm.resource">
                            <el-radio value="1" label="名称"></el-radio>
                            <el-radio value="2" label="编码"></el-radio>
                        </el-radio-group>
                        <el-button type="primary" :icon="Search" class="defaultBtn" @click="deviceTypeQuery">查询</el-button>
                    </el-space>
                    <div style="display: flex; align-items: center">
                        <div>
                            <el-button size="large" :icon="CirclePlusFilled" type="primary" class="defaultBtn" @click="addDeviceList">新增</el-button>
                        </div>
                        <div style="margin: 0px 10px 0px">
                            <el-upload :show-file-list="false" :http-request="upLoadModel">
                                <template #trigger>
                                    <el-button size="large" :icon="Upload">导入</el-button>
                                </template>
                            </el-upload>
                        </div>
                        <div>
                            <el-button size="large" :icon="Download" class="defaultBtn" @click="Export">导出</el-button>
                        </div>
                    </div>
                </el-header>
                <el-main class="defaultMain">
                    <el-table ref="multipleTableRef" :data="deviceList" class="tablePart">
                        <el-table-column type="selection" />
                        <el-table-column property="name" label="设备名称" />
                        <el-table-column property="code" label="设备编码" />
                        <el-table-column property="madeinFactory" label="生产厂家" />
                        <el-table-column property="model" label="规格型号" />
                        <el-table-column property="address" label="操作">
                            <template #default="scope">
                                <span style="color: #0064aa; cursor: pointer" @click="viewDeviceDetails(scope)">查看 </span>
                                <span style="color: #0064aa"> | </span>
                                <span style="color: #0064aa; cursor: pointer" @click="deviceDeletion(scope)"> 删除 </span>
                                <span style="color: #0064aa"> | </span>
                                <span style="color: #0064aa; cursor: pointer"> 门户 </span>
                                <span style="color: #0064aa"> | </span>
                                <span style="color: #0064aa; cursor: pointer"> 密码</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="display: flex; justify-content: right">
                        <el-pagination
                            v-model:current-page="currentPage"
                            v-model:page-size="currentPageSize"
                            :total="pageTotal"
                            :page-sizes="pagePagination"
                            background
                            :pager-count="7"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            layout="prev, pager, next, jumper,sizes,total"
                        ></el-pagination>
                    </div>
                </el-main>
            </el-container>
            <!-- 查看设备详情页面 -->
            <el-dialog v-model="editDeviceDialog" title="编辑设备台账" width="1000" :before-close="handleCloseEditDevice">
                <el-form
                    ref="modifyDeviceDetails"
                    :inline="true"
                    label-width="auto"
                    :model="editDeviceData"
                    :rules="editDeviceRules"
                    style="padding: 20px 33px; font-size: 14px; line-height: 1.5; word-wrap: break-word; font-size: 20px"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="设备类型:">
                                <el-input v-model="editDeviceData.objectType" placeholder="请输入设备类型" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="物模型ID:">
                                <el-input v-model="editDeviceData.iotModelId" placeholder="请输入物模型ID" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="设备名称:" prop="name">
                                <el-input v-model="editDeviceData.name" placeholder="请输入设备名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="设备编码:" prop="code">
                                <el-input v-model="editDeviceData.code" placeholder="请输入设备编码" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="管理部门:" prop="madeinFactory">
                                <el-input v-model="editDeviceData.orgId" placeholder="请输入管理部门" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="生产厂家:">
                                <el-input v-model="editDeviceData.madeinFactory" placeholder="请输入生产厂家" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="规格型号:">
                                <el-input v-model="editDeviceData.model" placeholder="请输入规格型号" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="安装位置:">
                                <el-input v-model="editDeviceData.location" placeholder="请输入安装位置" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="安装位置_经度:">
                                <el-input v-model="editDeviceData.longitude" placeholder="请输入安装位置_经度" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="安装位置_纬度:">
                                <el-input v-model="editDeviceData.latitude" placeholder="请输入安装位置_纬度" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="安装日期:">
                                <el-date-picker
                                    v-model="editDeviceData.installDate"
                                    type="datetime"
                                    style="width: 190px"
                                    placeholder="请输入安装日期"
                                    :size="size"
                                    format="YYYY-MM-DD HH:mm:ss"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注:">
                                <el-input v-model="editDeviceData.remarks" placeholder="请输入备注" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="上级设备ID:">
                                <el-input v-model="editDeviceData.parentEquipmentId" placeholder="请输入上级设备ID" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="editDeviceDialog = false"> 取消 </el-button>
                        <el-button @click="saveData">保存</el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 新增设备详情页面 -->
            <el-dialog v-model="editAddDeviceDialog" title="新增设备台账" width="1000" :before-close="handleCloseAddEditDevice">
                <el-form
                    ref="modifyAddDeviceDetails"
                    :inline="true"
                    label-width="auto"
                    :model="editAddDeviceData"
                    :rules="editAddDeviceRules"
                    style="padding: 20px 33px; font-size: 14px; line-height: 1.5; word-wrap: break-word; font-size: 20px"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="设备类型:">
                                <el-input v-model="editAddDeviceData.objectType" placeholder="请输入设备类型" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="物模型ID:">
                                <el-input v-model="editAddDeviceData.iotModelId" placeholder="请输入物模型ID" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="设备名称:" prop="name">
                                <el-input v-model="editAddDeviceData.name" placeholder="请输入设备名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="设备编码:" prop="code">
                                <el-input v-model="editAddDeviceData.code" placeholder="请输入设备编码" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="管理部门:" prop="madeinFactory">
                                <el-input v-model="editAddDeviceData.orgId" placeholder="请输入管理部门" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="生产厂家:">
                                <el-input v-model="editAddDeviceData.madeinFactory" placeholder="请输入生产厂家" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="规格型号:">
                                <el-input v-model="editAddDeviceData.model" placeholder="请输入规格型号" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="安装位置:">
                                <el-input v-model="editAddDeviceData.location" placeholder="请输入安装位置" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="安装位置_经度:">
                                <el-input v-model="editAddDeviceData.longitude" placeholder="请输入安装位置_经度" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="安装位置_纬度:">
                                <el-input v-model="editAddDeviceData.latitude" placeholder="请输入安装位置_纬度" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="安装日期:">
                                <el-date-picker
                                    v-model="editAddDeviceData.installDate"
                                    type="datetime"
                                    style="width: 190px"
                                    placeholder="请输入安装日期"
                                    :size="size"
                                    format="YYYY-MM-DD HH:mm:ss"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注:">
                                <el-input v-model="editAddDeviceData.remarks" placeholder="请输入备注" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="上级设备ID:">
                                <el-input v-model="editAddDeviceData.parentEquipmentId" placeholder="请输入上级设备ID" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="editAddDeviceDialog = false"> 取消 </el-button>
                        <el-button @click="saveAddData">保存</el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 删除弹框 -->
            <el-dialog v-model="dialogDeviceDeletion" title="操作提示" width="500" :before-close="handleCloseDelete">
                <span>确定是否删除?</span>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogDeviceDeletion = false">取消</el-button>
                        <el-button type="primary" @click="dialogDeviceDeletion1"> 确定 </el-button>
                    </div>
                </template>
            </el-dialog>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search, CirclePlusFilled, Upload, Download } from '@element-plus/icons-vue'
import { equipTree, equipQuery, equipAdd, equipDelete, equipUpdate, equipImport, equipExport } from '/@/api/backend'
import { ElTable, ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { useAdminInfo } from '/@/stores/adminInfo'
import { encrypt_aes, generateRandomNumber } from '/@/utils/crypto'

const adminInfo = useAdminInfo()
interface Tree {
    label: string
    children?: Tree[]
    id: string
}

// 设备左边树
const treeQuery = reactive({
    orgId: adminInfo.orgid,
})

const userData = ref()

const getTree = () => {
    console.log(treeQuery, 'treeQuery')

    equipTree(treeQuery).then((res) => {
        console.log(res, '树')
        userData.value = res.data
    })
}

// const aa = (data: any[]) => {
//     data.forEach((item: any) => {
//         if (!item.orgChildren) {
//             item.orgChildren = []
//         }
//         if (!item.equipChildren) {
//             item.equipChildren = []
//         }
//         if (item.orgChildren && item.orgChildren.length) {
//             item.equipChildren = [...item.equipChildren, ...item.orgChildren]
//             aa(item.orgChildren)
//         }
//     })
// }

onMounted(() => {
    getTree()
})

const formQuery = reactive({
    parentEquipmentId: '',
    iotModelId: '',
    pageSize: 0,
    pageNum: 0,
    objectType: '',
})
const queryParameter = ref()
const handleNodeClick = (data: any) => {
    console.log(data, '设备树data')

    queryParameter.value = data
    formQuery.parentEquipmentId = data.id
    formQuery.pageSize = currentPageSize.value
    formQuery.pageNum = currentPage.value
    formQuery.objectType = data.objectType
    equipQuery(formQuery).then((res) => {
        console.log(res)
        deviceList.value = res.rows
        pageTotal.value = res.total
    })
}

const loadNode = (node: Node, resolve: (data: Tree[]) => void) => {}

const deviceList = ref()
//  设备查询 equipQuery
const deviceQuery = (data: any) => {
    equipQuery(data).then((res) => {
        deviceList.value = res.rows
        pageTotal.value = res.total
    })
}

// 查询按钮
// 名字
const nameQuery = reactive({
    parentEquipmentId: '',
    iotModelId: '',
    pageSize: 0,
    pageNum: 0,
    name: '',
})
// 编号
const nameQuery2 = reactive({
    parentEquipmentId: '',
    iotModelId: '',
    pageSize: 0,
    pageNum: 0,
    code: '',
})
const deviceTypeQuery = () => {
    // 名称查询
    if (headerForm.resource === '1') {
        nameQuery.name = headerForm.searchFor
        nameQuery.parentEquipmentId = queryParameter.value.id
        nameQuery.pageSize = currentPageSize.value
        nameQuery.pageNum = currentPage.value
        deviceQuery(nameQuery)
    }
    // 编码查询
    if (headerForm.resource === '2') {
        nameQuery2.code = headerForm.searchFor
        nameQuery2.parentEquipmentId = queryParameter.value.id
        nameQuery2.pageSize = currentPageSize.value
        nameQuery2.pageNum = currentPage.value
        deviceQuery(nameQuery2)
    }
}

// 分页
const pagePagination = [5, 10, 20, 30]
const currentPage = ref(1)
const currentPageSize = ref(pagePagination[0])
const handleSizeChange = (val: number) => {
    formQuery.pageSize = val
    deviceQuery(formQuery)
}
const handleCurrentChange = (val: number) => {
    formQuery.pageNum = val
    deviceQuery(formQuery)
}
const pageTotal = ref(0)
const defaultProps = {
    children: 'equipChildren',
    label: 'name',
}

// 头部搜索框按钮功能
const headerForm = reactive({
    searchFor: '',
    resource: '2',
})

// 新增按钮
const addDeviceList = () => {
    editAddDeviceDialog.value = true
    editAddDeviceData.objectType = ''
    editAddDeviceData.code = ''
    editAddDeviceData.name = ''
    editAddDeviceData.madeinFactory = ''
    editAddDeviceData.model = ''
    editAddDeviceData.location = ''
    editAddDeviceData.longitude = ''
    editAddDeviceData.latitude = ''
    editAddDeviceData.installDate = ''
    editAddDeviceData.remarks = ''
    editAddDeviceData.orgId = ''
    editAddDeviceData.parentEquipmentId = ''
    editAddDeviceData.iotModelId = ''
}

// 查看设备详情
const editDeviceDialog = ref(false)

const editDeviceData = reactive({
    objectType: '',
    code: '',
    name: '',
    madeinFactory: '',
    model: '',
    location: '',
    longitude: '',
    latitude: '',
    installDate: '',
    remarks: '',
    orgId: '',
    parentEquipmentId: '',
    iotModelId: '',
    id: '',
})

const size = ref<'default' | 'large' | 'small'>('default')

const handleCloseEditDevice = () => {
    editDeviceDialog.value = false
}

// 设备查看按钮
const viewDeviceDetails = (data: any) => {
    console.log(data, '查看设备详情')

    editDeviceDialog.value = true
    editDeviceData.id = data.row.id
    editDeviceData.objectType = data.row.objectType
    editDeviceData.code = data.row.code
    editDeviceData.name = data.row.name
    editDeviceData.madeinFactory = data.row.madeinFactory
    editDeviceData.model = data.row.model
    editDeviceData.location = data.row.location
    editDeviceData.longitude = data.row.longitude
    editDeviceData.latitude = data.row.latitude
    editDeviceData.installDate = data.row.installDate
    editDeviceData.remarks = data.row.remarks
    editDeviceData.orgId = data.row.orgId
    editDeviceData.parentEquipmentId = data.row.parentEquipmentId
    editDeviceData.iotModelId = data.row.iotModelId
}

// 设备删除
const dialogDeviceDeletion = ref(false)
const deviceDeletion = (data: any) => {
    dialogDeviceDeletion.value = true
    del.id = data.row.id
}
//  弹框
const handleCloseDelete = () => {
    dialogDeviceDeletion.value = false
}

// 确认
const del = {
    id: '',
}
const dialogDeviceDeletion1 = () => {
    equipDelete(del).then((res) => {
        if (res.code == 200) {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            dialogDeviceDeletion.value = false
            deviceQuery(formQuery)
            getTree()
        } else {
            ElMessage.error({
                message: res.msg,
                type: 'error',
            })
        }
    })
}

const editDeviceRules = reactive({
    // name: [
    //     {
    //         required: true,
    //         message: '设备名称不能为空',
    //         trigger: 'blur',
    //     },
    // ],
    // code: [
    //     {
    //         required: true,
    //         message: '设备编码不能为空',
    //         trigger: 'blur',
    //     },
    // ],
    // administrative: [
    //     {
    //         required: true,
    //         message: '管理部门不能为空',
    //         trigger: 'blur',
    //     },
    // ],
    // statusIdentification: [
    //     {
    //         required: true,
    //         message: '状态标识不能为空',
    //         trigger: 'blur',
    //     },
    // ],
})
const modifyDeviceDetails = ref()
const saveData = () => {
    console.log(editDeviceData, 'editDeviceData')

    modifyDeviceDetails.value.validate((valid: any) => {
        if (valid) {
            equipUpdate(editDeviceData).then((res: any) => {
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                    deviceQuery(formQuery)
                    getTree()
                } else {
                    ElMessage.error({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        } else {
            console.log('error submit!!')
            return false
        }
    })
    editDeviceDialog.value = false
}

// 新增设备
const editAddDeviceData = reactive({
    objectType: '',
    code: '',
    name: '',
    madeinFactory: '',
    model: '',
    location: '',
    longitude: '',
    latitude: '',
    installDate: '',
    remarks: '',
    orgId: '',
    parentEquipmentId: '',
    iotModelId: '',
})

// 设备新增字段校验
const editAddDeviceRules = reactive({
    // name: [
    //     {
    //         required: true,
    //         message: '设备名称不能为空',
    //         trigger: 'blur',
    //     },
    // ],
    // code: [
    //     {
    //         required: true,
    //         message: '设备编码不能为空',
    //         trigger: 'blur',
    //     },
    // ],
    // administrative: [
    //     {
    //         required: true,
    //         message: '管理部门不能为空',
    //         trigger: 'blur',
    //     },
    // ],
    // statusIdentification: [
    //     {
    //         required: true,
    //         message: '状态标识不能为空',
    //         trigger: 'blur',
    //     },
    // ],
})

const editAddDeviceDialog = ref(false)
const modifyAddDeviceDetails = ref()
const saveAddData = () => {
    modifyAddDeviceDetails.value.validate((valid: any) => {
        if (valid) {
            console.log(editAddDeviceData, 'editAddDeviceData')
            equipAdd(editAddDeviceData).then((res) => {
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                    deviceQuery(formQuery)
                    getTree()
                } else {
                    ElMessage.error({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
            editAddDeviceDialog.value = false
        }
    })
}
const handleCloseAddEditDevice = () => {
    editAddDeviceDialog.value = false
}
// 导入
const upLoadModel = (file: any) => {
    const formData = new FormData()
    formData.append('file', file.file)
    const v = generateRandomNumber(16)
    const id = encrypt_aes(queryParameter.value.id, v)
    formData.append('id', id)
    return equipImport(formData, v)
        .then((res: any) => {
            if (res.success) {
                ElMessage.success('上传设备成功')
                deviceQuery(formQuery)
            } else {
                ElMessage.error(res.msg)
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '上传失败')
        })
}

// 导出
const Export = () => {
    equipExport({ id: queryParameter.value.id }).then((res: any) => {
        const downloadUrl = window.URL.createObjectURL(res)
        const a = document.createElement('a')
        a.href = downloadUrl
        a.download = '设备' + new Date().getTime()
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(downloadUrl)
        document.body.removeChild(a)
    })
}
</script>

<style scoped lang="scss">
.el-col {
    // border-radius: 4px;
    background-color: #fff;
}
@mixin searchInput($value) {
    margin-right: $value;
    width: 220px;
    height: 40px;
}
$headerHeight: 60px;
$defaultBackgroundColor: #fff;
$defaultHeaderHeight: 60px;
$defaultAsideWidth: 260px;
$defaultMainHeight: calc(100% - 60px);
$paginationHeight: 32px;
.ba-user-container {
    width: 100%;
    height: 100%;
    // background-color: #fff;
    .defaultContainer {
        width: 100%;
        height: 100%;
        .defaultAside {
            width: 260px;
            height: 100%;
            border-right: 1px solid #eaebed;
            .treeHeader {
                display: flex;
                align-items: center;
                justify-content: center;
                height: $defaultHeaderHeight;
                .searchInput {
                    height: 40px;
                }
            }
            .treeMain {
                height: calc(100% - $headerHeight);
                overflow-y: auto;
                .treePart {
                    height: 100%;
                    background-color: $defaultBackgroundColor;
                }
            }
        }
        .defaultMainContainer {
            width: calc(100% - $defaultAsideWidth);
            height: 100%;
            .defaultHeader {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: $headerHeight;
                padding: 0 20px;
                border-bottom: 1px solid #eaebed;
                .searchPart {
                    height: 40px;
                    width: 220px;
                }
                .defaultBtn {
                    width: 88px;
                    height: 40px;
                }
                .searchInput {
                    @include searchInput(10px);
                }
            }
            .defaultMain {
                height: $defaultMainHeight;
                .tablePart {
                    height: calc(100% - $paginationHeight);
                }
                .tableOperate {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    a {
                        margin: 5px;
                        color: #0064aa;
                        font-weight: 600;
                        &:hover {
                            cursor: pointer;
                        }
                    }
                }
            }
        }
    }
}
</style>
