<template>
    <div class="default-main" style="position: relative">
        <TableHeader>
            <template #select>
                <el-form-item label="终端型号">
                    <el-select v-model="tableStore.table.params.teriminal" clearable placeholder="请选择终端型号">
                        <el-option
                            v-for="item in teriminaloption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="终端状态">
                    <el-select v-model="tableStore.table.params.teriminalstatus" clearable placeholder="请选择终端状态">
                        <el-option
                            v-for="item in teriminalstatusoption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="通讯状态">
                    <el-select v-model="tableStore.table.params.state" clearable placeholder="请选择通讯状态">
                        <el-option
                            v-for="item in stateoption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="程序版本">
                    <el-select v-model="tableStore.table.params.program" clearable placeholder="请选择程序版本">
                        <el-option
                            v-for="item in programoption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="筛选">
                    <el-input
                        v-model="tableStore.table.params.filterName"
                        @keyup="searchEvent"
                        placeholder="输入关键字筛选"
                    />
                </el-form-item>
            </template>
            <template #operation>
                <el-button icon="el-icon-Download" @click="add">导出</el-button>
                <el-button icon="el-icon-Check" @click="add">批量升级</el-button>
            </template>
        </TableHeader>
        <div :style="`height: calc(${tableStore.table.height} + 58px)`">
            <vxe-table
                v-loading="tableStore.table.loading"
                height="auto"
                auto-resize
                ref="tableRef"
                v-bind="defaultAttribute"
                :data="treeData"
                show-overflow
                :tree-config="{ transform: true, parentField: 'uPid', rowField: 'uId' }"
                :scroll-y="{ enabled: true }"
            >
                <vxe-column field="name" align="left" title="电网拓扑" min-width="200" tree-node></vxe-column>
                <vxe-column field="devType" title="终端型号" :formatter="formFilter"></vxe-column>
                <vxe-column field="versionName" title="版本号"></vxe-column>
                <vxe-column field="protocol" title="协议版本"></vxe-column>
                <vxe-column field="versionDate" title="版本日期"></vxe-column>
                <vxe-column field="runFlag" title="终端状态">
                    <template #default="{ row }">
                        <el-tag v-if="row.runFlag === 0" style="color: #fff; background: #0099cc" size="small">
                            投运
                        </el-tag>
                        <el-tag v-if="row.runFlag === 1" style="color: #fff; background: #996600" size="small">
                            检修
                        </el-tag>
                        <el-tag v-if="row.runFlag === 2" style="color: #fff; background: #A52a2a" size="small">
                            停运
                        </el-tag>
                    </template>
                </vxe-column>
                <vxe-column field="comFlag" title="通讯状态">
                    <template #default="{ row }">
                        <el-tag v-if="row.comFlag === 0" style="color: #fff; background: #A52a2a" size="small">
                            中断
                        </el-tag>
                        <el-tag v-if="row.comFlag === 1" style="color: #fff; background: #2e8b57" size="small">
                            正常
                        </el-tag>
                    </template>
                </vxe-column>
                <vxe-column field="updateBy" title="升级人员">
                    <template #default="{ row }">
                        <span v-if="row.updateBy == null || row.updateBy == '/'">--</span>
                        <span v-else>{{ row.updateBy }}</span>
                    </template>
                </vxe-column>
                <vxe-column field="updateTime" title="最新升级时间"></vxe-column>
                <vxe-column title="操作" min-width="100">
                    <template #default="{ row }">
                        <el-button v-if="row.level == 4" size="small" link @click="updateprogram(row)">升级</el-button>
                        <el-button
                            v-if="row.level == 4"
                            :disabled="row.state == 1 ? true : false"
                            size="small"
                            link
                            @click="queryview(row)"
                        >
                            日志查看
                        </el-button>
                    </template>
                </vxe-column>
            </vxe-table>
        </div>
        <el-dialog
            draggable
            v-model="dialogVisible"
            :close-on-click-modal="false"
            :title="protitle + '#终端升级日志查看'"
            width="70%"
        >
            <div :style="{ height: dialogHeight.height }">
                <vxe-table height="auto" auto-resize :data="logtableData" v-bind="defaultAttribute">
                    <vxe-column field="devTypeName" align="center" title="终端序号"></vxe-column>
                    <vxe-column field="versionId" align="center" title="版本序号"></vxe-column>
                    <vxe-column field="flag" align="center" title="版本状态" width="100">
                        <template #default="{ row }">
                            <el-tag v-if="row.flag == true" style="color: #fff; background: #fc0">前期版本</el-tag>
                            <el-tag v-if="row.flag == false" style="color: #fff; background: #0c0">当前版本</el-tag>
                        </template>
                    </vxe-column>
                    <vxe-column field="result" align="center" title="升级结果" width="100">
                        <template #default="{ row }">
                            <el-tag v-if="row.result == false" style="color: #fff; background: #f30">升级失败</el-tag>
                            <el-tag v-if="row.result == true" style="color: #fff; background: #093">升级成功</el-tag>
                        </template>
                    </vxe-column>
                    <vxe-column field="state" align="center" title="状态" width="100">
                        <template #default="{ row }">
                            <el-tag v-if="row.state == false" style="color: #fff; background: #f30">删除</el-tag>
                            <el-tag v-if="row.state == true" style="color: #fff; background: #093">正常</el-tag>
                        </template>
                    </vxe-column>
                    <vxe-column field="createBy" align="center" title="创建用户"></vxe-column>
                    <vxe-column field="createTime" align="center" title="创建时间"></vxe-column>
                    <vxe-column field="updateTime" align="center" title="升级时间"></vxe-column>
                    <vxe-column field="updateBy" align="center" title="升级人员"></vxe-column>
                </vxe-table>
            </div>
        </el-dialog>
        <!-- 升级 -->
        <el-dialog
            draggable
            v-model="prodialogVisible"
            :close-on-click-modal="false"
            :title="protitle + '#终端程序升级'"
            width="40%"
        >
            <el-col v-for="(item, index) in percentageoption" :key="index">
                <span style="font-size: 14px; font-weight: bold">{{ item.name }}</span>
                :
                <el-progress
                    :text-inside="true"
                    :stroke-width="24"
                    :percentage="item.percentage"
                    :status="item.status"
                    :format="format"
                ></el-progress>
            </el-col>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, nextTick } from 'vue'
import TableStore from '@/utils/tableStore'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import TableHeader from '@/components/table/header/index.vue'
import { mainHeight } from '@/utils/layout'
import { getTerminalUpLog } from '@/api/device-boot/Business'
import XEUtils from 'xe-utils'
import { getDevTypeList } from '@/api/device-boot/modelManage'
import { debounce } from 'lodash-es'
import { useDictData } from '@/stores/dictData'
defineOptions({
    name: 'BusinessAdministrator/TerminalManagement/ProgramManagement'
})

const pageHeight = mainHeight(83)
const dialogHeight = mainHeight(300)
const dictData = useDictData()
const teriminaloption: any = ref([])
const teriminalstatusoption = ref([
    { name: '全部', id: '' },
    { name: '投运', id: 0 },
    { name: '检修', id: 1 },
    { name: '停运', id: 2 }
])
const stateoption = ref([
    { name: '全部', id: '' },
    { name: '正常', id: 1 },
    { name: '中断', id: 0 }
])
const prodialogVisible = ref(false)
const dialogVisible = ref(false)
const protitle = ref('')
const treeData: any = ref([])
const treeDataCopy: any = ref([])
//进度条对象
const percentageoption = ref([
    {
        name: '1号测试终端',
        status: 'exception',
        percentage: 20
    },
    {
        name: '2号测试终端',
        status: 'warning',
        percentage: 50
    },
    {
        name: '3号测试终端',
        status: 'success',
        percentage: 90
    }
])
const programoption: any = ref([])
const logtableData: any = ref([])
const tableRef = ref()
const status = ref('')
const tableStore = new TableStore({
    url: '/device-boot/version/getTerminalVersionList',
    method: 'POST',
    column: [],
    loadCallback: () => {
        // tableStore.table.data.forEach((item: any) => {
        //     if (item.children.length > 0) {
        //         item.id = item.children[0].pid
        //     }
        // })
        treeData.value = tree2List(tableStore.table.data, Math.random() * 1000)
        treeDataCopy.value = JSON.parse(JSON.stringify(treeData.value))
        setTimeout(() => {
            tableRef.value.setAllTreeExpand(true)
        }, 0)
    }
})
tableStore.table.params.teriminal = ''
tableStore.table.params.state = ''
tableStore.table.params.program = ''
tableStore.table.params.searchEvent = ''
tableStore.table.params.filterName = ''
provide('tableStore', tableStore)

const tree2List = (list: any, id: any) => {
    //存储结果的数组
    let arr: any = []
    // 遍历 tree 数组
    list.forEach((item: any) => {
        item.uPid = id
        item.uId = Math.random() * 1000

        // 判断item是否存在children
        if (!item.children) return arr.push(item)
        // 函数递归，对children数组进行tree2List的转换
        const children = tree2List(item.children, item.uId)
        // 删除item的children属性
        delete item.children
        // 把item和children数组添加至结果数组
        //..children: 意思是把children数组展开
        arr.push(item, ...children)
    })
    // 返回结果数组
    return arr
}

tableStore.table.params.searchValue = ''
tableStore.table.params.searchState = 0
onMounted(() => {
    getDevTypeList().then(res => {
        teriminaloption.value = res.data
    })
    tableStore.index()
})
const add = () => {}
const updateprogram = (row: any) => {
    protitle.value = row.name
    prodialogVisible.value = true
}
const queryview = (row: any) => {
    dialogVisible.value = true
    protitle.value = row.name
    let data = {
        id: row.id
    }
    getTerminalUpLog(data).then((res: any) => {
        logtableData.value = res.data
    })
}
const format = (percentage: any) => {
    if (percentage <= 100 && percentage >= 90) {
        status.value = 'success'
        return percentage === 100 ? '升级成功' : `${percentage}%`
    } else if (percentage > 0 && percentage < 50) {
        status.value = 'exception'
        return percentage <= 20 ? '升级失败' + percentage + '%' : `${percentage}%`
    } else if (percentage > 0 && percentage <= 50) {
        status.value = 'warning'
        return percentage <= 50 ? '升级中断' : `${percentage}%`
    }
}
const formFilter = (row: any) => {
    let title = '/'
    if (row.cellValue != null) {
        teriminaloption.value.forEach((item: any) => {
            if (item.id == row.cellValue) {
                title = item.name
            }
        })
    }

    return title
}

// 表格过滤
const searchEvent = debounce(e => {
    const filterVal = XEUtils.toValueString(tableStore.table.params.filterName).trim().toLowerCase()
    if (filterVal) {
        const options = { children: 'children' }
        const searchProps = ['name']
        const rest = XEUtils.searchTree(
            treeDataCopy,
            (item: any) => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1),
            options
        )

        treeData.value = rest

        // 搜索之后默认展开所有子节点
    } else {
        treeData.value = treeDataCopy
    }
    nextTick(() => {
        const $table = tableRef.value
        if ($table) {
            $table.setAllTreeExpand(true)
        }
    })
}, 300)
</script>
