<template>
    <el-dialog
        :width="(popupType == 0 || popupType == 1) ? '500px' : (popupType == 2 || popupType == 3) ? '800px' : '1100px'"
        v-model.trim="dialogVisible" :title="title" draggable>
        <!-- 新增方案数据 -->
        <el-form :model="form" scroll-to-error label-width="140px" :rules="rules1" ref="ruleFormRef1" class="form-one"
            v-if="popupType == 0 || popupType == 1">
            <el-form-item label="方案名称：" prop="itemName">
                <el-input maxlength="32" show-word-limit v-model.trim="form.itemName" placeholder="请输入方案名称" />
            </el-form-item>
            <el-form-item label="方案描述：" prop="describe">
                <el-input show-word-limit maxlength="300" type="textarea" v-model.trim="form.describe"
                    placeholder="请输入方案描述" />
            </el-form-item>
        </el-form>
        <!-- 测试项信息&数据绑定页面 -->
        <el-tabs type="border-card" v-model.trim="activeName" v-if="popupType != 0 && popupType != 1">
            <el-tab-pane label="测试项信息" :name="0" v-if="openType == 'tree'">
                <el-form :model="form1" ref="ruleFormRef2" scroll-to-error class="form-two" label-width="140px"
                    :rules="rules2">
                    <el-form-item label="测试项名称：" prop="itemName">
                        <el-input maxlength="32" show-word-limit v-model.trim="form1.itemName" placeholder="请输入测试项名称" />
                    </el-form-item>
                    <el-form-item label="测量间隔：" prop="statisticalInterval">
                        <el-select v-model.trim="form1.statisticalInterval" placeholder="请选择测量间隔" clearable
                            style="width: 100%">
                            <el-option v-for="(item, index) in statisticalIntervalList" :key="index" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="电压等级：" prop="voltageLevel">
                        <el-select v-model.trim="form1.voltageLevel" placeholder="请选择电压等级" clearable style="width: 100%"
                            @change="changeVoltageLevel">
                            <el-option v-for="(item, index) in voltageLevelList" :key="index" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="接线方式：" prop="volConType">
                        <el-select v-model.trim="form1.volConType" placeholder="请选择接线方式" clearable style="width: 100%">
                            <el-option v-for="(item, index) in volConTypeList" :key="index" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="最小短路容量：" prop="capacitySscmin">
                        <el-input maxlength="32" show-word-limit v-model.trim="form1.capacitySscmin" oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')" autocomplete="off" placeholder="请选择最小短路容量">
                            <template #append>MVA</template>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="用户协议容量：" prop="capacitySi">
                        <el-input maxlength="32" show-word-limit v-model.trim="form1.capacitySi" autocomplete="off"
                            oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')" placeholder="请输入用户协议容量">
                            <template #append>MVA</template>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="基准短路容量：" prop="capacitySscb">
                        <el-input maxlength="32" show-word-limit v-model.trim="form1.capacitySscb" oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')" placeholder="请输入基准短路容量">
                            <template #append>MVA</template>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="供电设备容量：" prop="capacitySt">
                        <el-input maxlength="32" show-word-limit v-model.trim="form1.capacitySt" oninput="value=value.replace(/[^\-?\d.]/g,'')
.replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')
.replace('-','$#$').replace(/\-/g,'').replace('$#$','-')" placeholder="请输入供电设备容量">
                            <template #append>MVA</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="PT变比：" prop="pt">
                        <el-input maxlength="32" show-word-limit style="width: 48%" v-model.number.trim="form1.pt"
                            autocomplete="off" placeholder="请输入PT变比" oninput="value=value.replace(/[^0-9.]/g,'')" />
                        <el-input maxlength="32" show-word-limit style="width: 48%" v-model.number.trim="form1.pt1"
                            autocomplete="off" placeholder="请输入PT变比" oninput="value=value.replace(/[^0-9.]/g,'')" />
                    </el-form-item>
                    <el-form-item label="CT变比：" prop="ct">
                        <el-input maxlength="32" show-word-limit v-model.number.trim="form1.ct" style="width: 48%"
                            autocomplete="off" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入CT变比" />
                        <el-input maxlength="32" show-word-limit v-model.number.trim="form1.ct1" style="width: 48%"
                            autocomplete="off" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入CT变比" />
                    </el-form-item>
                    <el-form-item label="监测位置：" prop="location" style="width: 100%">
                        <el-input show-word-limit maxlength="300" type="textarea" v-model.trim="form1.location"
                            placeholder="请输入监测位置" />
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="数据绑定" :name="1" v-if="openType == 'table'">
                <TreeTransfers :fromData="unBindList" :toData="bindList" @getData="getData" />
            </el-tab-pane>
        </el-tabs>
        <template #footer="">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="submit">确定</el-button>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { addPlan, addRecord, updateRecord, getDeviceList } from '@/api/cs-device-boot/planData'
import { useDictData } from '@/stores/dictData'
import TreeTransfers from './treeTransfers.vue'
const dictData = useDictData()
const dialogVisible = ref(false)
const voltageLevelList: any = dictData.getBasicData('Dev_Voltage_Stand')
const volConTypeList = dictData.getBasicData('Dev_Connect')
const emit = defineEmits(['onSubmit'])
//表单数据
const form = ref({})
//测试项数据
const form1: any = ref({})
//折叠面板初始值
const activeTab = ref(0)
//tab初始值
const activeName = ref(0)
//测量间隔数据
const statisticalIntervalList = [
    {
        id: 1,
        name: '1分钟'
    },
    {
        id: 3,
        name: '3分钟'
    },
    {
        id: 5,
        name: '5分钟'
    },
    {
        id: 10,
        name: '10分钟'
    }
]
//初始化form
const initForm = () => {
    //方案数据
    form.value = {
        itemName: '', //方案名称
        describe: '' //方案描述
    }
    //测试项数据
    form1.value = {
        itemName: '', //测试项名称
        statisticalInterval: statisticalIntervalList[1].id, //测量间隔
        voltageLevel: voltageLevelList[0].id, //电压等级
        volConType: volConTypeList[0].id, //接线方式
        capacitySscmin: 10, //最小短路容量
        capacitySi: 10, //用户协议容量
        capacitySscb: 10, //基准短路容量
        capacitySt: 10, //供电设备容量
        pt: 1, //pt变比1
        pt1: 1, //pt变比2
        ct: 300, //ct变比1
        ct1: 5, //ct变比2
        location: '' //监测位置
    }
    changeVoltageLevel()
}
const codeValue = (val: any) => {
    return (
        voltageLevelList.find((item: any) => {
            return item.code == val
        })?.value * 1
    )
}
//改变电压等级计算基准短路容量
const changeVoltageLevel = async () => {
    let value: any =
        voltageLevelList.find((item: any) => {
            return item.id == form1.value.voltageLevel
        })?.value * 1
    if (value < codeValue('6kV')) {
        form1.value.capacitySscb = 10
    } else if (value < codeValue('20kV')) {
        form1.value.capacitySscb = 100
    } else if (value < codeValue('35kV')) {
        form1.value.capacitySscb = 200
    } else if (value < codeValue('66kV')) {
        form1.value.capacitySscb = 250
    } else if (value < codeValue('110kV')) {
        form1.value.capacitySscb = 500
    } else if (value < codeValue('220kV')) {
        form1.value.capacitySscb = 750
    } else if (value < codeValue('330kV')) {
        form1.value.capacitySscb = 2000
    } else if (value < codeValue('500kV')) {
        form1.value.capacitySscb = 3000
    } else if (value < codeValue('750kV')) {
        form1.value.capacitySscb = 4500
    } else if (value < codeValue('1000kV')) {
        form1.value.capacitySscb = 7000
    } else {
        form1.value.capacitySscb = 9000
    }

    //PT变比 电压<0.48kv 1:1 电压>0.48 *1000/100
    if (Number(value) <= 0.48) {
        form1.value.pt = 1
        form1.value.pt1 = 1
    }
    if (Number(value) > 0.48) {
        form1.value.pt = value * 10
        form1.value.pt1 = 1
    }
}

initForm()
//方案校验规则
const rules1 = ref({
    //方案名称
    itemName: [
        {
            required: true,
            message: '请输入方案名称',
            trigger: 'blur'
        }
    ],
    //方案名称
    describe: [
        {
            required: true,
            message: '请输入方案描述',
            trigger: 'blur'
        }
    ]
})
//测试项校验规则
const rules2 = ref({
    //测试项名称
    itemName: [
        {
            required: true,
            message: '请输入测试项名称',
            trigger: 'blur'
        }
    ],
    describe: [
        {
            required: true,
            message: '请选择测量间隔',
            trigger: 'change'
        }
    ],
    voltageLevel: [
        {
            required: true,
            message: '请选择电压等级',
            trigger: 'change'
        }
    ],
    volConType: [
        {
            required: true,
            message: '请选择接线方式',
            trigger: 'change'
        }
    ],
    capacitySscmin: [
        {
            required: true,
            message: '请输入最小短路容量',
            trigger: 'blur'
        }
    ],
    capacitySi: [
        {
            required: true,
            message: '请输入用户协议容量',
            trigger: 'blur'
        }
    ],
    capacitySscb: [
        {
            required: true,
            message: '请输入基准短路容量',
            trigger: 'blur'
        }
    ],
    capacitySt: [
        {
            required: true,
            message: '请输入供电设备容量',
            trigger: 'blur'
        }
    ],
    pt: [
        {
            required: true,
            message: '请输入PT变比',
            trigger: 'blur'
        }
    ],
    ct: [
        {
            required: true,
            message: '请输入CT变比',
            trigger: 'blur'
        }
    ],
    location: [
        {
            required: true,
            message: '请输入监测位置',
            trigger: 'blur'
        }
    ]
})
//弹框标题
const title: any = ref('')
//判断页面显示条件
const popupType: any = ref(null)
//方案/测试项id
const planId: any = ref('')
//打开的类型
const openType = ref('')
const detailsType = (val: any) => {
    openType.value = val
    if (val == 'tree') {
        activeName.value = 0
    }
    if (val == 'table') {
        activeName.value = 1
    }
}
//回显方案、测试项操作
const details = (val: any) => {
    if (val) {
        form.value = {
            describe: val.describe,
            itemName: val.itemName
        }
    }
    if (val) {
        form1.value = val
        checkedIdList.value = form1.value.list
    }
}
//未绑定数据tree
const unBindList = ref([])
//已绑定数据tree
const bindList = ref([])
//0 新增方案 1 修改方案 2 新增测试项 3 修改测试项 4 设备信息
const open = async (val: any, id: any, name?: any) => {
    // console.log("🚀 ~ open ~ val:", val)
    popupType.value = val
    title.value = val == 0 ? '新增方案' : val == 1 ? '修改方案' : val == 2 ? '新增测试项' : val == 3 ? '修改测试项' : ('绑定测试项' + '_' + name)
    dialogVisible.value = true
    planId.value = id
    //新增方案或者测试项数据
    if (val == 0 || val == 2) {
        initForm()
    }
    if (val != 0 && val != 1) {
        //1 列表  0树
        // getDeviceList({ id: id, isTrueFlag: 0, pageNum: 1, pageSize: 200 }).then(res => {})
        dialogVisible.value = true
        selectId.value = id
        //0未绑定数据 1 已绑定数据
        //获取未绑定树形数据
        getDeviceList({ id: id, isTrueFlag: 0 }).then(res => {
            unBindList.value = res.data
        })
        //获取已绑定树形数据
        getDeviceList({ id: id, isTrueFlag: 1 }).then(res => {
            bindList.value = res.data
        })
        // activeName.value = 0
    }
}
//获取选择的绑定的数据
const checkedIdList: any = ref([])
const getData = (rightData: any) => {
    checkedIdList.value = []
    if (rightData && rightData.length != 0) {
        rightData.map((item: any) => {
            item.children.map((vv: any) => {
                vv.children.map((kk: any) => {
                    checkedIdList.value.push(kk.id)
                })
            })
        })
    }
    checkedIdList.value = [...new Set(checkedIdList.value)]
}

//判断是否显示新增页面 false显示详情页面和删除按钮隐藏确定按钮 true显示新增页面与确定按钮隐藏删除按钮
const addFlag = ref(false)
const selectId: any = ref('')
//判断是否选择了设备数据
const checkedList: any = ref([])
//关闭
const ruleFormRef1 = ref()
const ruleFormRef2 = ref()
const close = () => {
    dialogVisible.value = false
    //折叠面板
    activeTab.value = 0
    if (addFlag.value) {
        addFlag.value = false
        checkedList.value = []
    } else {
        dialogVisible.value = false
    }

    //取消表单校验状态
    if (popupType.value == 0 || popupType.value == 1) {
        ruleFormRef1.value && ruleFormRef1.value.resetFields()
    } else {
        ruleFormRef2.value && ruleFormRef2.value?.resetFields()
    }
    //tabs
    activeName.value = 0
    unBindList.value = []
    bindList.value = []
    initForm()
}
//提交
const submit = () => {
    //新增方案
    if (popupType.value == 0) {
        ruleFormRef1.value.validate((valid: any) => {
            if (valid) {
                const subForm = {
                    itemName: form.value.itemName,
                    describe: form.value.describe
                }
                addPlan(subForm).then((res: any) => {
                    if (res.code == 'A0000') {
                        ElMessage.success('新增方案成功')
                        initForm()
                        emit('onSubmit')
                        close()
                    }
                })
            } else {
                console.log('表单验证失败')
                return false
            }
        })
    }
    //修改方案
    if (popupType.value == 1) {
        ruleFormRef1.value.validate((valid: boolean) => {
            if (valid) {
                const subForm = {
                    id: planId.value,
                    itemName: form.value.itemName,
                    describe: form.value.describe
                }
                addPlan(subForm).then(res => {
                    ElMessage.success('修改方案成功')
                    emit('onSubmit')
                    close()
                })
            }
        })
    }
    //新增测试项
    if (popupType.value == 2) {
        ruleFormRef2.value.validate((valid: boolean) => {
            if (valid) {
                let subForm = {
                    id: planId.value,
                    records: [form1.value]
                }
                subForm.records[0].list = checkedIdList.value
                addRecord(subForm).then(res => {
                    ElMessage.success('新增测试项成功')
                    initForm()
                    emit('onSubmit')
                    close()
                })
            }
        })
    }
    //修改测试项
    if (popupType.value == 3 || popupType.value == 4) {
        let subForm = JSON.parse(JSON.stringify(form1.value))
        subForm.list = checkedIdList.value
        console.log(title.value.includes('绑定测试项'));

        updateRecord(subForm).then((res: any) => {
            if (res.code == 'A0000') {
                ElMessage.success(title.value.includes('绑定测试项') ? '绑定测试项成功' : '修改测试项成功')
                initForm()
                emit('onSubmit')
                close()
            }
        })
    }
}
defineExpose({ open, details, detailsType })
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
    display: flex !important;
    justify-content: space-between !important;
}

::v-deep .form-two {
    .el-select {
        width: 100% !important;
    }
}

.button_info {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin: 10px 0;
}

.device_info {
    width: 100%;
    display: flex;

    .left_device,
    .right_device {
        width: 410px;
        border: 1px solid #eee;
        padding-right: 10px;

        p {
            margin: 10px 10px 0 10px;
            font-weight: 800;
            font-size: 14px;
        }
    }

    .center_bind {
        flex: 1;
        display: flex;
        padding: 0 30px;
        align-items: center;
        justify-content: center;
    }
}
</style>
