<script lang="ts" setup name="EditArea">
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { addEnvironmentList, updateEnvironmentList } 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({
  id: '',
  temperature: '', // 温度
  humidity: '', // 湿度
  windSpeed: '', // 风速
  windDirection: '', // 风向
  // atmos: '', // 大气压
  // rainfall: '', // 降雨量
  // careRadiation: '', // 光照辐射量
  // totalRadiation: '', // 总辐射量
  uploadTime: '',
  temDay: '',
  temNight: '',
  city: '',
  wea: '',
  // wea: '',
}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  temperature: [{ required: true, message: '请输入上传温度', trigger: ['blur', 'change'] }],
  humidity: [{ required: true, message: '请输入上传湿度', trigger: ['blur', 'change'] }],
  windSpeed: [{ required: true, message: '请输入上传风速', trigger: ['blur', 'change'] }],
  windDirection: [{ required: true, message: '请输入上传风向', trigger: ['blur', 'change'] }],
  atmos: [{ required: true, message: '请输入大气压', trigger: ['blur', 'change'] }],
  rainfall: [{ required: true, message: '请输入降雨量', trigger: ['blur', 'change'] }],
  careRadiation: [{ required: true, message: '请输入光照辐射量', trigger: ['blur', 'change'] }],
  totalRadiation: [{ required: true, message: '请输入总辐射量', trigger: ['blur', 'change'] }],
} // 前端校验规则

// 重置表单
const resetForm = () => {
  areaForm.value = {
    id: '',
    temperature: '', // 温度
    humidity: '', // 湿度
    windSpeed: '', // 风速
    windDirection: '', // 风向
    // atmos: '', // 大气压
    // rainfall: '', // 降雨量
    // careRadiation: '', // 光照辐射量
    // totalRadiation: '', // 总辐射量
    temDay: '',
    temNight: '',
    city: '',
    wea: '',
    uploadTime: '',
  }
}
// 初始化对话框
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
    console.log(row, 'row')
    isEditMode.value = true
  }
}
defineExpose({
  initDialog,
})
// 新增数据
const createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      areaForm.value.uploadTime = dayjs().format('YYYY-MM-DD')
      btnLoading.value = true
      addEnvironmentList(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.uploadTime = dayjs().format('YYYY-MM-DD')
      btnLoading.value = true
      updateEnvironmentList(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
}
// 天气列表
const weaList = ref([
  { label: '晴' },
  { label: '多云' },
  { label: '阴' },
  { label: '小雨' },
  { label: '阵雨' },
  { label: '雷阵雨' },
  { label: '雨' },
  { label: '雷' },
  { label: '雨夹雪' },
  { label: '雪' },
  { label: '雾霾' },
  { label: '沙尘' },
])
</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="24">
        <el-col :span="12">
          <el-form-item label="环境温度:" prop="temperature">
            <el-input v-model="areaForm.temperature" :placeholder="dialogStatus === 'create' ? '请输入环境温度' : ''" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="相对湿度:" prop="humidity">
            <el-input v-model="areaForm.humidity" :placeholder="dialogStatus === 'create' ? '请输入相对湿度' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="风速:" prop="windSpeed">
            <el-input v-model="areaForm.windSpeed" :placeholder="dialogStatus === 'create' ? '请输入风速' : ''" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="风向:" prop="windSpeed">
            <el-input v-model="areaForm.windDirection" :placeholder="dialogStatus === 'create' ? '请输入风向' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="高温:" prop="temDay">
            <el-input v-model="areaForm.temDay" :placeholder="dialogStatus === 'create' ? '请输入温度' : ''" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="低温:" prop="temNight">
            <el-input v-model="areaForm.temNight" :placeholder="dialogStatus === 'create' ? '请输入温度' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="城市:" prop="city">
            <el-input v-model="areaForm.city" :placeholder="dialogStatus === 'create' ? '请输入城市' : ''" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="天气情况:" prop="wea">
            <!-- <el-input v-model="areaForm.wea" :placeholder="dialogStatus === 'create' ? '请输入天气情况' : ''" /> -->
            <el-select v-model="areaForm.wea" style="width: 100%;" placeholder="Select">
              <el-option v-for="item in weaList" :key="item.label" :label="item.label" :value="item.label" />
            </el-select>
          </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>
