<template>
    <div class="airBlower">
        <el-container class="containerPart">
            <el-header class="headerPart">
                <div class="headerLeft">
                    <div class="selectPart">
                        <span>{{ t('airBlower.status') }}</span>
                        <el-select
                            v-model="airBlowerSelect.iturbineoperationmode"
                            @change="selectAirBlower('iturbineoperationmode')"
                            :placeholder="'请选择' + t('airBlower.status')"
                            class="airBlowerSelect"
                        >
                            <el-option
                                v-for="v in airBlowerSelectOptions.iturbineoperationmode"
                                :key="v.value"
                                :label="v.label"
                                :value="v.value"
                            ></el-option>
                        </el-select>
                    </div>
                    <div class="selectPart">
                        <span>{{ t('airBlower.feeder') }}</span>
                        <el-select
                            v-model="airBlowerSelect.belongLine"
                            @change="selectAirBlower('belongLine')"
                            :placeholder="'请选择' + t('airBlower.feeder')"
                            class="airBlowerSelect"
                        >
                            <el-option v-for="v in airBlowerSelectOptions.belongLine" :key="v.value" :label="v.value" :value="v.value"></el-option>
                        </el-select>
                    </div>
                    <div class="selectPart">
                        <span>自动更新：</span>
                        <el-switch
                            v-model="autoUpdate"
                            class="ml-2"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        ></el-switch>
                    </div>
                </div>
                <div class="headerRight">
                    <el-popconfirm title="确认启动么？" @confirm="airBlowerOperate('setTurbineFastStart')">
                        <template #reference>
                            <el-button type="primary">{{ t('airBlower.start') }}</el-button>
                        </template>
                    </el-popconfirm>
                    <el-popconfirm title="确认停机么？" @confirm="airBlowerOperate('setTurbineStop')">
                        <template #reference>
                            <el-button style="color: #0064aa">{{ t('airBlower.stop') }}</el-button>
                        </template>
                    </el-popconfirm>
                    <el-popconfirm title="确认复位么？" @confirm="airBlowerOperate('setTurbineResetStatusCode')">
                        <template #reference>
                            <el-button style="color: #0064aa">{{ t('airBlower.reset') }}</el-button>
                        </template>
                    </el-popconfirm>
                    <el-popconfirm title="确认风机对时么？">
                        <template #reference>
                            <el-button style="color: #0064aa">{{ t('airBlower.verify') }}</el-button>
                        </template>
                    </el-popconfirm>
                </div>
            </el-header>
            <el-main class="mainPart">
                <el-table
                    ref="tableRef"
                    :column="tableColumn"
                    :data="tableData"
                    :header-row-style="tableHaderStyle"
                    @selectionChange="selectTable"
                    max-height="100%"
                >
                    <el-table-column type="selection" width="55"></el-table-column>
                    <template v-for="item in tableColumn" :key="item.prop">
                        <el-table-column
                            v-if="!item.custom"
                            :prop="item.prop"
                            :label="item.label"
                            :align="item.align"
                            :width="item.width"
                            :type="item.type"
                        />
                        <el-table-column v-else :label="item.label" :align="item.align" :width="item.width">
                            <template v-if="item.custom === 'default'" #default="scope">
                                <div v-if="item.prop === 'iturbineoperationmode'">
                                    <el-tag v-if="scope.row.locked === 1" color="rgba(254,55,49,0.20)" style="color: #fe3731">已锁定</el-tag>
                                    <el-tag v-if="scope.row.iturbineoperationmode === 20" color="rgba(0,100,170,0.20)" style="color: #0064aa"
                                        >并网</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 10" color="rgba(0,160,150,0.20)" style="color: #00a096"
                                        >维护</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 8" color="rgba(255,126,0,0.20)" style="color: #ff7e00"
                                        >限功率运行</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 0" color="rgba(153,153,153,0.20)" style="color: #666666"
                                        >离线</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 16" color="rgba(6,180,41,0.20)" style="color: #06b429"
                                        >启动</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 6" color="rgba(254,55,49,0.20)" style="color: #fe3731"
                                        >正常停机</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 1" color="rgba(254,55,49,0.20)" style="color: #fe3731"
                                        >外部因素导致停机</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 2" color="rgba(254,55,49,0.20)" style="color: #fe3731"
                                        >停机</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 11" color="rgba(255,182,0,0.20)" style="color: #ffb600"
                                        >待机</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 1110" color="rgba(153,153,153,0.20)" style="color: #666666"
                                        >解缆状态</el-tag
                                    >
                                    <el-tag v-if="scope.row.iturbineoperationmode === 1111" color="rgba(254,55,49,0.20)" style="color: #fe3731"
                                        >电网故障停机</el-tag
                                    >
                                </div>
                            </template>
                            <template v-if="item.custom === 'header'" #header="scope">
                                <div>{{ scope.column.label.split(' ')[0] }}</div>
                                <div>{{ scope.column.label.split(' ')[1] }}</div>
                            </template>
                            <template v-if="item.custom === 'header'" #default="scope">
                                <div>{{ scope.row[item.prop] }}</div>
                            </template>
                            <template v-if="item.prop === 'name'" #default="scope">
                                <div class="tableColumnClick" @click="openWindTurbine(scope.row)">{{ scope.row[item.prop] }}</div>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </el-main>
        </el-container>
    </div>
    <el-dialog v-model="multiTaskVisible" :title="mutiTaskTitle" width="400" :close-on-click-modal="false">
        <el-row v-for="item in mutiTaskList" :key="item.sendData.deviceId">
            <el-col :span="18">
                <div class="mutiTaskName">
                    {{ item.deviceName }}
                </div>
            </el-col>
            <el-col :span="6">
                <div class="mutiTaskStatus">
                    <el-icon style="color: #f56c6c" size="30" v-if="item.loading === 3">
                        <CircleClose />
                    </el-icon>
                    <el-icon style="color: #06b429" size="30" v-if="item.loading === 2">
                        <CircleCheck />
                    </el-icon>
                    <el-icon style="color: #4fa5ff" size="30" class="mutiTaskLoading" v-if="item.loading === 1">
                        <Loading />
                    </el-icon>
                    <div v-if="item.loading === 0">等待发送</div>
                </div>
            </el-col>
        </el-row>
    </el-dialog>
</template>

<script setup lang="ts">
import { SelectTypeObjType, SelectTypeKeyUnionType, TableDataObjType, TableColumnType } from './type'
import { onUnmounted, reactive, ref, watch, nextTick, KeepAlive } from 'vue'
import { useI18n } from 'vue-i18n'
import { getAirBlowerListReq, getBelongLineListReq, runAirBlowerReq } from '/@/api/backend/airBlower/request'
import { CircleCheck, CircleClose, Loading } from '@element-plus/icons-vue'
import { ElMessage, TableInstance, ElPopconfirm } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { getRealTimeState } from './utils'
import { sendCommandReq } from '/@/api/backend/control/request'
import { adminBaseRoutePath } from '/@/router/static/adminBase'

const router = useRouter()

const { t } = useI18n()

const airBlowerSelect = reactive<SelectTypeObjType>({
    iturbineoperationmode: 987654321,
    belongLine: '全部',
})

const airBlowerSelectOptions = reactive<{ [K in SelectTypeKeyUnionType]: { label: string; value: string | number }[] }>({
    iturbineoperationmode: [
        {
            label: '全部',
            value: 987654321,
        },
        {
            label: '并网',
            value: 20,
        },
        {
            label: '待机',
            value: 11,
        },
        {
            label: '启动',
            value: 16,
        },
        {
            label: '维护',
            value: 10,
        },
        {
            label: '离线',
            value: 0,
        },
        {
            label: '限功率运行',
            value: 8,
        },
        {
            label: '正常停机',
            value: 6,
        },
        {
            label: '外部因素导致停机',
            value: 1,
        },
        {
            label: '停机',
            value: 2,
        },
        {
            label: '解缆状态',
            value: 1110,
        },
        {
            label: '电网故障停机',
            value: 1111,
        },
        {
            label: '安全链停机',
            value: 1112,
        },
    ],
    belongLine: [],
})

const selectAirBlower = (type: SelectTypeKeyUnionType) => {
    if (airBlowerSelect.belongLine === '全部' && airBlowerSelect.iturbineoperationmode === 987654321) {
        tableData.value = originTableData.value
        return
    } else if (airBlowerSelect.belongLine !== '全部' && airBlowerSelect.iturbineoperationmode !== 987654321) {
        if (type === 'iturbineoperationmode' && airBlowerSelect.iturbineoperationmode === 2) {
            const type1 = originTableData.value.filter((item) => item.iturbineoperationmode === 1)
            const type6 = originTableData.value.filter((item) => item.iturbineoperationmode === 6)
            const type2 = originTableData.value.filter((item) => item.iturbineoperationmode === 2)
            const typeAll = [...type1, ...type6, ...type2]
            tableData.value = typeAll.filter((item) => item.belongLine === airBlowerSelect.belongLine)
            return
        }
        const resData = originTableData.value.filter((item) => item.iturbineoperationmode === airBlowerSelect.iturbineoperationmode)
        tableData.value = resData.filter((item) => item.belongLine === airBlowerSelect.belongLine)
        return
    } else {
        if (type === 'belongLine' && airBlowerSelect.belongLine === '全部') {
            tableData.value = originTableData.value.filter((item) => item.iturbineoperationmode === airBlowerSelect.iturbineoperationmode)
            return
        } else if (type === 'iturbineoperationmode' && airBlowerSelect.iturbineoperationmode === 987654321) {
            tableData.value = originTableData.value.filter((item) => item.belongLine === airBlowerSelect.belongLine)
            return
        }
        if (type === 'iturbineoperationmode' && airBlowerSelect.iturbineoperationmode === 2) {
            const type1 = originTableData.value.filter((item) => item.iturbineoperationmode === 1)
            const type6 = originTableData.value.filter((item) => item.iturbineoperationmode === 6)
            const type2 = originTableData.value.filter((item) => item.iturbineoperationmode === 2)
            tableData.value = [...type1, ...type6, ...type2]
            return
        }

        tableData.value = originTableData.value.filter((item) => item[type] === airBlowerSelect[type])
        return
    }
}

const airBlowerOperate = async (type: 'setTurbineFastStart' | 'setTurbineStop' | 'setTurbineResetStatusCode') => {
    const sendTypeEnum = {
        setTurbineFastStart: '风机快速启动指令',
        setTurbineStop: '风机停机指令',
        setTurbineResetStatusCode: '风机复位故障代码指令',
    }
    if (!selectList.value.length) {
        ElMessage.warning('请先选择风机')
        return
    }
    const data = selectList.value.map((item) => {
        return {
            sendData: {
                deviceId: item,
                serviceName: sendTypeEnum[type],
                serviceCode: type,
                optDesc: sendTypeEnum[type] + '，设定值为：' + 1,
                opValue: 1 as const,
            },
            deviceName: tableData.value.find((listItem) => listItem.irn === item)!.name,
            loading: 0 as const,
        }
    })
    mutiTaskList.value = data
    mutiTaskTitle.value = sendTypeEnum[type]
    multiTaskVisible.value = true
    console.log(mutiTaskList.value)

    for (let i = 0; i < mutiTaskList.value.length; i++) {
        mutiTaskList.value[i].loading = 1
        console.log(mutiTaskList.value[i].deviceName)
        runTask(mutiTaskList.value[i].sendData, i)
    }
}

const runTask = async (data: any, index: number) => {
    console.log(data)
    try {
        let resp = await sendCommandReq(data)
        if (resp.success) {
            mutiTaskList.value[index].loading = 2
        }
    } catch (error) {
        mutiTaskList.value[index].loading = 3
    }

    // .then((res: any) => {
    //     console.log(res)
    //     if (res.success) {
    //         console.log(data, 'success')
    //         mutiTaskList.value[index].loading = 2
    //     } else {
    //         mutiTaskList.value[index].loading = 3
    //     }
    // })
    // .catch(() => {
    //     mutiTaskList.value[index].loading = 3
    // })
}

const tableHaderStyle = {
    color: '#333',
}

const tableColumn: TableColumnType[] = [
    {
        label: '风机列表',
        prop: 'name',
        align: 'center',
        custom: 'default',
    },
    {
        label: '风机型号',
        prop: 'model',
        align: 'center',
    },
    {
        label: '风机状态',
        prop: 'iturbineoperationmode',
        align: 'center',
        custom: 'default',
    },
    {
        label: '线路',
        prop: 'belongLine',
        align: 'center',
    },
    {
        label: '风速 (m/s)',
        prop: 'iwindspeed',
        align: 'center',
        custom: 'header',
    },
    {
        label: '有功功率 (MW)',
        prop: 'igenpower',
        align: 'center',
        custom: 'header',
    },
    {
        label: '日发电量 (kWh)',
        prop: 'ikwhthisday',
        align: 'center',
        custom: 'header',
    },
    {
        label: '总发电量 (万kWh)',
        prop: 'ikwhoverall',
        align: 'center',
        custom: 'header',
    },
    {
        label: '机舱角度',
        prop: 'ivanedirection',
        align: 'center',
    },
    {
        label: '叶轮转速 (rmp)',
        prop: 'irotorspeed',
        align: 'center',
        custom: 'header',
    },
    {
        label: '发电机转速 (rmp)',
        prop: 'igenspeed',
        align: 'center',
        custom: 'header',
    },
    {
        label: '机舱温度 (℃)',
        prop: 'itempnacelle_1sec',
        align: 'center',
        custom: 'header',
    },
    {
        label: '主油路压力 (kpa)',
        prop: 'ihydrpress',
        align: 'center',
        custom: 'header',
    },
    {
        label: '变桨角度',
        prop: 'ipitchangle',
        align: 'center',
    },
]

const tableRef = ref<TableInstance>()
const tableData = ref<TableDataObjType[]>([])
const originTableData = ref<TableDataObjType[]>([])
const getTableData = () => {
    getAirBlowerListReq()
        .then((res) => {
            const data = res.data.map((item: any) => {
                const state = getRealTimeState(item.attributeMap)
                const ipitchangle = Math.min(item.attributeMap.ipitchangle1, item.attributeMap.ipitchangle2, item.attributeMap.ipitchangle3)
                const resVal: any = {}
                Object.keys(item.attributeMap).forEach((attrKey) => {
                    resVal[attrKey] =
                        item.attributeMap[attrKey] === 0
                            ? 0
                            : item.attributeMap[attrKey]
                              ? item.attributeMap.iwindspeed % 1 === 0
                                  ? item.attributeMap.iwindspeed
                                  : Math.floor(item.attributeMap[attrKey] * 1000) / 1000
                              : '-'
                })
                return {
                    irn: item.irn,
                    name: item.name ?? '-',
                    model: item.model || '-',
                    iotModelId: item.modelId,
                    belongLine: item.belongLine || '-',
                    iwindspeed: '-',
                    igenpower: '-',
                    ikwhthisday: '-',
                    ikwhoverall: '-',
                    ivanedirection: '-',
                    irotorspeed: '-',
                    igenspeed: '-',
                    itempnacelle_1sec: '-',
                    ihydrpress: '-',
                    ...resVal,
                    ipitchangle: ipitchangle === 0 ? 0 : ipitchangle ? Math.floor(ipitchangle * 1000) / 1000 : '-',
                    iturbineoperationmode: state,
                }
            })
            console.log(data)

            originTableData.value = data
            if (airBlowerSelect.belongLine === '全部' && airBlowerSelect.iturbineoperationmode === 987654321) {
                tableData.value = data
            } else {
                const irn = tableData.value.map((item) => item.irn)
                const result: TableDataObjType[] = []
                data.forEach((item: TableDataObjType) => {
                    if (irn.includes(item.irn)) {
                        result.push(item)
                    }
                })
                tableData.value = result
            }
            if (selectList.value.length) {
                const selected = tableData.value.filter((item) => selectList.value.includes(item.irn))
                selected.forEach((item) => {
                    nextTick(() => {
                        tableRef.value?.toggleRowSelection(item, true)
                    })
                })
            }
        })
        .catch((err: any) => {
            console.log(err)
        })
}

const getBlongLineList = () => {
    getBelongLineListReq()
        .then((res) => {
            const data = res.data.map((item: any) => {
                return {
                    value: item,
                }
            })
            airBlowerSelectOptions.belongLine = [{ value: '全部', label: '全部' }, ...data]
        })
        .catch((err) => {
            console.log(err)
        })
}

const selectList = ref<string[]>([])

const selectTable = (selected: TableDataObjType[]) => {
    selectList.value = selected.map((item) => item.irn)
}

const autoUpdate = ref(false)
const autoUpdateInterval = ref<any>(null)
watch(autoUpdate, (newVal: boolean) => {
    if (newVal) {
        if (autoUpdateInterval.value) return
        ElMessage.success('开启自动刷新')
        autoUpdateInterval.value = setInterval(() => {
            console.log('刷新')
            getTableData()
        }, 2000)
    } else {
        ElMessage.warning('关闭自动刷新')
        clearInterval(autoUpdateInterval.value)
        autoUpdateInterval.value = null
    }
})

const openWindTurbine = (row: TableDataObjType) => {
    if (!router.hasRoute('windTurbine')) {
        router.addRoute('admin', {
            path: adminBaseRoutePath + '/windTurbine',
            name: 'windTurbine',
            component: () => import('/@/views/backend/WindBlower/index.vue'),
            meta: {
                title: 'WindBlower',
                menuDesc: '单风机详情',
                addtab: true,
            },
        })
    }

    router.push({
        name: 'windTurbine',
        query: {
            irn: row.irn,
            iotModelId: row.iotModelId,
            name: row.name,
        },
    })
}

const multiTaskVisible = ref(false)
const mutiTaskTitle = ref('')
const mutiTaskList = ref<
    {
        loading: 0 | 1 | 2 | 3
        deviceName: string
        sendData: {
            deviceId: string
            serviceName: string
            serviceCode: string
            optDesc: string
            opValue: 1
        }
    }[]
>([])

onUnmounted(() => {
    autoUpdateInterval.value && clearInterval(autoUpdateInterval.value)
    autoUpdateInterval.value = null
})
getTableData()
getBlongLineList()
</script>

<style scoped lang="scss">
.airBlower {
    width: 100%;
    height: 100%;
    .containerPart {
        width: 100%;
        height: 100%;
        .headerPart {
            padding: 20px;
            width: 100%;
            height: 60px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .headerLeft {
                display: flex;
                .selectPart {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    height: 40px;
                    margin-right: 20px;
                    span {
                        margin-right: 10px;
                    }
                    .airBlowerSelect {
                        width: 200px;
                        :deep(.el-select__wrapper) {
                            height: 40px;
                        }
                    }
                }
            }
            .headerRight {
                width: 436px;
                display: flex;
                justify-content: space-between;
                .el-button {
                    width: 100px;
                    height: 40px;
                }
            }
        }
        .mainPart {
            width: 100%;
            height: calc(100% - 60px);
            .tableColumnClick {
                text-decoration: underline;
                color: #00a4ff;
                cursor: pointer;
            }
        }
    }
}

.mutiTaskName {
    width: 100%;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
}
.mutiTaskStatus {
    display: flex;
    align-items: center;
    justify-content: right;
    width: 100%;
    height: 40px;
}
.mutiTaskLoading {
    animation: rotate 1s linear infinite;
}
@keyframes rotate {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
</style>
