<template>
    <div v-loading="loading">
        <div class="card-container mb10">
            <el-card style="width: 700px">
                <template #header>
                    <div class="card-header">
                        <span style="line-height: 32px">公共连接点参数</span>
                    </div>
                </template>
                <div :style="`height: calc(${height} - 420px);overflow-y: auto;max-height:350px`">
                    <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="请选择用户模式" filterable>
                                <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="请选择接线类型"
                                filterable
                            >
                                <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="请选择功率因数" filterable>
                                <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="请选择电压等级" filterable> 
                                <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-card class="ml10" style="flex: 1">
                <template #header>
                    <div>
                        <span>干扰源用户：</span>
                        <el-select
                            v-model="userId"
                            placeholder="请选择用户"
                            size="small"
                            style="width: 240px"
                            :disabled="props.rowList.id != undefined"
                            @change="selChange"
                            filterable
                        >
                            <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} - 420px);overflow-y: auto;max-height:350px`">
                    <vxe-table v-bind="defaultAttribute" ref="vxeRef" height="auto" :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>
            <div class="button-group">
                <el-button
                    type="primary"
                    icon="el-icon-VideoPlay"
                    @click="assess"
                    class="mt10"
                    v-if="props.rowList.id == undefined"
                >
                    启动评估
                </el-button>
                <el-button type="primary" icon="el-icon-Download" @click="onExport" class="mt10" v-if="showFlag">
                    导出结果
                </el-button>
            </div>
        </div>

        <div class="bottomBox pt1 mt40" id="exportId">
            <div v-if="showFlag">
                <el-divider content-position="left">一级评估</el-divider>
                <div style="height: 40px" class="pl30">
                    结果: {{ outcome.firstResult }}%
                    {{ outcome.firstResult > 0.1 ? '>' : (outcome.firstResult = 0.1 ? '=' : '<') }} 0.1% 

                    <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: 220px" v-if="!(outcome.firstResult < 0.1)" class="mb10">
                    <el-divider content-position="left">二级评估</el-divider>
                    <div class="evaluateTheResults">
                        <div style="height: 200px; width: calc(100% - 350px)">
                            <vxe-table 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" />
                                            <CloseBold v-else class="SelectIcon" style="color: #f38d07" />
                                        </span>
                                        <span v-else>{{ row.row[row.column.field] }}</span>
                                    </template>
                                </vxe-column>
                            </vxe-table>
                        </div>
                        <div style="height: 200px; width: 350px">
                            <MyEChart :options="pieCharts" />
                        </div>
                    </div>
                </div>
            </div>
        </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 html2canvas from 'html2canvas'
import { Select, CloseBold } 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 == 0) {
        return ElMessage.warning('请选择有终端设备的用户')
    }
    loading.value = true
    formRef.value.validate((valid: any) => {

        if (valid) {
            form.value.devList = equipmentList.value
            carryCapacityEvaluate(form.value).then(res => {
                rendering(res.data)
                loading.value = false
            })
        }else{
            loading.value = false
        }
    })
}
// 设置图
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',

        //     textStyle: {
        //         fontWeight: 'normal'
        //     }
        // },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: '10px',
            selectedMode: false // 是否允许点击
        },
        toolbox: { show: false },
        xAxis: {
            show: false
        },
        yAxis: {
            show: false
        },
        color: ['#2E7D32', '#0288D1', '#F57C00', '#E64A19', '#C62828', '#00897B'],
        dataZoom: { show: false },
        series: [
            {
                type: 'pie',
                center: ['40%', '55%'],
                radius: ['55%', '68%'],
                label: {
                    normal: {
                        show: false
                    }
                },
                data: ChartsList
            }
        ],
        options: {
            title: [
                {
                    text: '评估结果',
                    left: '27%'
                },
                {
                    text:
                        row.reslutLevel == 6
                            ? '允许接入'
                            : row.reslutLevel == 5
                            ? '禁止接入'
                            : row.reslutLevel == 4
                            ? 'I级预警'
                            : row.reslutLevel == 3
                            ? 'II级预警'
                            : row.reslutLevel == 2
                            ? 'III级预警'
                            : row.reslutLevel == 1
                            ? '安全'
                            : '',
                    left: row.reslutLevel == 1 ? '33%' : '29%',
                    top: '48%',
                    textStyle: {
                        color:
                            row.reslutLevel == 6
                                ? '#00897B'
                                : row.reslutLevel == 5
                                ? '#C62828'
                                : row.reslutLevel == 4
                                ? '#E64A19'
                                : row.reslutLevel == 3
                                ? '#F57C00'
                                : row.reslutLevel == 2
                                ? '#0288D1'
                                : '#2E7D32',
                        foontWeight: '500'
                    }
                }
            ]
        }
    }
}

// 过滤数据
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 = async (e: any) => {
    loading.value = true
    await queyDeviceList({
        userId: e
    }).then(res => {
        equipmentList.value = res.data
    })
    loading.value = false
}
// 导出
const onExport = () => {
   // console.log("🚀 ~ onExport ~ document.getElementById('exportId'):", document.getElementById('exportId'))

    // 转换成canvas
    html2canvas(document.getElementById('exportId'), {
        useCORS: true, // 允许跨域图片
        allowTaint: true, // 允许污染的画布
        logging: false, // 关闭日志
        scale: 2 // 提高缩放比例以获得更清晰的截图
    }).then(function (canvas) {
       // console.log('🚀 ~ onExport ~ canvas:', canvas)
        // 创建a标签，实现下载
        let creatIMg = document.createElement('a')
        creatIMg.download = '光伏电站承载能力评估结果.png' // 设置下载的文件名，

        creatIMg.href = canvas.toDataURL() // 下载url
        creatIMg.click()
        creatIMg.remove() // 下载之后把创建的元素删除
    })
}

onMounted(() => {
    getUser()
    formRef.value?.resetFields()
    // 查看

    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>
.button-group {
    position: absolute;
    bottom: -45px;
    right: 10px;
}
// .card-header {
//     font-weight: 600;
// }
.SelectIcon {
    height: 18px;
    margin-top: 5px;
    color: blue;
}
:deep(.el-select__placeholder) {
    span {
        font-size: 14px;
        font-weight: 500;
    }
}
.card-container {
    display: flex;
    position: relative;
}
.evaluateTheResults {
    display: flex;
}
:deep(.el-tag) {
    display: inline-block;
    width: 55px;
    height: 24px;
    .el-tag__content{
        line-height: 23px;
    }
    
}
</style>
