<script lang="ts" setup name="EditArea">
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { getDictByCode } from '@/api/system/dict'
import { addMonitorStation, getDeviceList, getMonitorStationDetail, updateMonitorStation } from '@/api/api/index'
const emits = defineEmits(['refresh'])
const dataFormRef = ref()
const dialogFormVisible = ref(false) // 对话框是否显示
const dialogStatus = ref('') // 对话框类型：create,update
const isEditMode = ref(true)
const areaForm = ref({
  nodeId: '', // 发电机组对应节点数
  pg: '', // 发电机有功/MW
  qg: '', // 发电机无功
  qmax: '', // 最大无功
  qmin: '', // 最小无功
  vg: '', // 节点电压
  mbase: '', // 发电机容量
  status: '', // 运行状态
  pmax: '', // 最大有功
  pmin: '', // 最小有功
  strength: '', // 碳排强度
  stationType: '0',
  stationName: '',
  deviceId: '',
}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  nodeId: [{ required: true, message: '发电机组对应节点数不能为空', trigger: ['blur', 'change'] }],
  pg: [{ required: true, message: '发电机有功不能为空', trigger: ['blur', 'change'] }],
  qg: [{ required: true, message: '发电机无功不能为空', trigger: ['blur', 'change'] }],
  qmax: [{ required: true, message: '最大无功不能为空', trigger: ['blur', 'change'] }],
  qmin: [{ required: true, message: '最小无功不能为空', trigger: ['blur', 'change'] }],
  vg: [{ required: true, message: '节点电压不能为空', trigger: ['blur', 'change'] }],
  mbase: [{ required: true, message: '发电机容量不能为空', trigger: ['blur', 'change'] }],
  status: [{ required: true, message: '运行状态不能为空', trigger: ['blur', 'change'] }],
  pmax: [{ required: true, message: '最大有功不能为空', trigger: ['blur', 'change'] }],
  pmin: [{ required: true, message: '最小有功不能为空', trigger: ['blur', 'change'] }],
  strength: [{ required: true, message: '碳排强度不能为空', trigger: ['blur', 'change'] }],
  stationName: [{ required: true, message: '名称不能为空', trigger: ['blur', 'change'] }],
  deviceId: [{ required: true, message: '设备不能为空', trigger: ['blur', 'change'] }],
} // 前端校验规则

// 重置表单
const resetForm = () => {
  areaForm.value = {
    nodeId: '', // 发电机组对应节点数
    pg: '', // 发电机有功/MW
    qg: '', // 发电机无功
    qmax: '', // 最大无功
    qmin: '', // 最小无功
    vg: '', // 节点电压
    mbase: '', // 发电机容量
    status: '', // 运行状态
    pmax: '', // 最大有功
    pmin: '', // 最小有功
    strength: '', // 碳排强度
    stationType: '0',
    stationName: '',
    deviceId: '',
  }
}
const statusTypeList = ref<any[]>([])
// 获取运行状态
const fetchStatusType = () => {
  getDictByCode('station_status').then((res) => {
    statusTypeList.value = res.data
  })
}
fetchStatusType()
// 获取设备列表
const deviceList = ref<any[]>([])
const fetchDeviceList = () => {
  getDeviceList({ limit: 9999, offset: 1 }).then((res) => {
    deviceList.value = res.data.rows
  })
}
fetchDeviceList()
// 初始化对话框
const initDialog = (dialogStatusValue: string, row: any) => {
  dialogStatus.value = dialogStatusValue
  dialogFormVisible.value = true
  btnLoading.value = false
  if (dialogStatus.value === 'create') { // 如果是新增，清除验证
    resetForm()
    isEditMode.value = false
    nextTick(() => {
      dataFormRef.value.clearValidate()
    })
  }
  else if (dialogStatus.value === 'update') { // 如果是修改，将row中数据填写到输入框中
    getMonitorStationDetail(row.id).then((res) => {
      areaForm.value = res.data
      areaForm.value.status = areaForm.value.status.toString()
      isEditMode.value = true
    })
    // areaForm.value = row
    // isEditMode.value = true
  }
}
defineExpose({
  initDialog,
})

// 新增数据
const createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      addMonitorStation(areaForm.value).then((response) => {
        if (response.code === 200) {
          btnLoading.value = false
          // 通知父组件刷新状态
          setTimeout(() => {
            emits('refresh')
          })
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          dialogFormVisible.value = false
        }
      }).catch((_) => { // 异常情况，loading置为false
        btnLoading.value = false
      })
    }
  })
}

// 修改数据
const updateData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      updateMonitorStation(areaForm.value).then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          dataFormRef.value.clearValidate()
          setTimeout(() => {
            emits('refresh')
          })
          dialogFormVisible.value = false
        }
      }).catch((_) => { // 异常情况，loading置为false
        btnLoading.value = false
      })
    }
  })
}

// 保存数据
const saveData = () => {
  if (dialogStatus.value === 'update') {
    updateData()
  }
  else if (dialogStatus.value === 'create') {
    createData()
  }
}
const cancel = () => {
  dialogFormVisible.value = false
}
</script>

<template>
  <el-dialog v-model="dialogFormVisible" :title="textMap[dialogStatus]" append-to-body>
    <el-form ref="dataFormRef" :rules="rules" :model="areaForm" label-position="right" label-width="160px">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="名称:" prop="stationName">
            <el-input v-model="areaForm.stationName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备列表:" prop="deviceId">
            <el-select
              v-model="areaForm.deviceId" class="m-2"
              style="width: 100%;"
            >
              <el-option v-for="item in deviceList" :key="item.id" :label="item.deviceName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="对应节点数:" prop="nodeId">
            <el-input v-model="areaForm.nodeId" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发电机有功/MW:" prop="pg">
            <el-input v-model="areaForm.pg" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="发电机无功:" prop="qg">
            <el-input v-model="areaForm.qg" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大无功:" prop="qmax">
            <el-input v-model="areaForm.qmax" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="最小无功:" prop="qmin">
            <el-input v-model="areaForm.qmin" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="节点电压:" prop="vg">
            <el-input v-model="areaForm.vg" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="发电机容量:" prop="mbase">
            <el-input v-model="areaForm.mbase" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="运行状态:" prop="status">
            <el-select
              v-model="areaForm.status" class="m-2"
              style="width: 100%;"
            >
              <el-option v-for="item in statusTypeList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="最大有功:" prop="pmax">
            <el-input v-model="areaForm.pmax" :placeholder="dialogStatus === 'create' ? '请输入最大有功' : ''" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最小有功:" prop="pmin">
            <el-input v-model="areaForm.pmin" :placeholder="dialogStatus === 'create' ? '请输入最小有功' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="碳排强度:" prop="strength">
            <el-input v-model="areaForm.strength" :placeholder="dialogStatus === 'create' ? '请输入碳排强度' : ''" />
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="btnLoading" type="primary" @click="saveData">
          保存
        </el-button>
        <el-button @click="cancel">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.el-dialog {
  width: 700px;
}

.el-select {
  width: 100%;
}
</style>
