<template>
    <TableHeader ref="refheader" :showSearch="false">
        <template #select>
            <el-form-item label="日期">
                <DatePicker ref="datePickerRef"></DatePicker>
            </el-form-item>
            <el-form-item>
                <el-checkbox-group style="width: 150px" v-model="checkList">
                    <el-checkbox label="稳态" :value="0" />
                    <el-checkbox label="暂态" :value="1" />
                </el-checkbox-group>
            </el-form-item>
        </template>
        <template #operation>
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button type="primary" :icon="Setting" @click="handleUpDevice">补召</el-button>
            <el-button :icon="Back" @click="go(-1)">返回</el-button>
        </template>

    </TableHeader>
    <!-- 设备补召 -->
    <div class=" current_device" v-loading="loading">

        <div class="current_body" ref="tbodyRef">
            <vxe-table border ref="tableRef" :data="dirList" align="center" height="auto"
                :style="{ height: tableHeight }" @radio-change="radioChangeEvent">
                <vxe-column type="radio" width="60">
                    <template #header>
                        <vxe-button mode="text" @click="clearRadioRowEvent" :disabled="!selectRow">取消</vxe-button>
                    </template>
                </vxe-column>
                <!-- <vxe-column  type="checkbox" width="60"></vxe-column> -->
                <vxe-column field="name" title="名称"></vxe-column>
                <vxe-column field="status" title="补召进度">
                    <template #default="{ row }">
                        <div class="finish" v-if="row.status == 100">
                            <SuccessFilled style="width: 16px;" /><span class="ml5">补召完成</span>
                        </div>
                        <el-progress v-model="row.status" v-else :class="row.status == 100 ? 'progress' : ''"
                            :format="format" :stroke-width="10" striped :percentage="row.status" :duration="30"
                            striped-flow />


                    </template>
                </vxe-column>
                <vxe-column field="startTime" title="起始时间"></vxe-column>
                <vxe-column field="endTime" title="结束时间"></vxe-column>
            </vxe-table>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, defineExpose, onBeforeUnmount, inject } from 'vue'
import { getMakeUpData, getAskDirOrFile, offlineDataUploadMakeUp } from '@/api/cs-harmonic-boot/recruitment.ts'
import DatePicker from '@/components/form/datePicker/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { useRouter, useRoute } from 'vue-router'
import { mainHeight } from '@/utils/layout'
import { VxeUI, VxeTableInstance, VxeTableEvents } from 'vxe-table'
import { SuccessFilled } from '@element-plus/icons-vue'
import {
    Back,
    Setting, Search
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import mqtt from 'mqtt'
defineOptions({
    name: 'supplementaryRecruitment'
})
const checkList: any = ref([])
// const props = defineProps(['lineId'])
const { go } = useRouter() // 路由
const selectRow: any = ref(null)
const loading = ref(false)
const dirList = ref([])
const route: any = ref({})
const datePickerRef = ref()
const format = (percentage) => (percentage === 100 ? '完成' : `${percentage}%`)
const getMakeUpDataList = (row: any) => {
    route.value = row
    loading.value = true
    getMakeUpData(row.id).then(res => {
        res.data.map((item: any) => {
            item.name = item.prjName
                ? item.prjDataPath.replace('/bd0/cmn/', item.prjName + '-')
                : item.prjDataPath.replace('/bd0/cmn/', '')
            item.startTime = item.startTime ? item.startTime : '/'
            item.endTime = item.endTime ? item.endTime : '/'
            item.status = 0
        })
        dirList.value = res.data
        loading.value = false
    })
}
// 进入文件夹
const dirCheckedList: any = ref([])
const tbodyRef = ref()
const tableHeight = mainHeight(85).height
const routes = useRoute()
const tableRef = ref()
const selectRowCopy: any = ref(null)
const handleUpDevice = () => {
    let proList = tableRef.value.getCheckboxRecords().map((item: any) => {
        return item.prjDataPath
    })
    if (checkList.value.length == 0) {
        return ElMessage.warning('请选择暂态稳态')
    }
    if (selectRow.value == null) {
        return ElMessage.warning('请选择工程')
    }
    selectRowCopy.value = JSON.parse(JSON.stringify(selectRow.value))
    let form = {
        dataTypeList: checkList.value,
        startTime: datePickerRef.value && datePickerRef.value.timeValue[0],
        endTime: datePickerRef.value && datePickerRef.value.timeValue[1],
        lineId: routes.query.id,
        ndid: routes.query.ndid,
        proList: [selectRow.value?.prjDataPath]
    }
    ElMessage.warning('补召中, 请稍等...')
    offlineDataUploadMakeUp(form)
        .then((res: any) => {
            if (res.code == 'A0000') {
                // ElMessage.success(res.data)
                dirList.value.map((item: any) => {
                    // checkedList.map((vv: any) => {
                    if (item.name == selectRowCopy.value?.name) {
                        item.status = 5
                    }
                    // })
                })
                // loading.value = false
            }
        })
        .catch(() => {
            // loading.value = false
        })
}

const radioChangeEvent: VxeTableEvents.RadioChange = ({ row }) => {
    selectRow.value = row
    // console.log('单选事件')
}


const clearRadioRowEvent = () => {
    const $table = tableRef.value
    if ($table) {
        selectRow.value = null
        $table.clearRadioRow()
    }
}
const mqttRef = ref()
const url: any = inject('MQTTURL')
const connectMqtt = () => {
    if (mqttRef.value) {
        if (mqttRef.value.connected) {
            return
        }
    }
    const options = {
        protocolId: 'MQTT',
        qos: 2,
        clean: true,
        connectTimeout: 30 * 1000,
        clientId: 'mqttjs' + Math.random(),
        username: 't_user',
        password: 'njcnpqs'
    }
    mqttRef.value = mqtt.connect(url, options)
}
const handleSearch = () => {
    getMakeUpDataList(route.value)
}
connectMqtt()
mqttRef.value.on('connect', () => {
    // ElMessage.success('连接mqtt服务器成功!')
    console.log('mqtt客户端已连接....')
    // mqttRef.value.subscribe('/Web/Progress')
    // mqttRef.value.subscribe('/Web/Progress/+')
    mqttRef.value.subscribe('/dataOnlineRecruitment/Progress/' + route.value.id)
})
const mqttMessage = ref<any>({})
mqttRef.value.on('message', (topic: any, message: any) => {
    // console.log('mqtt接收到消息', JSON.parse(JSON.stringify(JSON.parse(new TextDecoder().decode(message)))))
    loading.value = false
    let str = JSON.parse(JSON.stringify(JSON.parse(new TextDecoder().decode(message))))
    let regex1 = /allStep:(.*?),nowStep/
    let regex2 = /nowStep:(.*?)}/
    mqttMessage.value = {
        allStep: str.match(regex1)[1],
        nowStep: str.match(regex2)[1]
    }
    // console.log(mqttMessage.value)
    let checkedList = tableRef.value.getCheckboxRecords().map((item: any) => {
        return item.name
    })
    dirList.value.map((item: any) => {
        // checkedList.map((vv: any) => {
        if (item.name == selectRowCopy.value?.name) {
            let percentage = parseInt(Number((mqttMessage.value.nowStep / mqttMessage.value.allStep) * 100)) || 0
            if (percentage > 5) {
                item.status = percentage

            }
        }
        // })
    })
})

mqttRef.value.on('error', (error: any) => {
    console.log('mqtt连接失败...', error)
    mqttRef.value.end()
})

mqttRef.value.on('close', function () {
    console.log('mqtt客户端已断开连接.....')
})
onMounted(() => {
})
onBeforeUnmount(() => {
    if (mqttRef.value) {
        mqttRef.value.end()
    }
})
defineExpose({ getMakeUpDataList })
</script>
<style lang="scss" scoped>
// .current_device {
//     width: 100%;

//     display: flex;
//     flex-direction: column;

//     .current_header {
//         width: 100%;
//         height: 60px;
//         padding: 15px;
//         display: flex;
//         align-items: center;
//         box-sizing: border-box;

//         .el-form-item {
//             display: flex;
//             align-items: center;
//             margin-bottom: 0;
//         }
//     }

//     .current_body {
//         flex: 1;
//     }
// }
:deep(.el-progress-bar__inner--striped) {
    background-image: linear-gradient(45deg, rgba(255, 255, 255, .3) 25%, transparent 0, transparent 50%, rgba(255, 255, 255, .3) 0, rgba(255, 255, 255, .3) 75%, transparent 0, transparent);

}

:deep(.progress) {
    .el-progress__text {
        color: green;

    }
}

.finish {
    display: flex;
    justify-content: center;
    font-weight: 550;
    color: #009688
}
</style>
