<template>
    <div class="DeviceModel">
        <el-dialog v-model="modelDialogVisible" :title="modelDialogTitle" :width="400" @close="cancelModelForm">
            <el-form ref="modelFormRef" :model="modelForm" :rules="modelFormRules" label-width="110">
                <el-form-item prop="iotModelName" :label="ModelFieldsEnums['iotModelName']">
                    <el-input
                        :disabled="modelDialogState === ModelDialogTitleStateType['detail']"
                        v-model="modelForm.iotModelName"
                        :placeholder="'请输入' + ModelFieldsEnums['iotModelName']"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="iotModelCode" :label="ModelFieldsEnums['iotModelCode']">
                    <el-input
                        :disabled="modelDialogState === ModelDialogTitleStateType['detail']"
                        v-model="modelForm.iotModelCode"
                        :placeholder="'请输入' + ModelFieldsEnums['iotModelCode']"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="objectType" :label="ModelFieldsEnums['objectType']">
                    <el-select
                        :disabled="modelDialogState === ModelDialogTitleStateType['detail']"
                        v-model="modelForm.objectType"
                        :placeholder="'请选择' + ModelFieldsEnums['objectType']"
                    >
                        <el-option
                            v-for="item in deviceTypeList"
                            :key="item.equipmentTypeId"
                            :label="item.equipmentTypeName"
                            :value="item.equipmentTypeId"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer v-if="modelDialogState !== ModelDialogTitleStateType['detail']">
                <el-button type="primary" @click="submitModelForm">提交</el-button>
                <el-button @click="cancelModelForm">取消</el-button>
            </template>
        </el-dialog>
        <el-container class="containerPart">
            <el-aside class="asidePart">
                <el-header class="asideHeader">
                    <el-input
                        v-model="searchModelValue"
                        :suffix-icon="Search"
                        clearable
                        @input="debounceSearchModel"
                        placeholder="请输入模型名称"
                        class="searchModelInput"
                    ></el-input>
                </el-header>
                <el-main class="treeMain">
                    <el-tree
                        ref="modelTreeRef"
                        node-key="id"
                        :data="treeData"
                        :props="DeviceModelPropReplace"
                        class="treePart"
                        @node-contextmenu="modelContextMenu"
                        @node-click="modelNodeClick"
                        highlight-current
                    >
                    </el-tree>
                </el-main>
            </el-aside>
            <el-container class="mainContainer">
                <el-header class="mainHeader">
                    <div class="mainHeaderCenter">
                        <el-input
                            clearable
                            class="modelAttributeSearchInput"
                            v-model="modelAttributeAndServiceInputValue"
                            :placeholder="modelAttributeAndServiceInputPlaceHolder"
                        ></el-input>
                        <el-radio-group v-model="modelAttributeSearchRadio">
                            <el-radio value="Name">名称</el-radio>
                            <el-radio value="Code">编码</el-radio>
                        </el-radio-group>
                        <el-button :icon="Search" type="primary" @click="searchModelAttribute">查询</el-button>
                    </div>
                    <div class="mainHeaderRight">
                        <el-button :icon="Plus" type="primary" @click="addModelAttributeAndService">新增</el-button>
                        <el-upload :show-file-list="false" :limit="1" :http-request="upLoadModel">
                            <template #trigger>
                                <el-button :icon="Upload">导入</el-button>
                            </template>
                        </el-upload>
                        <el-button :icon="Download" @click="downLoadModel">导出</el-button>
                    </div>
                </el-header>
                <el-main class="mainMain">
                    <el-tabs v-model="ModelTabs" @tab-change="changeTabs" class="tabsPart">
                        <el-tab-pane :label="modelTabsType['attribute']" name="attribute">
                            <el-table :data="attributeTableData" class="tablePart" highlight-current-row>
                                <el-table-column
                                    prop="attributeName"
                                    :label="ModelAttributeFieldsEnums['attributeName']"
                                    align="center"
                                ></el-table-column>
                                <el-table-column
                                    prop="attributeCode"
                                    :label="ModelAttributeFieldsEnums['attributeCode']"
                                    align="center"
                                ></el-table-column>
                                <el-table-column
                                    prop="attributeTypeName"
                                    :label="ModelAttributeFieldsEnums['attributeTypeName']"
                                    align="center"
                                ></el-table-column>
                                <el-table-column prop="porder" :label="ModelAttributeFieldsEnums['porder']" align="center"></el-table-column>
                                <el-table-column fixed="right" label="操作" min-width="80" align="center">
                                    <template #default="scope">
                                        <div class="tableOperate">
                                            <a @click="editAttributeForm(scope.row)">编辑</a>
                                            <a>|</a>
                                            <el-popconfirm title="确定删除么？" @confirm="delAttributeForm(scope.row)">
                                                <template #reference>
                                                    <a>删除</a>
                                                </template>
                                            </el-popconfirm>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane :label="modelTabsType['service']" name="service">
                            <el-table :data="serviceTableData" class="tablePart">
                                <el-table-column prop="serviceName" :label="ModelServiceFieldsEnums['serviceName']" align="center"></el-table-column>
                                <el-table-column prop="serviceCode" :label="ModelServiceFieldsEnums['serviceCode']" align="center"></el-table-column>
                                <el-table-column
                                    prop="serviceTypeName"
                                    :label="ModelServiceFieldsEnums['serviceTypeName']"
                                    align="center"
                                ></el-table-column>
                                <el-table-column prop="porder" :label="ModelServiceFieldsEnums['porder']" align="center"></el-table-column>
                                <el-table-column fixed="right" label="操作" min-width="80" align="center">
                                    <template #default="scope">
                                        <div class="tableOperate">
                                            <a @click="editServiceForm(scope.row)">编辑</a>
                                            <a>|</a>
                                            <el-popconfirm title="确定删除么？" @confirm="delServiceForm(scope.row)">
                                                <template #reference>
                                                    <a>删除</a>
                                                </template>
                                            </el-popconfirm>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="mainFooter">
                        <el-pagination
                            v-model:current-page="currentPage"
                            v-model:page-size="currentPageSize"
                            :total="pageTotal"
                            :page-sizes="pagePagination"
                            background
                            :pager-count="7"
                            layout="prev, pager, next, jumper,sizes,total"
                            @change="getcurrentPage"
                        ></el-pagination>
                    </div>
                </el-main>
            </el-container>
        </el-container>
        <ContextMenu :pos="contextMenuPos" v-model:visible="modelOperateVisible">
            <template #default>
                <div class="modelOperate">
                    <el-button @click="openModel('detail', curContextMenuTreeData)" :icon="Reading">查看</el-button>
                    <el-button @click="openModel('add')" :icon="DocumentAdd">新增</el-button>
                    <el-button @click="openModel('edit', curContextMenuTreeData)" :icon="DocumentChecked">修改</el-button>
                    <el-popconfirm title="确认删除？" @confirm="delModel">
                        <template #reference>
                            <el-button :icon="DocumentDelete" @click.stop>删除</el-button>
                        </template>
                    </el-popconfirm>
                </div>
            </template>
        </ContextMenu>
        <el-dialog v-model="attributeVisible" :title="attributeFormTitle" @close="closeAttributeForm" :width="600">
            <el-form ref="attributeFormRef" :model="attributeForm" label-width="100" :rules="attributeAndServiceRules">
                <el-form-item :label="ModelAttributeFieldsEnums['attributeName']" prop="attributeName">
                    <el-input v-model="attributeForm.attributeName" :placeholder="'请输入' + ModelAttributeFieldsEnums['attributeName']"></el-input>
                </el-form-item>
                <el-form-item :label="ModelAttributeFieldsEnums['attributeCode']" prop="attributeCode">
                    <el-input v-model="attributeForm.attributeCode" :placeholder="'请输入' + ModelAttributeFieldsEnums['attributeCode']"></el-input>
                </el-form-item>
                <el-form-item :label="ModelAttributeFieldsEnums['attributeTypeName']" prop="attributeType">
                    <el-select v-model="attributeForm.attributeType" :placeholder="'请选择' + ModelAttributeFieldsEnums['attributeTypeName']">
                        <el-option label="模拟量" :value="138"></el-option>
                        <el-option label="累积量" :value="139"></el-option>
                        <el-option label="离散量" :value="140"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="ModelAttributeFieldsEnums['porder']" prop="porder">
                    <el-input v-model="attributeForm.porder" :placeholder="'请输入' + ModelAttributeFieldsEnums['porder']"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="submitAttributeForm">提交</el-button>
                <el-button @click="closeAttributeForm">取消</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="serviceVisible" :title="serviceFormTitle" @close="closeServiceForm" :width="600">
            <el-form ref="serviceFormRef" :model="serviceForm" label-width="100" :rules="attributeAndServiceRules">
                <el-form-item :label="ModelServiceFieldsEnums['serviceName']" prop="serviceName">
                    <el-input v-model="serviceForm.serviceName" :placeholder="'请输入' + ModelServiceFieldsEnums['serviceName']"></el-input>
                </el-form-item>
                <el-form-item :label="ModelServiceFieldsEnums['serviceCode']" prop="serviceCode">
                    <el-input v-model="serviceForm.serviceCode" :placeholder="'请输入' + ModelServiceFieldsEnums['serviceCode']"></el-input>
                </el-form-item>
                <el-form-item :label="ModelServiceFieldsEnums['serviceTypeName']" prop="serviceType">
                    <el-select v-model="serviceForm.serviceType" :placeholder="'请选择' + ModelServiceFieldsEnums['serviceTypeName']">
                        <el-option label="遥调" :value="146"></el-option>
                        <el-option label="遥控" :value="147"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="ModelServiceFieldsEnums['porder']" prop="porder">
                    <el-input v-model="serviceForm.porder" :placeholder="'请输入' + ModelServiceFieldsEnums['porder']"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="submitServiceForm">提交</el-button>
                <el-button @click="closeServiceForm">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import {
    ElContainer,
    ElAside,
    ElHeader,
    ElMain,
    ElTree,
    ElInput,
    ElMessage,
    ElRadioGroup,
    ElRadio,
    ElButton,
    ElTabs,
    ElTabPane,
    ElTable,
    ElUpload,
    FormInstance,
    UploadRequestOptions,
    TreeNode,
    TreeInstance,
} from 'element-plus'
import { Reading, DocumentAdd, DocumentChecked, DocumentDelete, Search, Plus, Download, Upload } from '@element-plus/icons-vue'
import {
    ModelFieldsEnums,
    AddModelType,
    UpdateModelType,
    ModelDialogTitleStateType,
    ModelDialogTitleStateValueType,
    ModelDialogTitleStateKeyType,
    radioGroupType,
    modelTabsTypeKeyType,
    modelTabsType,
    AddModelAttributeType,
    UpdateModelAttributeType,
    UpdateModelServiceType,
    AddModelServiceType,
    ModelAttributeFieldsEnums,
    ModelAttributeTableType,
    ModelServiceTableType,
    ModelServiceFieldsEnums,
    AttributeDialogTitleStateType,
    serviceDialogTitleStateType,
    GetModelServiceType,
    GetModelAttributeType,
    DeviceType,
} from './type'
import {
    getModelListReq,
    addModelReq,
    updateModelReq,
    delModelReq,
    getModelAttributeListReq,
    addModelAttributeReq,
    updateModelAttributeReq,
    delModelAttributeReq,
    getModelServiceListReq,
    addModelServiceReq,
    updateModelServiceReq,
    delModelServiceReq,
    downloadModelReq,
    uploadModelReq,
    getDeviceTypeEnumReq,
} from '/@/api/backend/deviceModel/request'
import ContextMenu from './contextMenu.vue'
import { encrypt_aes, generateRandomNumber } from '/@/utils/crypto'
import { debounce } from 'lodash'

const DeviceModelPropReplace = {
    label: 'iotModelName',
}
const modelTreeRef = ref<TreeInstance>()
const treeData = ref<(AddModelType & UpdateModelType)[]>([])
const originTreeData = ref<(AddModelType & UpdateModelType)[]>([])

const searchModelValue = ref('')
const searchModel = () => {
    if (searchModelValue.value === '') {
        treeData.value = originTreeData.value
        return
    }
    const reg = new RegExp(searchModelValue.value)
    const result = []
    for (let item of originTreeData.value) {
        if (reg.test(item.iotModelName)) {
            result.push(item)
        }
    }
    treeData.value = result
}
const debounceSearchModel = debounce(searchModel, 100)
const modelFormRef = ref<FormInstance>()
const modelDialogVisible = ref(false)
const modelDialogState = ref<ModelDialogTitleStateValueType>(ModelDialogTitleStateType['detail'])
const modelDialogTitle = computed(() => {
    return modelDialogState.value === ModelDialogTitleStateType['detail']
        ? '查看物模型'
        : modelDialogState.value === ModelDialogTitleStateType['edit']
          ? '新增物模型'
          : '编辑物模型'
})
const originModelForm: AddModelType & UpdateModelType = {
    iotModelName: '',
    objectType: null,
    iotModelCode: '',
    revision: 1,
    createdBy: undefined,
    createdTime: undefined,
    updatedBy: undefined,
    updatedTime: undefined,
    id: null,
}

const modelForm = ref<AddModelType & UpdateModelType>(JSON.parse(JSON.stringify(originModelForm)))
const modelFormRules = {
    iotModelName: [{ required: true, message: '请输入物模型名称', trigger: 'blur' }],
    iotModelCode: [{ required: true, message: '请输入物模型编码', trigger: 'blur' }],
    objectType: [{ required: true, message: '请选择物模型类型', trigger: 'blur' }],
}
const submitModelForm = () => {
    if (modelDialogState.value === ModelDialogTitleStateType['add']) {
        addModelReq(modelForm.value)
            .then((res) => {
                if (res.success) {
                    ElMessage.success('新增物模型成功')
                    modelDialogVisible.value = false
                    getModelList()
                } else {
                    ElMessage.error(res.msg)
                }
            })
            .catch((err) => {
                ElMessage.error(err?.response?.data?.msg ?? '新增失败')
            })
    } else if (modelDialogState.value === ModelDialogTitleStateType['edit']) {
        updateModelReq(modelForm.value)
            .then((res) => {
                if (res.success) {
                    ElMessage.success('修改物模型成功')
                    modelDialogVisible.value = false
                    getModelList()
                } else {
                    ElMessage.error(res.msg)
                }
            })
            .catch((err) => {
                ElMessage.error(err?.response?.data?.msg ?? '修改失败')
            })
    }
}
const getModelList = (name?: string) => {
    return new Promise((resolve) => {
        getModelListReq({ iotModelName: name })
            .then((res) => {
                if (res.success) {
                    originTreeData.value = res.data!
                    treeData.value = res.data!
                    resolve(res.data![0])
                } else {
                    ElMessage.error(res.msg)
                }
            })
            .catch((err) => {
                ElMessage.error(err?.response?.data?.msg ?? '查询失败')
            })
    })
}
const cancelModelForm = () => {
    modelForm.value = JSON.parse(JSON.stringify(originModelForm))
    modelFormRef.value?.resetFields()
    modelDialogVisible.value = false
}
const deviceTypeList = ref<DeviceType[]>([])

const modelOperateVisible = ref(false)
const contextMenuPos = ref({
    x: 0,
    y: 0,
})
const curContextMenuTreeData = ref<AddModelType & UpdateModelType>()
const modelContextMenu = (event: any, data: TreeNode) => {
    contextMenuPos.value.x = event.pageX
    contextMenuPos.value.y = event.pageY
    curContextMenuTreeData.value = JSON.parse(JSON.stringify(data))
    modelOperateVisible.value = true
}
const modelNodeClick = (target: TreeNode) => {
    curContextMenuTreeData.value = JSON.parse(JSON.stringify(target))
    if (ModelTabs.value === 'attribute') {
        getAttributeList()
    } else {
        getServiceList()
    }
}
const openModel = (type: ModelDialogTitleStateKeyType, data?: AddModelType & UpdateModelType) => {
    modelDialogState.value = ModelDialogTitleStateType[type]
    if (type !== 'add') {
        modelForm.value = JSON.parse(JSON.stringify(data!))
    }
    // modelOperateVisible.value = false
    modelDialogVisible.value = true
}
const delModel = () => {
    delModelReq({ id: curContextMenuTreeData.value!.id! })
        .then((res) => {
            if (res.success) {
                ElMessage.success('删除物模型成功')
                getModelList()
                modelOperateVisible.value = false
            } else {
                ElMessage.error(res.msg)
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '删除失败')
        })
}
const modelAttributeAndServiceInputPlaceHolder = computed(() => {
    return '请输入' + (ModelTabs.value === 'attribute' ? '属性' : '方法') + (modelAttributeSearchRadio.value === 'Name' ? '名称' : '编码')
})
const modelAttributeAndServiceInputValue = ref('')
const searchModelAttribute = () => {
    if (modelAttributeSearchRadio.value === 'Name') {
        if (ModelTabs.value === 'attribute') {
            getAttributeList(modelAttributeSearchRadio.value, modelAttributeAndServiceInputValue.value)
        } else if (ModelTabs.value === 'service') {
            getServiceList(modelAttributeSearchRadio.value, modelAttributeAndServiceInputValue.value)
        }
    } else if (modelAttributeSearchRadio.value === 'Code') {
        if (ModelTabs.value === 'attribute') {
            getAttributeList(modelAttributeSearchRadio.value, modelAttributeAndServiceInputValue.value)
        } else if (ModelTabs.value === 'service') {
            getServiceList(modelAttributeSearchRadio.value, modelAttributeAndServiceInputValue.value)
        }
    }
}

const modelAttributeSearchRadio = ref<radioGroupType>('Name')

const ModelTabs = ref<modelTabsTypeKeyType>('attribute')
const changeTabs = (name: any) => {
    if (name === 'attribute') {
        getAttributeList()
    } else {
        getServiceList()
    }
}

const attributeTableData = ref<ModelAttributeTableType[]>([])
const editAttributeForm = (data: AddModelAttributeType & UpdateModelAttributeType) => {
    attributeFormTitle.value = AttributeDialogTitleStateType['edit']
    attributeForm.value = JSON.parse(JSON.stringify(data))
    attributeVisible.value = true
}
const delAttributeForm = (data: AddModelAttributeType & UpdateModelAttributeType) => {
    delModelAttributeReq({ id: data.id! })
        .then((res) => {
            if (res.success) {
                ElMessage.success('删除物模型属性成功')
                getAttributeList()
            } else {
                ElMessage.error(res.msg)
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '删除失败')
        })
}

const getAttributeList = (type?: radioGroupType, value?: string) => {
    const requestData: GetModelAttributeType = {
        iotModelId: curContextMenuTreeData.value!.id!,
        pageNum: currentPage.value,
        pageSize: currentPageSize.value,
    }
    if (type === 'Name') {
        requestData.attributeName = value
    } else if (type === 'Code') {
        requestData.attributeCode = value
    }

    getModelAttributeListReq(requestData)
        .then((res) => {
            if (res.rows && res.rows.length > 0) {
                attributeTableData.value = res.rows!.map((item) => {
                    return {
                        ...item,
                        attributeTypeName:
                            item.attributeType === 138
                                ? '模拟量'
                                : item.attributeType === 139
                                  ? '累积量'
                                  : item.attributeType === 140
                                    ? '离散量'
                                    : item.attributeType!,
                    }
                })
                pageTotal.value = res.total
            } else {
                if (res.rows && res.rows.length === 0) {
                    attributeTableData.value = []
                } else {
                    ElMessage.error(res.msg)
                }
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '查询失败')
        })
}

const getServiceList = (type?: radioGroupType, value?: string) => {
    const requestData: GetModelServiceType = {
        iotModelId: curContextMenuTreeData.value!.id!,
        pageNum: currentPage.value,
        pageSize: currentPageSize.value,
    }
    if (type === 'Name') {
        requestData.serviceName = value
    } else if (type === 'Code') {
        requestData.serviceCode = value
    }
    getModelServiceListReq(requestData)
        .then((res) => {
            if (res.rows && res.rows.length > 0) {
                serviceTableData.value = res.rows!.map((item) => {
                    return {
                        ...item,
                        serviceTypeName: item.serviceType === 146 ? '遥调' : item.serviceType === 147 ? '遥控' : item.serviceType!,
                    }
                })
                pageTotal.value = res.total
            } else {
                if (res.rows && res.rows.length === 0) {
                    serviceTableData.value = []
                } else {
                    ElMessage.error(res.msg)
                }
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '查询失败')
        })
}

const serviceTableData = ref<ModelServiceTableType[]>([])

const editServiceForm = (data: AddModelServiceType & UpdateModelServiceType) => {
    serviceFormTitle.value = serviceDialogTitleStateType['edit']
    serviceForm.value = JSON.parse(JSON.stringify(data))
    serviceVisible.value = true
}
const delServiceForm = (data: AddModelServiceType & UpdateModelServiceType) => {
    delModelServiceReq({ id: data.id! })
        .then((res) => {
            if (res.success) {
                ElMessage.success('删除物模型方法成功')
                getServiceList()
            } else {
                ElMessage.error(res.msg)
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '删除失败')
        })
}

const attributeVisible = ref(false)
const attributeFormTitle = ref(AttributeDialogTitleStateType['add'])
const originAttributeForm: AddModelAttributeType & UpdateModelAttributeType = {
    id: null,
    iotModelId: '',
    attributeCode: '',
    attributeName: '',
    attributeType: null,
    porder: null,
    revision: 1,
    createdBy: undefined,
    createdTime: undefined,
    updatedBy: undefined,
    updatedTime: undefined,
}
const attributeFormRef = ref<FormInstance>()
const attributeForm = ref<AddModelAttributeType & UpdateModelAttributeType>(JSON.parse(JSON.stringify(originAttributeForm)))

const closeAttributeForm = () => {
    attributeVisible.value = false
    attributeForm.value = JSON.parse(JSON.stringify(originAttributeForm))
    attributeFormRef.value?.resetFields()
}
const submitAttributeForm = () => {
    attributeFormRef.value?.validate((valid) => {
        if (valid) {
            if (attributeFormTitle.value === AttributeDialogTitleStateType['add']) {
                attributeForm.value.iotModelId = curContextMenuTreeData.value!.id!
                addModelAttributeReq(attributeForm.value)
                    .then((res) => {
                        if (res.success) {
                            ElMessage.success('新增物模型属性成功')
                            closeAttributeForm()
                            getAttributeList()
                        } else {
                            ElMessage.error(res.msg)
                        }
                    })
                    .catch((err) => {
                        ElMessage.error(err?.response?.data?.msg ?? '新增失败')
                    })
            } else if (attributeFormTitle.value === AttributeDialogTitleStateType['edit']) {
                updateModelAttributeReq(attributeForm.value)
                    .then((res) => {
                        if (res.success) {
                            ElMessage.success('修改物模型属性成功')
                            closeAttributeForm()
                            getAttributeList()
                        } else {
                            ElMessage.error(res.msg)
                        }
                    })
                    .catch((err) => {
                        ElMessage.error(err?.response?.data?.msg ?? '修改失败')
                    })
            }
        }
    })
}

const serviceVisible = ref(false)
const serviceFormTitle = ref(serviceDialogTitleStateType['add'])
const originServiceForm: AddModelServiceType & UpdateModelServiceType = {
    id: null,
    iotModelId: '',
    serviceCode: '',
    serviceName: '',
    serviceType: null,
    porder: null,
    revision: 1,
    createdBy: undefined,
    createdTime: undefined,
    updatedBy: undefined,
    updatedTime: undefined,
}
const serviceFormRef = ref<FormInstance>()
const serviceForm = ref<AddModelServiceType & UpdateModelServiceType>(JSON.parse(JSON.stringify(originServiceForm)))
const closeServiceForm = () => {
    serviceVisible.value = false
    serviceForm.value = JSON.parse(JSON.stringify(originServiceForm))
    serviceFormRef.value?.resetFields()
}
const submitServiceForm = () => {
    serviceFormRef.value?.validate((valid) => {
        if (valid) {
            if (serviceFormTitle.value === serviceDialogTitleStateType['add']) {
                serviceForm.value.iotModelId = curContextMenuTreeData.value!.id!
                addModelServiceReq(serviceForm.value)
                    .then((res) => {
                        if (res.success) {
                            ElMessage.success('新增物模型方法成功')
                            closeServiceForm()
                            getServiceList()
                        } else {
                            ElMessage.error(res.msg)
                        }
                    })
                    .catch((err) => {
                        ElMessage.error(err?.response?.data?.msg ?? '新增失败')
                    })
            } else if (serviceFormTitle.value === serviceDialogTitleStateType['edit']) {
                updateModelServiceReq(serviceForm.value)
                    .then((res) => {
                        if (res.success) {
                            ElMessage.success('修改物模型方法成功')
                            closeServiceForm()
                            getServiceList()
                        } else {
                            ElMessage.error(res.msg)
                        }
                    })
                    .catch((err) => {
                        ElMessage.error(err?.response?.data?.msg ?? '修改失败')
                    })
            }
        }
    })
}
const codeReg = /^[a-zA-Z][a-zA-Z0-9_]*$/
const attributeAndServiceRules = {
    attributeCode: [
        { required: true, message: '请输入属性编码', trigger: 'blur' },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (!codeReg.test(value)) {
                    callback(new Error('必须为字母开头,不能包含特殊字符'))
                } else {
                    callback()
                }
            },
            trigger: 'blur',
        },
    ],
    attributeName: [{ required: true, message: '请输入属性名称', trigger: 'blur' }],
    attributeType: [{ required: true, message: '请选择属性类型', trigger: 'change' }],
    serviceCode: [
        { required: true, message: '请输方法编码', trigger: 'blur' },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (!codeReg.test(value)) {
                    callback(new Error('必须为字母开头,不能包含特殊字符'))
                } else {
                    callback()
                }
            },
            trigger: 'blur',
        },
    ],
    serviceName: [{ required: true, message: '请输入方法名称', trigger: 'blur' }],
    serviceType: [{ required: true, message: '请选择方法类型', trigger: 'change' }],
    porder: [{ required: true, message: '请输入序号', trigger: 'blur' }],
}

const addModelAttributeAndService = () => {
    if (ModelTabs.value === 'attribute') {
        attributeVisible.value = true
    } else {
        serviceVisible.value = true
    }
}

const upLoadModel = (file: UploadRequestOptions) => {
    const formData = new FormData()
    formData.append('file', file.file)
    const v = generateRandomNumber(16)
    const id = encrypt_aes(curContextMenuTreeData.value!.id!, v)
    formData.append('id', id)
    return uploadModelReq(formData, v)
        .then((res) => {
            if (res.success) {
                ElMessage.success('上传物模型成功')
                getModelList()
            } else {
                ElMessage.error(res.msg)
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '上传失败')
        })
}

const downLoadModel = () => {
    downloadModelReq({ id: curContextMenuTreeData.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)
    })
}

const currentPage = ref(1)
const currentPageSize = ref(10)
const pageTotal = ref(0)
const pagePagination = ref([10, 20, 30])
const getcurrentPage = () => {
    if (ModelTabs.value === 'attribute') {
        getAttributeList()
    } else if (ModelTabs.value === 'service') {
        getServiceList()
    }
}

getModelList().then((res) => {
    curContextMenuTreeData.value = JSON.parse(JSON.stringify(res))
    modelTreeRef.value?.setCurrentKey(curContextMenuTreeData.value!.id!)
    if (ModelTabs.value === 'attribute') {
        getAttributeList()
    } else {
        getServiceList()
    }
})

getDeviceTypeEnumReq()
    .then((res) => {
        if (res.success) {
            deviceTypeList.value = res.data!
        } else {
            ElMessage.error(res.msg)
        }
    })
    .catch((err) => {
        ElMessage.error(err?.response?.data?.msg ?? '获取设备类型失败')
    })
</script>

<style lang="scss" scoped>
$headerHeight: 60px;
$defaultBackgroundColor: #fff;
$defaultAsideWidth: 260px;
$paginationHeight: 32px;
.DeviceModel {
    position: relative;
    width: 100%;
    height: 100%;
    .containerPart {
        width: 100%;
        height: 100%;
        .asidePart {
            width: $defaultAsideWidth;
            height: 100%;
            border-right: 1px solid #eaebed;
            .asideHeader {
                display: flex;
                justify-content: center;
                align-items: center;
                .searchModelInput {
                    height: 40px;
                }
            }
            .treeMain {
                height: calc(100% - $headerHeight);
                overflow-y: auto;
                .treePart {
                    height: 100%;
                    background-color: $defaultBackgroundColor;
                }
            }
        }
        .mainContainer {
            width: calc(100% - $defaultAsideWidth);
            height: 100%;
            .mainHeader {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: $headerHeight;
                padding: 0 20px;
                border-bottom: 1px solid #eaebed;
                .modelAttributeSearchInput {
                    height: 40px;
                    width: 220px;
                }
                .mainHeaderCenter {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 480px;
                }
                .mainHeaderRight {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 280px;
                }
                .el-button {
                    width: 88px;
                    height: 40px;
                }
            }
            .mainMain {
                height: calc(100% - $headerHeight);
                .tabsPart {
                    height: calc(100% - $paginationHeight);
                    :deep(.el-tabs__content) {
                        height: calc(100% - 55px);
                        .el-tab-pane {
                            height: 100%;
                        }
                    }
                    .tablePart {
                        height: 100%;
                    }
                    .tableOperate {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        a {
                            margin: 5px;
                            color: #0064aa;
                            font-weight: 600;
                            &:hover {
                                cursor: pointer;
                            }
                        }
                    }
                }
                .mainFooter {
                    display: flex;
                    justify-content: right;
                    background-color: #fff;
                }
            }
        }
    }
    .modelOperate {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
        width: 80px;
        height: 200px;
        .el-button {
            margin: 0;
        }
    }
}
</style>
