<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%"
                        ref="equipTreeRef"
                        :data="userData"
                        :props="defaultProps"
                        node-key="equipmentTypeId"
                        @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="openMeasure(scope)">量测</span>
                                <span style="color: #0064aa"> | </span>
                                <span style="color: #0064aa; cursor: pointer" @click="openControl(scope)">调控</span>
                                <span style="color: #0064aa"> | </span>
                                <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>
                            </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="720" :before-close="handleCloseEditDevice">
                <el-form
                    ref="modifyDeviceDetails"
                    :inline="true"
                    label-width="auto"
                    :model="editDeviceData"
                    :rules="editDeviceRules"
                    style="padding: 5px 15px; 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" disabled placeholder="请输入设备类型" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="物模型:">
                                <el-select
                                    :disabled="editDeviceData.iotModelId"
                                    v-model="editDeviceData.iotModelId"
                                    placeholder="请选择物模型"
                                    style="width: 200px"
                                >
                                    <el-option v-for="item in equipModeData" :key="item.id" :label="item.iotModelName" :value="item.id" />
                                </el-select>
                            </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" style="width: 200px" placeholder="请输入设备编码" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="生产厂家:">
                                <el-input
                                    :disabled="hasSetOfMachines"
                                    v-model="editDeviceData.madeinFactory"
                                    :placeholder="hasSetOfMachines ? '请选择规格型号' : '请输入生产厂家'"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="规格型号:">
                                <el-select
                                    v-if="hasSetOfMachines"
                                    v-model="editDeviceData.model"
                                    placeholder="请选择规格型号"
                                    style="width: 200px"
                                    @change="selectEditModel"
                                >
                                    <el-option v-for="item in modelList" :key="item.model" :value="item.model"></el-option>
                                </el-select>
                                <el-input v-else v-model="editDeviceData.model" style="width: 200px" placeholder="请输入规格型号" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="管理部门:" prop="madeinFactory">
                                <el-tree-select
                                    v-model="editDeviceData.orgId"
                                    lazy
                                    :load="treeSelectLoad"
                                    :props="treeSelectProps"
                                    check-strictly
                                    style="width: 190px"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12" v-if="editDeviceData.objectType !== '风电场'">
                            <el-form-item label="所属风电场:">
                                <el-tree-select
                                    :disabled="editDeviceData.objectType === '风电场'"
                                    :placeholder="editDeviceData.objectType === '风电场' ? '无' : '请选择所属风电场'"
                                    v-model="editDeviceData.parentEquipmentId"
                                    :data="belongingEquipment"
                                    :props="defaultEquipmentProps"
                                    :render-after-expand="false"
                                    check-strictly
                                    style="width: 200px"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="editDeviceData.objectType !== '风电场'">
                            <el-form-item label="所属线路:">
                                <el-input placeholder="请输入所属线路" v-model="editDeviceData.belongLine" style="width: 200px" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="editDeviceData.objectType !== '风电场'">
                            <el-form-item label="标杆机组:">
                                <el-switch @change="edithandleSwitchChange" :active-value="1" :inactive-value="0" v-model="editDeviceData.standard" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="安装位置:">
                                <el-input v-model="editDeviceData.location" style="width: 570px" placeholder="请输入安装位置" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="经度:" prop="longitude">
                                <el-input-number
                                    v-model="editDeviceData.longitude"
                                    style="width: 200px"
                                    :controls="false"
                                    placeholder="请输入经度"
                                    controls-position="right"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="纬度:" prop="latitude">
                                <el-input-number
                                    v-model="editDeviceData.latitude"
                                    style="width: 200px"
                                    :controls="false"
                                    placeholder="请输入纬度"
                                    controls-position="right"
                                />
                            </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="date"
                                    style="width: 200px"
                                    placeholder="请输入安装日期"
                                    :size="size"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="hasSetOfMachines ? '额定容量(MW):' : '装机容量(MW):'">
                                <el-input-number
                                    :disabled="hasSetOfMachines"
                                    style="width: 200px"
                                    :controls="false"
                                    :placeholder="hasSetOfMachines ? '请输入额定容量' : '请输入装机容量'"
                                    v-model="editDeviceData.nominalCapacity"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="备注:">
                                <el-input
                                    v-model="editDeviceData.remarks"
                                    style="width: 530px"
                                    :rows="2"
                                    type="textarea"
                                    placeholder="请输入备注"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="saveData">保存</el-button>
                        <el-button @click="editDeviceDialog = false">取消</el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 新增设备详情页面 -->
            <el-dialog v-model="editAddDeviceDialog" title="新增设备台账" width="720" :before-close="handleCloseAddEditDevice">
                <el-form
                    ref="modifyAddDeviceDetails"
                    :inline="true"
                    label-width="auto"
                    :model="editAddDeviceData"
                    :rules="editAddDeviceRules"
                    style="padding: 5px 15px; 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" disabled placeholder="请输入设备类型" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="物模型:">
                                <el-select v-model="editAddDeviceData.iotModelId" placeholder="请选择物模型" style="width: 200px">
                                    <el-option v-for="item in equipModeData" :key="item.id" :label="item.iotModelName" :value="item.id" />
                                </el-select>
                            </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" style="width: 200px" placeholder="请输入设备编码" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="生产厂家:">
                                <el-input
                                    :disabled="hasSetOfMachines"
                                    v-model="editAddDeviceData.madeinFactory"
                                    :placeholder="hasSetOfMachines ? '请选择规格型号' : '请输入生产厂家'"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="规格型号:">
                                <el-select
                                    v-if="hasSetOfMachines"
                                    v-model="editAddDeviceData.model"
                                    placeholder="请选择规格型号"
                                    style="width: 200px"
                                    @change="selectAddModel"
                                >
                                    <el-option v-for="item in modelList" :key="item.model" :value="item.model"></el-option>
                                </el-select>
                                <el-input v-else v-model="editAddDeviceData.model" placeholder="请输入规格型号" style="width: 200px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="管理部门:" prop="madeinFactory">
                                <el-tree-select
                                    v-model="editAddDeviceData.orgId"
                                    lazy
                                    :load="treeSelectLoad"
                                    :props="treeSelectProps"
                                    check-strictly
                                    style="width: 190px"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12" v-if="editAddDeviceData.objectType !== '风电场'">
                            <el-form-item label="所属风电场:">
                                <el-tree-select
                                    :disabled="editAddDeviceData.objectType === '风电场'"
                                    :placeholder="editAddDeviceData.objectType === '风电场' ? '无' : '请选择所属风电场'"
                                    v-model="editAddDeviceData.parentEquipmentId"
                                    :data="belongingEquipment"
                                    :props="defaultEquipmentProps"
                                    :render-after-expand="false"
                                    check-strictly
                                    style="width: 200px"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="editAddDeviceData.objectType !== '风电场'">
                            <el-form-item label="所属线路:">
                                <el-input placeholder="请输入所属线路" v-model="editAddDeviceData.belongLine" style="width: 200px" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="editAddDeviceData.objectType !== '风电场'">
                            <el-form-item label="标杆机组:">
                                <el-switch
                                    @change="addhandleSwitchChange"
                                    :active-value="1"
                                    :inactive-value="0"
                                    v-model="editAddDeviceData.standard"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="安装位置:">
                                <el-input v-model="editAddDeviceData.location" style="width: 570px" placeholder="请输入安装位置" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="经度:" prop="longitude">
                                <el-input-number
                                    v-model="editAddDeviceData.longitude"
                                    style="width: 200px"
                                    :controls="false"
                                    placeholder="请输入经度"
                                    controls-position="right"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="纬度:" prop="latitude">
                                <el-input-number
                                    v-model="editAddDeviceData.latitude"
                                    style="width: 200px"
                                    :controls="false"
                                    placeholder="请输入纬度"
                                    controls-position="right"
                                />
                            </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="date"
                                    style="width: 200px"
                                    placeholder="请输入安装日期"
                                    :size="size"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="hasSetOfMachines ? '额定容量(MW):' : '装机容量(MW):'">
                                <el-input-number
                                    :disabled="hasSetOfMachines"
                                    style="width: 200px"
                                    :controls="false"
                                    :placeholder="hasSetOfMachines ? '请输入额定容量' : '请输入装机容量'"
                                    v-model="editAddDeviceData.nominalCapacity"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="备注:">
                                <el-input
                                    v-model="editAddDeviceData.remarks"
                                    style="width: 530px"
                                    :rows="2"
                                    type="textarea"
                                    placeholder="请输入备注"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="saveAddData">保存</el-button>
                        <el-button @click="editAddDeviceDialog = false">取消</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 type="primary" @click="dialogDeviceDeletion1">保存</el-button>
                        <el-button @click="dialogDeviceDeletion = false">取消</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-container>
        <el-dialog v-model="showControlPage" :width="800">
            <div class="controlSlot">
                <ControlPage :deviceId="contorlData.deviceId" :iotModelId="contorlData.iotModelId" :show="showControlPage"></ControlPage>
            </div>
        </el-dialog>
        <el-dialog v-model="showMeasure" title="量测" :width="800">
            <template #header>
                <div class="measureSlotHeader">
                    <span style="font-size: 20px">量测</span>
                    <div class="measureSlotHeaderRight">
                        <span>自动更新：</span>
                        <el-switch
                            v-model="measureData.autoUpdate"
                            class="ml-2"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        ></el-switch>
                    </div>
                    <el-tabs v-model="measureData.measureType" class="measureTabs">
                        <el-tab-pane label="模拟量" :name="138"></el-tab-pane>
                        <el-tab-pane label="离散量" :name="140"></el-tab-pane>
                        <el-tab-pane label="累计量" :name="139"></el-tab-pane>
                        <el-tab-pane label="计算量" :name="199"></el-tab-pane>
                    </el-tabs>
                </div>
            </template>
            <div class="measureSlot">
                <MeasurementPage
                    :show="showMeasure"
                    :deviceId="measureData.deviceId"
                    :iotModelId="measureData.iotModelId"
                    :autoUpdate="measureData.autoUpdate"
                    :attributeType="measureData.measureType"
                    :madein-factory="measureData.madeinFactory"
                    :model="measureData.model"
                ></MeasurementPage>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { Search, CirclePlusFilled, Upload, Download } from '@element-plus/icons-vue'
import {
    equipTree,
    equipQuery,
    equipAdd,
    equipDelete,
    equipUpdate,
    equipImport,
    equipExport,
    equipType,
    equipDetailsModel,
    equipDetailsOrg,
} from '/@/api/backend'
import { ElTable, ElMessage, ElMessageBox } from 'element-plus'
import { useAdminInfo } from '/@/stores/adminInfo'
import { encrypt_aes, generateRandomNumber } from '/@/utils/crypto'
import ControlPage from './control.vue'
import MeasurementPage from './measurement.vue'
import { ModelAttributeType } from '/@/views/backend/auth/model/type'
import { theoreticalpowerCurveList } from '/@/api/backend/theoreticalpowerCurve/request'

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

// 设备左边树
const userData = ref()
const equipTreeRef = ref()
// 设备类型
const deviceTypeList = ref()
const equipTypeList = () => {
    equipType().then((res) => {
        userData.value = res.data
        deviceTypeList.value = res.data
        nextTick(() => {
            equipTreeRef.value?.setCurrentKey(res.data[0]?.equipmentTypeId!, false)
            formQuery.pageSize = currentPageSize.value
            formQuery.pageNum = currentPage.value
            formQuery.objectType = res.data[0].equipmentTypeId
            equipQuery(formQuery).then((res) => {
                deviceList.value = res.rows
                pageTotal.value = res.total
            })
            queryParameter.value = res.data[0]
            equipModeList({
                objectType: res.data[0].equipmentTypeId,
            })
            queryParameter.value.equipmentTypeId = res.data[0].equipmentTypeId
        })
    })
}

// 设备详情物模型
const equipModeData = ref()
const equipModeList = (data: any) => {
    equipDetailsModel(data).then((res) => {
        equipModeData.value = res.data
    })
}

// 设备详情机构列表
const equipOrgData = ref()
const equipOrgList = () => {
    equipDetailsOrg({
        parentOrgId: adminInfo.orgid,
    }).then((res) => {
        equipOrgData.value = res.data
    })
}

// 所属设备
const belongingEquipment = ref()
const equipOrgBelonging = () => {
    equipTree().then((res) => {
        belongingEquipment.value = filterEquipments(res.data)
    })
}
const filterEquipments = (data: any) => {
    return data
        .filter((item: any) => item.objectType == 10001)
        ?.map((item: any) => ({
            ...item,
            equipChildren: filterEquipments(item.equipChildren),
        }))
}

const treeSelectLoad = (node: any, resolve: any) => {
    if (node.level === 0) {
        equipDetailsOrg({
            parentOrgId: null,
        }).then((res: any) => {
            if (!res.data.length) {
                node.isLeaf = true
            }

            return resolve(res.data)
        })
    } else {
        equipDetailsOrg({ parentOrgId: node.data.id })
            .then((res: any) => {
                if (!res.data.length) {
                    node.isLeaf = true
                }
                return resolve(res.data)
            })
            .catch((err) => {})
    }
}

const treeSelectProps = {
    label: 'name',
    value: 'id',
    children: 'children',
}

const defaultEquipmentProps = {
    label: 'name',
    value: 'id',
    children: 'equipChildren',
}

onMounted(() => {
    equipTypeList()
    equipOrgList()
    equipOrgBelonging()
})

const formQuery = reactive({
    pageSize: 0,
    pageNum: 0,
    objectType: '',
})
const queryParameter = ref()
const handleNodeClick = (data: any) => {
    queryParameter.value = data
    formQuery.pageSize = currentPageSize.value
    formQuery.pageNum = currentPage.value
    formQuery.objectType = data.equipmentTypeId
    equipQuery(formQuery).then((res) => {
        deviceList.value = res.rows

        pageTotal.value = res.total
    })
    equipModeList({
        objectType: data.equipmentTypeId,
    })
}

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

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

// 分页
const pagePagination = [20, 50, 100]
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 = {
    label: 'equipmentTypeName',
}

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

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

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

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

const hasSetOfMachines = computed(() => {
    return queryParameter.value.equipmentTypeId === 10002
})
const modelList = ref<{ model: string; madeinFactory: string; nominalCapacity: string }[]>([])

const getModelList = () => {
    theoreticalpowerCurveList().then((res) => {
        if (res.rows) {
            modelList.value = (res.rows as any[]).map((item: any) => {
                return {
                    model: item.model,
                    madeinFactory: item.madeinfactory,
                    nominalCapacity: item.nominalCapacity,
                }
            })
        }
    })
}
const selectEditModel = (value: string) => {
    editDeviceData.madeinFactory = modelList.value.find((item) => item.model == value)?.madeinFactory || ''
    editDeviceData.nominalCapacity = modelList.value.find((item) => item.model == value)?.nominalCapacity || ''
}
const selectAddModel = (value: string) => {
    editAddDeviceData.madeinFactory = modelList.value.find((item) => item.model == value)?.madeinFactory || ''
    editAddDeviceData.nominalCapacity = modelList.value.find((item) => item.model == value)?.nominalCapacity || ''
}
const size = ref<'default' | 'large' | 'small'>('default')

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

// 设备查看按钮
const viewDeviceDetails = (data: any) => {
    equipOrgBelonging()
    modifyDeviceDetails.value?.resetFields()
    editDeviceDialog.value = true
    editDeviceData.id = data.row.id
    editDeviceData.objectType = queryParameter.value.equipmentTypeName
    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
    editDeviceData.belongLine = data.row.belongLine
    editDeviceData.standard = data.row.standard || 0
    editDeviceData.nominalCapacity = data.row.nominalCapacity
}

// 设备删除
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)
        } else {
            ElMessage.error({
                message: res.msg,
                type: 'error',
            })
        }
    })
}
const longitudePass = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback()
    }
    if (value >= 73.66 && value <= 135.05) {
        callback()
    } else {
        callback(new Error('请输入73.66~135.05之间的数字'))
    }
}

const latitudePass = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback()
    }
    if (value >= 3.86 && value <= 53.55) {
        callback()
    } else {
        callback(new Error('请输入3.86~53.55之间的数字'))
    }
}

const editDeviceRules = reactive({
    name: [
        {
            required: true,
            message: '设备名称不能为空',
            trigger: 'blur',
        },
    ],
    code: [
        {
            required: true,
            message: '设备编码不能为空',
            trigger: 'blur',
        },
    ],
    longitude: [{ validator: longitudePass, trigger: 'blur' }],
    latitude: [{ validator: latitudePass, trigger: 'blur' }],
})
const modifyDeviceDetails = ref()
const saveData = () => {
    modifyDeviceDetails.value.validate((valid: any) => {
        if (valid) {
            deviceTypeList.value.forEach((ele: any) => {
                if (ele.equipmentTypeName === editDeviceData.objectType) {
                    editDeviceData.objectType = ele.equipmentTypeId
                }
            })
            equipUpdate(editDeviceData)
                .then((res: any) => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        deviceQuery(formQuery)
                    } else {
                        ElMessage.error({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                })
                .catch((err) => {
                    ElMessage.error({
                        message: err.response?.data?.msg ?? '编辑失败！',
                        type: 'error',
                    })
                })
        } else {
            return false
        }
    })
    editDeviceDialog.value = false
}

// 新增设备
const editAddDeviceData = reactive({
    objectType: '',
    code: '',
    name: '',
    madeinFactory: '',
    model: '',
    location: '',
    longitude: null,
    latitude: null,
    installDate: '',
    remarks: '',
    orgId: '',
    parentEquipmentId: '',
    iotModelId: '',
    belongLine: '',
    standard: 0,
    nominalCapacity: '',
})
const addhandleSwitchChange = (value: any) => {
    editAddDeviceData.standard = value ? 1 : 0
}
const edithandleSwitchChange = (value: any) => {
    editDeviceData.standard = value ? 1 : 0
}

// 设备新增字段校验
const editAddDeviceRules = reactive({
    name: [
        {
            required: true,
            message: '设备名称不能为空',
            trigger: 'blur',
        },
    ],
    code: [
        {
            required: true,
            message: '设备编码不能为空',
            trigger: 'blur',
        },
    ],
    longitude: [{ validator: longitudePass, trigger: 'blur' }],
    latitude: [{ validator: latitudePass, trigger: 'blur' }],
})

const editAddDeviceDialog = ref(false)
const modifyAddDeviceDetails = ref()
const saveAddData = () => {
    modifyAddDeviceDetails.value.validate((valid: any) => {
        if (valid) {
            deviceTypeList.value.forEach((ele: any) => {
                if (ele.equipmentTypeName === editAddDeviceData.objectType) {
                    editAddDeviceData.objectType = ele.equipmentTypeId
                }
            })
            equipAdd(editAddDeviceData)
                .then((res) => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        deviceQuery(formQuery)
                    } else {
                        ElMessage.error({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                })
                .catch((err) => {
                    ElMessage.error({
                        message: err.response?.data?.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.equipmentTypeId, 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({ objectType: queryParameter.value.equipmentTypeId }).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)
    })
}

const showControlPage = ref(false)
const contorlData = reactive({
    deviceId: '',
    iotModelId: '',
})
const openControl = (data: any) => {
    contorlData.deviceId = data.row.id
    contorlData.iotModelId = data.row.iotModelId
    if (contorlData.iotModelId) {
        showControlPage.value = true
    } else {
        ElMessage.warning('该设备没有绑定物模型！')
    }
}

const measureData = reactive<{
    deviceId: string
    iotModelId: string
    autoUpdate: boolean
    measureType: ModelAttributeType
    madeinFactory: string
    model: string
}>({
    deviceId: '',
    iotModelId: '',
    autoUpdate: false,
    measureType: 138,
    madeinFactory: '',
    model: '',
})
const showMeasure = ref(false)
const openMeasure = (data: any) => {
    measureData.deviceId = data.row.id
    measureData.iotModelId = data.row.iotModelId
    measureData.madeinFactory = data.row.madeinFactory
    measureData.model = data.row.model
    if (measureData.iotModelId) {
        showMeasure.value = true
    } else {
        ElMessage.warning('该设备没有绑定物模型！')
    }
}

watch(showMeasure, (newVal: boolean) => {
    !newVal && (measureData.autoUpdate = false)
})

getModelList()
</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;
                        }
                    }
                }
            }
        }
    }
}
.measureSlotHeader {
    display: flex;
    .measureSlotHeaderRight {
        margin-left: 20px;
    }
    .measureTabs {
        margin-left: auto;
    }
}
</style>
