<template>
    <el-dialog draggable v-model="add" title="问题新增" width="400px" :before-close="handleClose">
        <el-divider content-position="left">第一步 基本信息填报</el-divider>
        <el-form :inline="true" ref="ruleForm" :rules="rules" label-width="auto" class="form-one" :model="addData">
            <el-form-item label="所属单位">
                <Area ref="areaRef" v-model="addData.orgNo" disabled />
            </el-form-item>

            <el-form-item label="问题来源" prop="problemSources">
                <el-select v-model="addData.problemSources" clearable placeholder="请选择问题来源" filterable>
                    <el-option
                        v-for="item in problemData"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="问题名称" prop="problemName">
                <el-input v-model="addData.problemName" clearable placeholder="请填写问题名称"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="nextStep">下一步</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 新增第二步(在线监测超标问题新增) -->
    <el-dialog draggable title="在线监测超标问题新增" v-model="onlineAdd" width="1500px" :before-close="handleClose">
        <el-divider content-position="left">第二步 选择问题测点</el-divider>
        <el-form :inline="true" class="form">
            <el-form-item label="告警时间">
                <DatePicker ref="DateRef" />
            </el-form-item>
            <el-form-item label="稳态指标">
                <el-select v-model="harmonicTypes" multiple collapse-tags placeholder="请选择稳态指标" filterable>
                    <el-option v-for="item in harmonicTypesList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="越线天数占比(%)">
                <el-input-number v-model="rate" :min="0" :max="100" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-Search" @click="searchOnLine">查询</el-button>
            </el-form-item>
        </el-form>
        <vxe-table v-bind="defaultAttribute" v-loading="isLoading1" height="350" ref="xTable1Ref" :data="onlineAddData">
            <vxe-column type="radio" width="60"></vxe-column>
            <vxe-column field="sustationName" title="变电站"></vxe-column>
            <vxe-column field="barName" title="母线"></vxe-column>
            <vxe-column field="measurementPointName" title="监测点名称"></vxe-column>
            <vxe-column field=" " title="监测点编号"></vxe-column>
            <vxe-column field="loadType" title="监测对象类型"></vxe-column>
            <vxe-column field="objName" title="监测对象"></vxe-column>
            <vxe-column field="voltageLevel" title="电压等级"></vxe-column>
            <vxe-column field="harmonicType" title="告警类型" :formatter="formatter"></vxe-column>
            <vxe-column field="overLimitrate" title="越线天数占比">
                <template #default="{ row }">
                    <el-dropdown>
                        <span class="el-dropdown-link">
                            {{ row.overLimitrate.toFixed(3) }}
                            <el-icon class="el-icon--right">
                                <arrow-down />
                            </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-for="item in row?.dateList">{{ item }}</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </vxe-column>
        </vxe-table>

        <div style="display: flex; justify-content: center; margin-top: 10px">
            <el-button type="primary" class="ml20" @click="previouStep">上一步</el-button>
            <el-button type="primary" class="ml20" @click="OnlineMonitoring">生成问题</el-button>
            <el-button type="primary" class="ml20" @click="handleClose">取消</el-button>
        </div>
    </el-dialog>

    <!-- 新增第二步(普测超标问题新增) -->
    <el-dialog draggable title="普测超标问题新增" v-model="ordinaryAdd" width="1200px" :before-close="handleClose">
        <el-divider content-position="left">第二步 选择普测计划及问题类型</el-divider>
        <el-form :model="ordinaryA" :inline="true" class="form">
            <el-form-item>
                <Area v-model="ordinaryA.orgNo"></Area>
            </el-form-item>

            <el-form-item label="普测结果上传时间">
                <el-date-picker
                    v-model="ordinaryA.planStartTime"
                    type="month"
                    format="YYYY-MM"
                    value-format="YYYY-MM-DD"
                    placeholder="选择月"
                    @change="queryPlanName"
                ></el-date-picker>
            </el-form-item>

            <el-form-item label="普测计划名称">
                <el-select v-model="ordinaryA.planName" clearable placeholder="请选择" filterable>
                    <el-option
                        v-for="item in planNameList"
                        :key="item.planName"
                        :label="item.planName"
                        :value="item.planName"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-Search" @click="searchFnExcessive">查询</el-button>
            </el-form-item>
        </el-form>
        <vxe-table
            v-bind="defaultAttribute"
            v-loading="isLoading2"
            height="350"
            ref="xTable2Ref"
            :data="ordinaryAddData"
        >
            <vxe-column type="radio" width="60"></vxe-column>
            <vxe-column field="subName" title="变电站名称"></vxe-column>
            <vxe-column field="voltageLevelName" title="变电站电压等级"></vxe-column>
        </vxe-table>

        <el-divider content-position="left">第三步 选择问题指标</el-divider>
        <el-form :model="ordinaryA" :rules="rules" ref="ordinaryARef" :inline="true" class="form">
            <el-form-item label="稳态指标" prop="steadyState">
                <el-checkbox-group v-model="ordinaryA.steadyState">
                    <el-checkbox v-for="(item, ind) in steadyStateList" :key="ind" :label="item.code">
                        {{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <br />
            <el-form-item label="暂态指标" prop="transientIndicators">
                <el-checkbox-group v-model="ordinaryA.transientIndicators">
                    <el-checkbox v-for="(item, ind) in transientIndicatorsList" :key="ind" :label="item.code">
                        {{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>

        <div style="display: flex; justify-content: center; margin-top: 10px">
            <el-button type="primary" class="ml20" @click="previouStep">上一步</el-button>
            <el-button type="primary" class="ml20" @click="GeneralSurvey">生成问题</el-button>
            <el-button type="primary" class="ml20" @click="handleClose">取消</el-button>
        </div>
    </el-dialog>
    <!-- 新增第二步(运维异常问题新增) -->
    <el-dialog draggable title="运维异常问题新增" v-model="operationAdd" width="1200px" :before-close="handleClose">
        <el-divider content-position="left">第二步 选择普测计划及问题类型</el-divider>
        <el-form :model="operationAdddata" ref="operationAddRef" :inline="true" :rules="rules">
            <el-form-item label="异常终端名称:" prop="abnormalDevName">
                <el-input
                    v-model="operationAdddata.abnormalDevName"
                    clearable
                    placeholder="请填写异常终端名称"
                ></el-input>
            </el-form-item>

            <el-form-item label="发现异常时间:" prop="abnormalDevTime">
                <el-date-picker
                    v-model="operationAdddata.abnormalDevTime"
                    type="date"
                    placeholder="请选择发现异常时间"
                    value-format="YYYY-MM-DD"
                ></el-date-picker>
            </el-form-item>
            <br />
            <el-form-item label="终端异常描述:" style="margin-top: 10px" prop="eventDescription">
                <el-input
                    type="textarea"
                    style="width: 400px"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请填写终端异常描述"
                    v-model="operationAdddata.eventDescription"
                ></el-input>
            </el-form-item>

            <el-divider content-position="left">第三步 选择问题指标</el-divider>
            <el-form-item label="稳态指标:" prop="steadyState">
                <el-checkbox-group v-model="operationAdddata.steadyState">
                    <el-checkbox v-for="(item, ind) in steadyStateList" :key="ind" :label="item.code">
                        {{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <br />
            <el-form-item label="暂态指标:" prop="transientIndicators">
                <el-checkbox-group v-model="operationAdddata.transientIndicators">
                    <el-checkbox v-for="(item, ind) in transientIndicatorsList" :key="ind" :label="item.code">
                        {{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>

        <div style="display: flex; justify-content: center; margin-top: 10px">
            <el-button type="primary" class="ml20" @click="previouStep">上一步</el-button>
            <el-button type="primary" class="ml20" @click="generateAbnormal">生成问题</el-button>
            <el-button type="primary" class="ml20" @click="handleClose">取消</el-button>
        </div>
    </el-dialog>

    <!-- 新增第二步(用户投诉问题新增) -->
    <el-dialog draggable title="用户投诉问题新增" v-model="userAdd" width="1200px" :before-close="handleClose">
        <el-divider content-position="left">第二步 选择投诉用户</el-divider>
        <el-form :model="userAdddata" :inline="true" ref="userAddRef" :rules="rules">
            <el-form-item label="用户名称:" prop="userName">
                <el-input v-model="userAdddata.userName" clearable placeholder="请输入用户名称"></el-input>
            </el-form-item>
            <el-form-item label="用户编号:" prop="userNo">
                <el-input v-model="userAdddata.userNo" clearable placeholder="请输入用户编号"></el-input>
            </el-form-item>

            <el-divider content-position="left">第三步 填写投诉详情</el-divider>

            <el-form-item label="投诉内容:" style="margin-top: 10px" prop="complaintContent">
                <el-input
                    type="textarea"
                    style="width: 400px"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入内容"
                    v-model="userAdddata.complaintContent"
                ></el-input>
            </el-form-item>
            <br />
            <el-form-item label="投诉时间:" style="margin-top: 10px" prop="complaintTime">
                <el-date-picker
                    v-model="userAdddata.complaintTime"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DD"
                ></el-date-picker>
            </el-form-item>

            <el-divider content-position="left">第四步 选择问题指标</el-divider>

            <el-form-item label="稳态指标:" prop="steadyState">
                <el-checkbox-group v-model="userAdddata.steadyState">
                    <el-checkbox v-for="(item, ind) in steadyStateList" :key="ind" :label="item.code">
                        {{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <br />
            <el-form-item label="暂态指标:" prop="transientIndicators">
                <el-checkbox-group v-model="userAdddata.transientIndicators">
                    <el-checkbox v-for="(item, ind) in transientIndicatorsList" :key="ind" :label="item.code">
                        {{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>

        <div style="display: flex; justify-content: center; margin-top: 10px">
            <el-button type="primary" class="ml20" @click="previouStep">上一步</el-button>
            <el-button type="primary" class="ml20" @click="userAddProblem">生成问题</el-button>
            <el-button type="primary" class="ml20" @click="handleClose">取消</el-button>
        </div>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useDictData } from '@/stores/dictData'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import Area from '@/components/form/area/index.vue'
import DatePicker from '@/components/form/datePicker/index.vue'
import { ArrowDown } from '@element-plus/icons-vue'
const emit = defineEmits(['handleClose', 'onSubmit'])
const dictData = useDictData()
const problemData = dictData.getBasicData('Problem_Sources')
const alarmList = dictData.getBasicData('alarm_Type')
const Voltage = dictData.getBasicData('Dev_Voltage')
const userTypeData = dictData.getBasicData('User_Category')
import {
    getRMpPartHarmonicDetail,
    querySurveyPlanName,
    querySurveyPlanOnQuestion,
    addAbnormalIssues,
    addComplaintIssues,
    addGeneralSurveyIssues,
    addExcessiveIssues
} from '@/api/process-boot/electricitymanagement'
import { ElMessage } from 'element-plus'
const steadyStateList = dictData.getBasicData('Steady_Indicator')
const transientIndicatorsList = dictData.getBasicData('Transient_Indicators')

const add = ref(true)
const onlineAdd = ref(false)
const isLoading1 = ref(false)
const isLoading2 = ref(false)
const ordinaryAdd = ref(false)
const userAdd = ref(false)
const operationAdd = ref(false)
const ruleForm = ref()
const DateRef = ref()
const userAddRef = ref()
const operationAddRef = ref()
const ordinaryARef = ref()
const xTable1Ref = ref()
const xTable2Ref = ref()
const harmonicTypes = ref([]) //稳态指标id集合
const harmonicTypesList = dictData.getBasicData('Indicator_Type')
const rate = ref(60) //越线天数占比（一个月）
const addData = ref({
    orgName: '',
    problemSources: '',
    problemName: '',
    orgNo: dictData.state.area[0].id
})
const ordinaryA = ref({
    orgNo: '',
    orgName: '',
    planName: '',
    planStartTime: '',
    uploadTime: '',
    name: '',
    steadyState: [],
    transientIndicators: []
})
const operationAdddata = ref({
    abnormalDevName: '',
    eventDescription: '',
    abnormalDevTime: '',
    steadyState: [],
    transientIndicators: []
})
const userA = ref({
    userType: 'Elec_User',
    id: ''
})
const userAdddata = ref({
    complaintContent: '',
    complaintTime: '',
    steadyState: [],
    userName: '',
    userNo: '',
    transientIndicators: []
})
const planNameList: any = ref([])
const onlineAddData = ref([])
const ordinaryAddData = ref([])
const rules = {
    problemName: [{ required: true, message: '请输入问题名称', trigger: 'blur' }],
    userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
    userNo: [{ required: true, message: '请输入用户编号', trigger: 'blur' }],
    complaintContent: [{ required: true, message: '请输入投诉内容', trigger: 'blur' }],
    complaintTime: [{ required: true, message: '请选择时间', trigger: 'change' }],
    problemSources: [{ required: true, message: '情选择问题来源', trigger: 'change' }],
    abnormalDevTime: [{ required: true, message: '请选择时间', trigger: 'change' }],
    transientIndicators: [{ required: true, message: '请选择暂态指标', trigger: 'change' }],
    steadyState: [{ required: true, message: '请选择稳态指标', trigger: 'change' }],
    eventDescription: [{ required: true, message: '请输入终端异常描述', trigger: 'blur' }],
    abnormalDevName: [{ required: true, message: '请输入问题名称', trigger: 'blur' }]
}

// 关闭
const handleClose = () => {
    emit('handleClose')
    emit('onSubmit')
}
// 下一步
const nextStep = () => {
    ruleForm.value.validate((valid: any) => {
        if (valid) {
            if (addData.value.problemSources == 'Online') {
                add.value = false

                onlineAdd.value = true
                setTimeout(() => {
                    DateRef.value.setTimeOptions([{ label: '月份', value: 3 }])
                    searchOnLine()
                }, 0)
            } else if (addData.value.problemSources == 'General') {
                ordinaryA.value.orgNo = dictData.state.area[0].id
                ordinaryA.value.orgName = dictData.state.area[0].name

                add.value = false
                ordinaryAdd.value = true
                ordinaryA.value.planStartTime = window.XEUtils.toDateString(new Date().getTime(), 'yyyy-MM') + '-01'

                queryPlanName()
                setTimeout(() => {
                    searchFnExcessive()
                }, 0)
            } else if (addData.value.problemSources == 'User_Complaints') {
                add.value = false
                userAdd.value = true
            } else if (addData.value.problemSources == 'Dev_Exception') {
                add.value = false
                operationAdd.value = true
            }
        }
    })
}
// 上一步
const previouStep = () => {
    onlineAdd.value = false
    ordinaryAdd.value = false
    userAdd.value = false
    operationAdd.value = false
    add.value = true
}

// 在线监测超标问题新增
const OnlineMonitoring = () => {
    if (xTable1Ref.value.getRadioRecord() == null) {
        return ElMessage.warning('请选择变电站')
    } else {
        addExcessiveIssues({
            warnTarget:xTable1Ref.value.getRadioRecord().harmonicType,
            ...xTable1Ref.value.getRadioRecord(),
            ...addData.value
        }).then((res: any) => {
            ElMessage.success('新增成功!')
            emit('handleClose')
            emit('onSubmit')
        })
    }
}
// 在线监测告警查询
const searchOnLine = () => {
    isLoading1.value = true
    getRMpPartHarmonicDetail({
        harmonicTypes: harmonicTypes.value,
        rate: rate.value * 0.01,
        startTime: DateRef.value.timeValue[0],
        endTime: DateRef.value.timeValue[1]
    }).then(res => {
        isLoading1.value = false
        onlineAddData.value = res.data
    })
}

// 普通监测超标问题新增
const queryPlanName = () => {
    querySurveyPlanName({
        orgNo: ordinaryA.value.orgNo,
        planStartTime: ordinaryA.value.planStartTime
    }).then(res => {
        planNameList.value = res.data
    })
}
const searchFnExcessive = () => {
    isLoading2.value = true
    querySurveyPlanOnQuestion(ordinaryA.value).then(res => {
        isLoading2.value = false
        ordinaryAddData.value = res.data
    })
}
// 普测超标生成问题
const GeneralSurvey = () => {
    if (xTable2Ref.value.getRadioRecord() == null) {
        return ElMessage.warning('请选择变电站')
    } else {
        ordinaryARef.value.validate((valid: any) => {
            if (valid) {
                addGeneralSurveyIssues({
                    substationId: xTable2Ref.value.getRadioRecord().subId,
                    ...xTable2Ref.value.getRadioRecord(),
                    ...ordinaryA.value,
                    ...addData.value
                }).then((res: any) => {
                    ElMessage.success('新增成功!')
                    emit('handleClose')
                    emit('onSubmit')
                })
            }
        })
    }
}
const formatter = (row: any) => {
    if (row.column.field == 'harmonicType') {
        return harmonicTypesList.filter((item: any) => item.id == row.cellValue)[0]?.name
    } else if (row.column.field == 'voltageLevel') {
        return Voltage.filter((item: any) => item.id == row.cellValue)[0]?.name
    } else if (row.column.field == 'electricityType') {
        return dictData.getBasicData('Ele_Class').filter((item: any) => item.id == row.cellValue)[0]?.name
    } else {
        return row.cellValue
    }
}
// 运维异常问题新增
const generateAbnormal = () => {
    operationAddRef.value.validate((valid: any) => {
        if (valid) {
            addAbnormalIssues({
                ...operationAdddata.value,
                ...addData.value
            }).then((res: any) => {
                ElMessage.success('新增成功!')
                emit('handleClose')
                emit('onSubmit')
            })
        }
    })
}

// 用户投诉新增
const userAddProblem = () => {
    userAddRef.value.validate((valid: any) => {
        if (valid) {
            addComplaintIssues({
                ...userAdddata.value,
                ...addData.value
            }).then((res: any) => {
                ElMessage.success('新增成功!')
                emit('handleClose')
                emit('onSubmit')
            })
        }
    })
}
onMounted(() => {})
</script>
<style lang="scss" scoped>
.el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary) !important;
    display: flex;
    align-items: center;
}
</style>
