<template>
    <div>
        <el-row :gutter="30" class="mb20">
            <el-col :span="10">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>公共连接点参数</span>
                        </div>
                    </template>
                    <div :style="`height: calc(${height} / 2 - 117px);overflow-y: auto`">
                        <el-form
                            ref="formRef"
                            :model="form"
                            label-width="150px"
                            :rules="rules"
                            :disabled="props.rowList.id != undefined"
                            style="max-width: 500px; margin: auto"
                        >
                            <el-form-item label="用户模式" prop="userMode">
                                <el-select v-model="form.userMode" placeholder="请选择用户模式">
                                    <el-option
                                        v-for="item in ModeList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="接线类型" prop="ptType">
                                <el-select
                                    v-model="form.ptType"
                                    @change="form.connectionMode = ''"
                                    placeholder="请选择接线类型"
                                >
                                    <el-option
                                        v-for="item in connection"
                                        :key="item.value"
                                        :label="item.name"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="连接方式" v-if="form.ptType == 0" prop="connectionMode">
                                <el-select v-model="form.connectionMode" clearable placeholder="请选择连接方式">
                                    <el-option
                                        v-for="item in method"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="功率因数" prop="k">
                                <el-select v-model="form.k" clearable placeholder="请选择功率因数">
                                    <el-option
                                        v-for="item in factor"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="电压等级" prop="scale">
                                <el-select v-model="form.scale" clearable placeholder="请选择电压等级">
                                    <el-option
                                        v-for="item in levelList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="供电设备容量(MVA)" prop="deviceCapacity">
                                <el-input-number
                                    v-model="form.deviceCapacity"
                                    style="width: 100%"
                                    :min="0.000001"
                                    placeholder="请填入供电设备容量"
                                />
                            </el-form-item>
                            <el-form-item label="最小短路容量(MVA)" prop="shortCapacity">
                                <el-input-number
                                    v-model="form.shortCapacity"
                                    style="width: 100%"
                                    :min="0.000001"
                                    placeholder="请填入最小短路容量"
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="14">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>干扰源用户：</span>
                            <el-select
                                v-model="userId"
                                placeholder="请选择用户"
                                style="width: 240px; font-weight: normal"
                                :disabled="props.rowList.id != undefined"
                                @change="selChange"
                            >
                                <el-option
                                    v-for="item in userData"
                                    :key="item.userId"
                                    :label="item.userName"
                                    :value="item.userId"
                                />
                            </el-select>
                        </div>
                    </template>
                    <div :style="`height: calc(${height} / 2 - 128px);overflow-y: auto`">
                        <vxe-table
                            v-bind="defaultAttribute"
                            ref="vxeRef"
                            height="auto"
                            v-loading="loading"
                            :data="equipmentList"
                        >
                            <vxe-column field="devName" title="设备名称"></vxe-column>
                            <vxe-column field="devScale" title="电压等级" :formatter="formatter"></vxe-column>
                            <vxe-column field="protocolCapacity" title="设备容量(MVA)"></vxe-column>
                        </vxe-table>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <div class="bottomBox">
            <div v-if="showFlag">
                <div style="height: 70px">
                   
                    一级评估：{{ outcome.firstResult }}%
                    {{ outcome.firstResult > 0.1 ? '>' : (outcome.firstResult = 0.1 ? '=' : '<') }} 0.1%
                    <!-- <span>{{ 0.02 < outcome.firstResult && outcome.firstResult < 0.1 ? '满足' : '不满足' }}</span> -->
                    <el-tag v-if="outcome.firstResult < 0.1" type="success" effect="dark">满足</el-tag>
                    <el-tag v-else type="warning" effect="dark">不满足</el-tag>
                </div>
                <div style="height: 20px" v-if="!(outcome.firstResult < 0.1)" class="mb10">
                    二级评估:
                    <el-row>
                        <el-col :span="16" :style="`height: calc(${height} / 2 - 100px)`">
                            <vxe-table style="flex: 1.5" v-bind="defaultAttribute" height="auto" :data="level2Data">
                                <vxe-column field="name" title="谐波次数" width="180"></vxe-column>
                                <vxe-column v-for="item in column" :field="item.field" :title="item.title">
                                    <template #default="row">
                                        <span v-if="row.row.name == '是否允许值'">
                                            <Select v-if="row.row[row.column.field]" class="SelectIcon" />
                                            <InfoFilled v-else class="SelectIcon" style="color: #f38d07" />
                                        </span>
                                        <span v-else>{{ row.row[row.column.field] }}</span>
                                    </template>
                                </vxe-column>
                            </vxe-table>
                        </el-col>
                        <el-col :span="8" :style="`height: calc(${height} / 2 - 100px)`">
                            <MyEChart style="flex: 1" :options="pieCharts" />
                        </el-col>
                    </el-row>
                </div>
            </div>
            <el-button type="primary" icon="el-icon-Document" @click="assess" v-if="props.rowList.id == undefined">
                承载能力评估
            </el-button>
        </div>

        <el-dialog draggable v-model="dialogVisible" title="新增干扰源类型" width="70%">
            <vxe-table v-bind="defaultAttribute" height="400px" ref="xTable" :data="userData">
                <vxe-column type="checkbox" width="60"></vxe-column>
                <vxe-column field="userName" title="用户名称"></vxe-column>
                <vxe-column field="userType" title="用户类型" :formatter="formatter"></vxe-column>
                <vxe-column field="voltage" title="电压等级(V)" :formatter="formatter"></vxe-column>
                <vxe-column field="protocolCapacity" title="用户协议容量(MVA)"></vxe-column>
            </vxe-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addUse">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import MyEChart from '@/components/echarts/MyEchart.vue'
import { useDictData } from '@/stores/dictData'
import { mainHeight } from '@/utils/layout'
import { Select, InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { queyDetailUser, carryCapacityEvaluate, queyDeviceList } from '@/api/advance-boot/bearingCapacity'
const props = defineProps(['rowList'])
const dictData = useDictData()
const height = mainHeight(80).height
const levelList = dictData.getBasicData('Dev_Voltage_Stand')
const connection: any = dictData.getBasicData('Dev_Connect')
const method = dictData.getBasicData('carry_capcity_connection_mode')
const ModeList = dictData.getBasicData('carry_capcity_user_mode')
const uesrList = dictData.getBasicData('CARRY_CAPCITY_USER_TYPE', ['Power_Station_Users'])
const xTable = ref()
const formRef = ref()
const vxeRef = ref()
const loading = ref(false)
const outcome: any = ref([])
const factor = [
    {
        name: 0.95,
        id: 0.95
    },
    
    {
        name: 0.96,
        id: 0.96
    },
    {
        name: 0.97,
        id: 0.97
    },
    {
        name: 0.98,
        id: 0.98
    },
    {
        name: 0.99,
        id: 0.99
    },
    {
        name: 1.0,
        id: 1.0
    }
]
const dialogVisible = ref(false)
const showFlag = ref(false)
const tableData = ref([])
const equipmentList: any = ref([])
const userId = ref('')
const level2Data = ref([
    {
        name: '谐波电流幅值(A)'
    },
    {
        name: '国际限值(A)'
    },
    {
        name: '是否允许值'
    }
])

const column: any = ref([])
const userData: any = ref([])
const form: any = ref({
    ptType: '0',
    connectionMode: '',
    userMode: '',
    k: '1',
    scale: '',
    shortCapacity: 1,
    deviceCapacity: 1,
    userList: []
})
const rules = {
    userMode: [{ required: true, message: '请选用户', trigger: 'change' }],
    ptType: [{ required: true, message: '请选择接线类型', trigger: 'change' }],
    connectionMode: [{ required: true, message: '请选择连接方式', trigger: 'change' }],
    k: [{ required: true, message: '请选择功率因数', trigger: 'change' }],
    scale: [{ required: true, message: '请选择电压等级', trigger: 'change' }],
    shortCapacity: [{ required: true, message: '请填入供电设备容量', trigger: 'blur' }],
    deviceCapacity: [{ required: true, message: '请填入最小短路容量', trigger: 'blur' }]
}
const pieCharts = ref({})

// 查询用户
const getUser = () => {
    queyDetailUser({ pageNum: 1, pageSize: 10000, userTypeList: uesrList.map(item => item.id) }).then(res => {
        userData.value = res.data.records
    })
}

// 添加用户
const addUse = () => {
    tableData.value = []
    tableData.value.push(...xTable.value.getCheckboxRecords())
    // const res = new Map()
    // tableData.value = tableData.value.filter((arr: any) => !res.has(arr.userId) && res.set(arr.userId, 1))
    dialogVisible.value = false
}
// 查看设备
const equipment = (row: any) => {}
// 承载能力评估
const assess = () => {
    // vxeRef.value.getRadioRecord()

    if (equipmentList.value.length == null) {
        return ElMessage.warning('请选择用户')
    }
    formRef.value.validate((valid: any) => {
        if (valid) {
            form.value.devList = equipmentList.value
            carryCapacityEvaluate(form.value).then(res => {
                rendering(res.data)
            })
        }
    })
}
// 设置图
const rendering = (row: any) => {
    column.value = []
    let ChartsList = [
        {
            name: '安全',
            value: 0
        },
        {
            name: 'III级',
            value: 0
        },
        {
            name: 'II级',
            value: 0
        },
        {
            name: 'I级',
            value: 0
        },
        {
            name: '禁止接入',
            value: 0
        },
        {
            name: '允许接入',
            value: 0
        }
    ]
    outcome.value = row
    row.iresultList.forEach((item: any) => {
        column.value.push({
            title: item.time + '次',
            field: 'num' + item.time
        })

        level2Data.value[0]['num' + item.time] = item.i.toFixed(3)
        level2Data.value[1]['num' + item.time] = item.i_limit.toFixed(3)
        level2Data.value[2]['num' + item.time] = item.i < item.i_limit ? true : false
    })
    showFlag.value = true
    row.reslutLevel == null ? '' : (ChartsList[row.reslutLevel - 1].value = 1)
    pieCharts.value = {
        title: {
            text: '承载能力评估结果',
            x: 'center',
            top: `30px`,
            textStyle: {
                fontWeight: 'normal'
            }
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            left: 10,
            top: '10%'
        },

        xAxis: {
            show: false
        },
        yAxis: {
            show: false
        },
        color: ['#77DA63', '#00BFF5', '#FFBF00', '#Ff6600', '#ff0000', '#07CCCA'],
        dataZoom: { show: false },
        series: [
            {
                type: 'pie',
                center: ['60%', '70%'],
                radius: ['35%', '48%'],
                label: {
                    normal: {
                        show: false
                    }
                },
                data: ChartsList
            }
        ]
    }
}

// 过滤数据
const formatter = (row: any) => {
    if (row.column.field == 'userType') {
        return uesrList.filter(item => item.id == row.cellValue)[0].name
    } else if (row.column.field == 'devScale') {
        return levelList.filter(item => item.id == row.cellValue)[0].name
    } else if (row.column.field == 'voltage') {
        return levelList.filter(item => item.id == row.cellValue)[0].name
    } else {
        return row.cellValue
    }
}
// 查询设备
const selChange = (e: any) => {
    loading.value = true
    queyDeviceList({
        userId: e
    }).then(res => {
        loading.value = false
        equipmentList.value = res.data
    })
}

onMounted(() => {
    getUser()
    formRef.value?.resetFields()
    // 查看
    console.log('🚀 ~ onMounted ~ props.rowList:', props.rowList)

    if (props.rowList.userId != undefined) {
        form.value = props.rowList
        userId.value = props.rowList.userId
        selChange(props.rowList.userId)
        rendering(props.rowList)
    }
})
</script>
<style lang="scss" scoped>
.bottomBox {
    position: relative;
    .el-button {
        position: absolute;
        top: 0;
        right: 10px;
    }
}
.card-header {
    font-weight: 600;
}
.SelectIcon {
    height: 30px;
    margin-top: 5px;
    color: blue;
}
</style>
