<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import Page from '@/components/Pagination/page.vue'
import { ElMessageBox, ElMessage, ElTable, FormRules, ElTree } from 'element-plus'
import { getDeviceByType } from '@/api/device'
import { queryDevice, addDevice, updateDevice, deleteDeviceById, deleteDeviceByIds, updateDeviceByIds } from '@/api/auxiliarymanage/index';
import { getGatewayList } from '@/api/systemmanage'
import Eldialog from '@/components/seccmsdialog/eldialog.vue'
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
//树形控件类型定义
interface Tree {
    [x: string]: any;
    label: string;
    children?: Tree[];
}
const ruleFormRef: any = ref(null);
const equipform: any = ref({})
const rules = reactive<FormRules>({
    deviceName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
    deviceCode: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
    deviceType: [{ required: true, message: '请选择设备类型', trigger: 'change', }]
});
const queryInfo: any = ref({
    current: 1,
    size: 15,
    total: 0
})
const queryparams: any = ref({
    deviceModel: '',
    deviceType: '',
    status: '',
    deviceName: ''
})
const typeoptions: any = ref([])
const regionoptions: any = ref([])

const statusoptions: any = ref([])
const multipleSelection = ref([])
const loading = ref(false)
const tableData: any = ref([])
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}
const dialogVisible = ref(false)
const dialogtitle = ref('新增辅控设备')

const defaultProps = { label: "dictname" };
const checktreenode: any = ref({})
const handleNodeClick = (data: Tree) => {
    queryInfo.value.current = 1
    queryInfo.value.size = 15
    queryparams.value.deviceName = ''
    queryparams.value.deviceModel = ''
    queryparams.value.deviceType = ''
    queryparams.value.status = ''
    checktreenode.value.code = data.itemcode
    checktreenode.value.id = data.id
    checktreenode.value.name = data.dictname
    getData();
};
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData: any = ref([])
const treeloading = ref(false)
const vMove = {
    mounted(el: any) {
        el.onmousedown = function (e: any) {
            var init = e.clientX;
            var parent: any = document.getElementById("silderLeft");
            const initWidth: any = parent.offsetWidth;
            document.onmousemove = function (e) {
                var end = e.clientX;
                var newWidth = end - init + initWidth;
                parent.style.width = newWidth + "px";
            };
            document.onmouseup = function () {
                document.onmousemove = document.onmouseup = null;
            };
        };
    }
}
const temDeviceData: any = ref([]) // 列表
function getSystemDevice() {
    getGatewayList({stationId:userStore.stationId}).then((res: any) => {
        temDeviceData.value = res.data
    })
}
function correlationSubmit() {
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
        id.push(item.deviceId)
    })
    let params = {
        ids: id,
        ip: equipform.value.netdeviceIp
    };
    updateDeviceByIds(params).then((res: any) => {
        ElMessage({
            message: "关联成功",
            type: "success",
        });
        correlationVisible.value = false
        getData()
    })
}
onMounted(() => {
    init()
    queryselect()
})
function init() {
    const params = {
        dictcode: 'system'
    }
    treeloading.value = true
    getDeviceByType(params).then((res: any) => {
        if (res.data.length !== 0 && res.data !== null) {
            treeData.value = res.data
            treeloading.value = false
            if (res.data.length !== 0 && res.data !== null) {
                nextTick(() => {
                    treeRef.value?.setCurrentKey(res.data[0].id);
                    checktreenode.value.code = res.data[0].itemcode
                    checktreenode.value.name = res.data[0].dictname
                    getData();
                });
            }
        }
    })
}
function queryselect() {
    const statusparams = {
        dictcode: 'deviceStatus'
    }
    getDeviceByType(statusparams).then((res: any) => {
        statusoptions.value = res.data
    })
    const deviceTypeparams = {
        dictcode: 'deviceType'
    }
    getDeviceByType(deviceTypeparams).then((ress: any) => {
        typeoptions.value = ress.data
    })
    getDeviceByType({ dictcode: 'deviceArea' }).then((ress: any) => {
        regionoptions.value = ress.data
    })

}
function getData() {
    loading.value = true
    const params = {
        systemcode: checktreenode.value.code,
        current: queryInfo.value.current,
        size: queryInfo.value.size,
        deviceName: queryparams.value.deviceName,
        deviceModel: queryparams.value.deviceModel,
        deviceType: queryparams.value.deviceType,
        status: queryparams.value.status
    }
    queryDevice(params).then((res: any) => {
        tableData.value = res.data.records
        queryInfo.value.total = res.data.total
        loading.value = false
    })
}
function editclick(row: any) {
    isSwitch.value = false
    dialogtitle.value = '修改辅控设备'
    getSystemDevice()
    equipform.value = JSON.parse(JSON.stringify(row))
    dialogVisible.value = true
}
function delclick(row: any) {
    ElMessageBox.confirm("确定删除此辅控设备信息吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let params = {
            id: row.deviceId
        };
        deleteDeviceById(params).then((res: any) => {
            ElMessage({
                message: "删除成功",
                type: "success",
            });
            getData()
        });
    }).catch(() => { })
}
function delclicks() {
    ElMessageBox.confirm("确定删除选择辅控设备信息吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let id = [] as any[];
        multipleSelection.value.forEach((item: any) => {
            id.push(item.deviceId)
        })
        let params = {
            ids: id.join(','),
        };
        deleteDeviceByIds(params).then((res: any) => {
            ElMessage({
                message: "删除成功",
                type: "success",
            });
            getData()
        });
    }).catch(() => { })
}
function addclick() {
    if (ruleFormRef.value != null) ruleFormRef.value.resetFields();
    isSwitch.value = false
    equipform.value = {}
    equipform.value.systemcode = checktreenode.value.code
    equipform.value.status = '02'
    dialogtitle.value = '新增辅控设备'
    getSystemDevice()
    dialogVisible.value = true
}
const isSwitch = ref(false)
function formsubmit(formEl: any) {
    formEl.validate((valid: any) => {
        if (valid) {
            if (isSwitch.value == true) {
                return
            }
            isSwitch.value = true
            loading.value = true
            equipform.value.stationId = userStore.stationId
            if (equipform.value.deviceId) {
                updateDevice(equipform.value).then((res: any) => {
                    ElMessage({
                        message: "修改成功",
                        type: "success",
                    });
                    isSwitch.value = false
                    dialogVisible.value = false
                    loading.value = false
                    getData()
                }).catch(() => {
                    isSwitch.value = false
                    loading.value = false
                })
            } else {
                addDevice(equipform.value).then((res: any) => {
                    ElMessage({
                        message: "新增成功",
                        type: "success",
                    });
                    isSwitch.value = false
                    dialogVisible.value = false
                    loading.value = false
                    getData()
                }).catch(() => {
                    isSwitch.value = false
                    loading.value = false
                })
            }
        }
    })
}
function handleClose() {
    if (ruleFormRef.value != null) ruleFormRef.value.resetFields();
    dialogVisible.value = false
    correlationVisible.value = false
}
function dateFormat(row: any) { // 时间方法
    const daterc = row;
    if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    }
}
function resetData() {
    queryInfo.value.current = 1
    queryInfo.value.size = 10
    queryparams.value.deviceName = ''
    queryparams.value.deviceModel = ''
    queryparams.value.deviceType = ''
    queryparams.value.status = ''
    getData()
}
const correlationVisible = ref(false)
function correlationClick() {
    equipform.value = {
        netdeviceIp: ""
    }
    getSystemDevice()
    correlationVisible.value = true
}
const tableRowClassName = ({
    row,
    rowIndex,
}: {
    row: any
    rowIndex: number
}) => {
    if (rowIndex % 2 === 0) {
        return 'warning-row'
    } else if (rowIndex % 2 === 1) {
        return 'success-row'
    }
    return ''
}
</script>
<template>
    <div class="faulttemplate-box">
        <aside id="silderLeft">
            <el-tree v-loading="treeloading" ref="treeRef" node-key="id" :data="treeData" :highlight-current="true"
                :props="defaultProps" :expand-on-click-node="false" @node-click="handleNodeClick"
                style="height: calc(100vh - 175px); overflow: auto;margin-top: 10px;">
            </el-tree>
            <div class="moveBtn" v-move>
                <div class="moveBtn-line"></div>
            </div>
        </aside>
        <section class="silderRight">
            <el-row>
                <el-col :span="24">
                    <div
                        style="margin-bottom:10px;display: flex;display: -webkit-flex; justify-content: space-between;-webkit-justify-content: space-between; width: 100%;">
                        <div>
                            <el-input v-model="queryparams.deviceName" placeholder="请输入设备名称" style="width: 220px;"
                                clearable />
                            <el-input v-model="queryparams.deviceModel" placeholder="请输入设备型号"
                                style="width: 220px;margin-left: 10px;" clearable />
                            <el-select v-model="queryparams.deviceType" placeholder="请选择设备类型"
                                style="width: 220px;margin-left: 10px;" clearable>
                                <el-option v-for="item in typeoptions" :key="item.itemcode" :label="item.dictname"
                                    :value="item.itemcode" />
                            </el-select>
                            <el-button class="searchButton" type="primary" style="margin-left: 10px;" @click="getData">搜索</el-button>
                            <el-button class="searchButton" style="margin-left: 10px;" @click="resetData">重置</el-button>
                        </div>
                        <div>
                            <el-button class="searchButton" :disabled="multipleSelection.length <= 0 ? true : false" type="primary"
                                style="margin-left: 10px;" @click="correlationClick">关联网关设备IP</el-button>
                            <el-button class="searchButton" type="primary" style="margin-left: 10px;"
                                @click="addclick">新增</el-button>
                            <el-button class="searchButton" :disabled="multipleSelection.length <= 0 ? true : false"
                                 style="margin-left: 10px;" @click="delclicks">删除</el-button>
                        </div>
                    </div>
                </el-col>
            </el-row>
            <el-table ref="multipleTableRef" :data="tableData" style="width: 100%;margin-bottom: 20px;height: calc(78vh);
                      overflow: auto;" row-key="id" default-expand-all :v-loading="loading"
                @selection-change="handleSelectionChange" :row-class-name="tableRowClassName"
                :header-cell-style="{ background: '#002b6a', color: '#B5D7FF', height: '50px' }">
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column label="设备编号" prop="deviceCode" width="80" />
                <el-table-column label="设备名称" prop="deviceName" />
                <el-table-column label="设备类型" prop="deviceTypeName" width="170" />
                <el-table-column label="设备型号" prop="deviceModel" width="170" />
                <el-table-column label="出厂编号" prop="productionNum" width="150" />
                <el-table-column label="出厂日期" prop="productionDate" width="160">
                    <template #default="scope">
                        <span>{{ dateFormat(scope.row.productionDate) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="安装位置" prop="place" />
                <el-table-column label="网关设备IP" prop="netdeviceIp" width="120" />
                <el-table-column fixed="right" label="操作" width="80">
                    <template #default="scope">
                        <span
                            style="display: flex;display: -webkit-flex;justify-content: space-around; -webkit-justify-content: space-around; ">
                            <img  src="@/assets/newimg/ht_xg.png"  title="修改"
                                style="cursor: pointer;" @click="editclick(scope.row)">
                            <img src="@/assets/newimg/ht_sc.png"  title="删除"
                                style="cursor: pointer;" @click="delclick(scope.row)">
                        </span>
                    </template>
                </el-table-column>
            </el-table>
            <Page class="mt-[20px]" :total="queryInfo.total" v-model:size="queryInfo.size"
                v-model:current="queryInfo.current" @pagination="getData" />
        </section>
        <Eldialog v-if="dialogVisible" :title="dialogtitle" :zIndex="2000" :width="'50%'" @before-close="handleClose">
            <template v-slot:PopFrameContent>
                <el-form ref="ruleFormRef" :rules="rules" :model="equipform" label-width="120px" style="margin-top:15px ;">
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="所属系统">
                                <el-input v-model="checktreenode.name" disabled clearable />
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="设备编号" prop="deviceCode">
                                <el-input v-model="equipform.deviceCode" maxlength="40" show-word-limit
                                    placeholder="请输入设备编号" clearable />
                            </el-form-item>
                        </div>
                    </div>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="设备名称" prop="deviceName">
                                <el-input v-model="equipform.deviceName" maxlength="100" show-word-limit
                                    placeholder="请输入设备名称" clearable />
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="设备类型" prop="deviceType">
                                <el-select v-model="equipform.deviceType" placeholder="请选择设备类型"  style="width: 100%;" >
                                    <el-option v-for="item in typeoptions" :key="item.itemcode" :label="item.dictname"
                                        :value="item.itemcode" />
                                </el-select>
                            </el-form-item>
                        </div>
                    </div>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="中文描述">
                                <el-input v-model="equipform.deviceDesc" maxlength="100" show-word-limit
                                    placeholder="请输入设备编号" clearable />
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="设备型号">
                                <el-input v-model="equipform.deviceModel" maxlength="100" show-word-limit
                                    placeholder="请输入设备型号" clearable />
                            </el-form-item>
                        </div>
                    </div>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="出厂编号">
                                <el-input v-model="equipform.productionNum" maxlength="40" show-word-limit
                                    placeholder="请输入出厂编号" clearable />
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="出厂日期">
                                <el-date-picker v-model="equipform.productionDate" show-word-limit type="date"
                                    style="width:100%" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                                    placeholder="请输入出厂日期" />
                            </el-form-item>
                        </div>
                    </div>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="生产厂家">
                                <el-input v-model="equipform.manufacturer" maxlength="100" show-word-limit
                                    placeholder="请输入生产厂家" clearable />
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="生产国家">
                                <el-input v-model="equipform.madein" maxlength="100" show-word-limit
                                    placeholder="请输入生产国家" clearable />
                            </el-form-item>
                        </div>
                    </div>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="实物ID">
                                <el-input v-model="equipform.phyassetId" maxlength="40" show-word-limit
                                    placeholder="请输入实物ID" clearable />
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="区域标识">
                                <!-- <el-input v-model="equipform.region" maxlength="40" show-word-limit placeholder="请输入区域标识" clearable /> -->
                                <el-select style="width: 100%;" v-model="equipform.region" placeholder="请选择区域标识 ">
                                    <el-option v-for="item in regionoptions" :key="item.itemcode" :label="item.dictname"
                                        :value="item.itemcode" />
                                </el-select>
                            </el-form-item>
                        </div>
                    </div>
                    <el-form-item label="安装位置">
                        <el-input v-model="equipform.place" maxlength="100" show-word-limit placeholder="请输入安装位置"
                            clearable />
                    </el-form-item>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="以太网Mac地址">
                                <el-input v-model="equipform.macAddr" maxlength="40" show-word-limit
                                    placeholder="请输入以太网Mac地址" clearable />
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="以太网IP地址">
                                <el-input v-model="equipform.ipAddr" maxlength="40" show-word-limit
                                    placeholder="请输入以太网IP地址" clearable />
                            </el-form-item>
                        </div>
                    </div>
                    <el-form-item label="对应网关设备IP">
                        <el-select style="width: 100%;" v-model="equipform.netdeviceIp" placeholder="请选择对应网关设备IP" clearable filterable>
                            <el-option v-for="item in temDeviceData" :key="item.ipAddr"
                                :label="item.deviceName + ' - ' + item.ipAddr" :value="item.ipAddr" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <span class="dialog-footer" style="display: flex;justify-content: flex-end;">
                    <el-button class="searchButton" @click="handleClose">取消</el-button>
                    <el-button class="searchButton" type="primary" @click="formsubmit(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </Eldialog>
        <Eldialog v-if="correlationVisible" :title="'关联设备网关IP'" :zIndex="2000" :width="'600px'"
            @before-close="handleClose">
            <template v-slot:PopFrameContent>
                <el-form :model="equipform" label-width="120px" style="margin-top: 15px;">
                    <el-form-item label="对应网关设备IP">
                        <el-select style="width: 100%;" v-model="equipform.netdeviceIp" placeholder="请选择对应网关设备IP" clearable filterable>
                            <el-option v-for="item in temDeviceData" :key="item.ipAddr"
                                :label="item.deviceName + ' - ' + item.ipAddr" :value="item.ipAddr" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <span class="dialog-footer" style="display: flex;justify-content: flex-end;">
                    <el-button class="searchButton" @click="handleClose">取消</el-button>
                    <el-button class="searchButton" type="primary" @click="correlationSubmit">确定</el-button>
                </span>
            </template>
        </Eldialog>

    </div>
</template>

<style scoped lang="scss">
.looknum {
    cursor: pointer;
}

.silderLeft-default {
    :deep(.el-tree-node__label) {
        font-size: 16px !important;
    }
}

.faulttemplate-box {
    height: 100%;
    display: flex;
    display: -webkit-flex;
    background-color: #f2f4f900;
    padding: 15px 15px 0px 15px;

}

#silderLeft {
    width: 300px;
    padding: 5px 0px 10px;
    box-sizing: border-box;
    border-radius: 3px;
    position: relative;
    background: url(@/assets/navigation/ty_260x988.png);
    background-size: 100% 100%;

    &:hover {
        .moveBtn {
            opacity: 1;
        }
    }
}

/* 拖动条 */
.moveBtn {
    height: 100%;
    width: 15px;
    padding: 0 6px;
    opacity: 0;
    position: absolute;
    right: -15px;
    top: 0;
}

.moveBtn-line {
    width: 100%;
    height: 100%;
    cursor: col-resize;
    user-select: none;
    background-color: #60bfff;
}

.silderRight {
    flex: 1;
    width: 100%;
    height: calc(100vh - 160px);
    overflow: auto;
    background-color: rgba(255, 255, 255, 0);
    border-radius: 3px;
    padding: 15px;
    padding-bottom: 0px;
    box-sizing: border-box;
    margin-left: 15px;
    background: url(@/assets/newimg/cjrw_1890.png);
    background-size: 100% 100%;
}

.avatar {
    width: 86px;
    height: 86px;
    display: block;
}

:deep(.el-tree-node.is-current>.el-tree-node__content) {
    width: 100%;
    height: 40px;
    // color: #fff !important;
}

:deep(.el-tree) {
    background-color: #ffffff00 !important;
    --el-tree-node-hover-bg-color: #0099ff09;
}



:deep(.el-tree-node__content) {
    width: 100% !important;
    height: 40px !important;
    margin: auto !important;
}

.el-message-box {
    width: 300px !important;
}

:deep(.el-table:not(.el-table--border) .el-table__cell) {
    border: none;
    color: #fff;
}

:deep(.el-tree) {
    background-color: #ffffff00 !important;
    --el-tree-node-hover-bg-color: #0099ff09;
}

:deep(.el-input) {
    --el-input-bg-color: #ffffff00 !important;
}

:deep(.el-input-group__append) {
    background: #ffffff00 !important;
}
:deep(.el-input .el-input__count .el-input__count-inner){
    background-color: rgba(240, 248, 255, 0);
}
</style>