<template>
    <div class="measurement">
        <el-table :columns="tableColumn" :data="tableData" @sort-change="sortChange" max-height="420">
            <el-table-column
                v-for="item in tableColumn"
                :key="item.prop"
                :label="item.label"
                :prop="item.prop"
                :width="item.width ?? ''"
                :align="item.align"
                :sortable="item.sortable"
            >
                <template #default="scope">
                    <el-radio
                        v-if="item.prop === 'index'"
                        :label="scope.row.attributeCode"
                        v-model="selectedIndex"
                        @change="handleRadioChange(scope.row)"
                        >&nbsp;</el-radio
                    >
                </template>
            </el-table-column>
        </el-table>
        <div>
            <el-pagination
                v-model:current-page="pageSetting.current"
                v-model:page-size="pageSetting.pageSize"
                :total="pageSetting.total"
                :page-sizes="pageSetting.pageSizes"
                background
                :pager-count="7"
                layout="prev, pager, next, jumper,sizes,total"
                @change="getcurrentPage"
            ></el-pagination>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import type { ModelAttributeFieldsEnums } from '/@/views/backend/auth/model/type'
import { getModelAttributeListReq, getRealValueListReq } from '/@/api/backend/deviceModel/request'

const props = defineProps({
    iotModelId: {
        type: String,
        default: '',
    },
    deviceId: {
        type: String,
        default: '',
    },
    irn: {
        type: String,
        default: '',
    },
    show: {
        type: Boolean,
        default: false,
    },
})

const selectedIndex: any = ref(null)
const tableColumn = [
    {
        type: 'selection',
        prop: 'index',
        width: 55,
    },
    {
        label: '序号',
        prop: 'porder',
        width: 76,
        align: 'center',
        sortable: 'custom',
    },
    {
        label: '属性名称',
        prop: 'attributeName',
        align: 'left',
        sortable: 'custom',
    },
    {
        label: '属性编码',
        prop: 'attributeCode',
        align: 'left',
        width: 200,
        sortable: 'custom',
    },
    {
        label: '子系统',
        prop: 'subSystem',
        align: 'left',
        width: 110,
        sortable: false,
    },
]
const tableData = ref<any[]>([])
const emit = defineEmits(['handleRadioChange'])
const handleRadioChange = (row: any) => {
    selectedIndex.value = row.attributeCode
    emit('handleRadioChange', row)
}
const getAttributeList = () => {
    const requestData: any = {
        iotModelId: props.iotModelId,
        pageNum: pageSetting.current,
        pageSize: pageSetting.pageSize,
        attributeType: '138',
        orderColumn: sortData.orderColumn,
        orderType: sortData.orderType,
    }
    return new Promise((resolve) => {
        getModelAttributeListReq(requestData)
            .then((res) => {
                if (res.rows && res.rows.length > 0) {
                    const codeList: any = []
                    const data = res.rows!.map((item) => {
                        codeList.push(item.attributeCode)
                        return {
                            ...item,
                            attributeTypeName:
                                item.attributeType === 138
                                    ? '模拟量'
                                    : item.attributeType === 139
                                      ? '累积量'
                                      : item.attributeType === 140
                                        ? '离散量'
                                        : item.attributeType!,
                        }
                    })
                    pageSetting.total = res.total
                    resolve({ data, codeList })
                } else {
                    if (res.rows && res.rows.length === 0) {
                        tableData.value = []
                    } else {
                        ElMessage.error(res.msg)
                    }
                }
            })
            .catch((err) => {
                ElMessage.error(err?.response?.data?.msg ?? '查询失败')
            })
    })
}

const getRealValueList = (data: { deviceId: string; attributes: string[] }, list?: any) => {
    return new Promise((resolve) => {
        getRealValueListReq([data]).then((res) => {
            if (res.success && res.data) {
                resolve({ realVal: res.data, list })
            }
        })
    })
}

const getCompleteData = () => {
    getAttributeList()
        .then(({ data, codeList }: any) => {
            return getRealValueList({ deviceId: props.deviceId, attributes: codeList }, data)
        })
        .then((realData: any) => {
            const data = realData.list.map((item: any) => {
                const realValItem = realData.realVal[props.deviceId]?.[item.attributeCode?.toLowerCase()]
                return {
                    ...item,
                    realTimeValue: realValItem ? (realValItem % 1 === 0 ? realValItem : realValItem.toFixed(3)) : '-',
                }
            })

            tableData.value = data
        })
}

const sortData = reactive<{ orderColumn?: keyof typeof ModelAttributeFieldsEnums; orderType?: 'asc' | 'desc' }>({
    orderColumn: 'porder',
    orderType: 'asc',
})

const sortChange = ({ prop, order }: { prop: keyof typeof ModelAttributeFieldsEnums; order: 'ascending' | 'descending' | null }) => {
    const propEnums = {
        attributeCode: 'attribute_code',
        attributeName: 'attribute_name',
        attributeTypeName: 'attribute_type',
        porder: 'porder',
        serviceCode: 'service_code',
        serviceName: 'service_name',
        serviceTypeName: 'service_type',
    }
    const orderType = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : undefined
    const filed = propEnums[prop as keyof typeof propEnums] as keyof typeof ModelAttributeFieldsEnums
    sortData.orderColumn = orderType ? filed : undefined
    sortData.orderType = orderType
    getCompleteData()
}

const pageSetting = reactive({
    current: 1,
    pageSize: 20,
    total: 0,
    pageSizes: [20, 50, 100],
})

const getcurrentPage = () => {
    getCompleteData()
}

watch(
    () => props.show,
    (newVal) => {
        if (newVal) {
            getCompleteData()
            selectedIndex.value = props.irn
        }
    },
    {
        immediate: true,
    }
)
</script>

<style scoped></style>
