<script lang="ts" setup name="EditArea">
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { addCarbonOtherMonitor, getDeviceList, updateCarbonOtherMonitor } 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 type = ref('') // (0用电 1用热  2用气)
const areaForm = ref({
  deviceId: '',
  monitorUnit: '',
  monitorVal: '',
  pd: '',
  qd: '',
  id: '',
  createTime: '',
}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  deviceId: [{ required: true, message: '请先选择设备', trigger: ['blur', 'change'] }],
  monitorVal: [{ required: true, message: '请输入数值', trigger: ['blur', 'change'] }],
  monitorUnit: [{ required: true, message: '请输入单位', trigger: ['blur', 'change'] }],
  pd: [{ required: true, message: '请输入负荷有功功率', trigger: ['blur', 'change'] }],
  qd: [{ required: true, message: '请输入负荷无功功率', trigger: ['blur', 'change'] }],
} // 前端校验规则
// 获取设备列表
const deviceList = ref<any>([])
const fetchDeviceList = () => {
  getDeviceList({ deviceClassify: type.value }).then((res) => {
    deviceList.value = res.data
  })
}
// 重置表单
const resetForm = () => {
  areaForm.value = {
    deviceId: '',
    monitorUnit: '',
    monitorVal: '',
    pd: '',
    qd: '',
    id: '',
    createTime: '',
  }
}
// 初始化对话框
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中数据填写到输入框中
    areaForm.value = row
    isEditMode.value = true
  }
  // 保存类型
  type.value = row.type
  // 获取设备列表
  fetchDeviceList()
}
defineExpose({
  initDialog,
})
// 新增数据
const createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      areaForm.value.createTime = dayjs().format('YYYY-MM-DD hh:mm:ss')
      addCarbonOtherMonitor(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) {
      areaForm.value.createTime = dayjs().format('YYYY-MM-DD hh:mm:ss')
      btnLoading.value = true
      updateCarbonOtherMonitor(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="120px">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="设备列表:" prop="deviceId">
            <el-select
              v-model="areaForm.deviceId" class="m-2" :placeholder="dialogStatus === 'create' ? '请选择设备' : ''"
              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 v-if="type !== '0'" :gutter="20">
        <el-col :span="20">
          <el-form-item label="数值:" prop="monitorVal">
            <el-input v-model="areaForm.monitorVal" :placeholder="dialogStatus === 'create' ? '请输入数值' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-else :gutter="20">
        <el-col :span="20">
          <el-form-item label="负荷有功功率:" prop="pd">
            <el-input v-model="areaForm.pd" :placeholder="dialogStatus === 'create' ? '请输入负荷有功功率' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="type !== '0'" :gutter="20">
        <el-col :span="20">
          <el-form-item label="单位:" prop="monitorUnit">
            <el-input v-model="areaForm.monitorUnit" :placeholder="dialogStatus === 'create' ? '请输入单位' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-else :gutter="20">
        <el-col :span="20">
          <el-form-item label="负荷无功功率:" prop="qd">
            <el-input v-model="areaForm.qd" :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>
