<script lang="ts" setup name="EditArea">
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { addCollectList, getDeviceListPage, updateCollectList } from '@/api/api/index'
import { getDictByCode } from '@/api/system/dict'
const emits = defineEmits(['refresh'])
const dataFormRef = ref()
const dialogFormVisible = ref(false) // 对话框是否显示
const dialogStatus = ref('') // 对话框类型：create,update
const isEditMode = ref(true)
const areaForm = ref({
  deviceId: '',
  uploadTime: '',
  frequency: '',
  deviceStat: '',
  collectionType: '',
}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  collectTyle: [{ required: true, message: '请选择采集类型', trigger: ['blur', 'change'] }],
  deviceId: [{ required: true, message: '请选择设备', trigger: ['blur', 'change'] }],
  frequency: [{ required: true, message: '请输入上传频率', trigger: ['blur', 'change'] }],
  uploadTime: [{ required: true, message: '请选择上传时间', trigger: ['blur', 'change'] }],
  deviceStat: [{ required: true, message: '请选择设备状态', trigger: ['blur', 'change'] }],
  collectionType: [{ required: true, message: '请选择采集类型', trigger: ['blur', 'change'] }],
} // 前端校验规则

// 重置表单
const resetForm = () => {
  areaForm.value = {
    deviceId: '',
    uploadTime: '',
    frequency: '',
    deviceStat: '',
  }
}
// 初始化对话框
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
  }
}
defineExpose({
  initDialog,
})
// 获取设备列表
const deviceList = ref<any>([])
const fetchDeviceList = () => {
  getDeviceListPage({ offset: 1, limit: 99999 }).then((res) => {
    deviceList.value = res.data.rows
  })
}
const collectTypeList = ref([])
// 获取采集分类列表
const getCollectionType = () => {
  getDictByCode('collection_type').then((res) => {
    collectTypeList.value = res.data
  })
}
const deviceStatusList = ref([])
// 获取设备状态列表
const getDeviceStatus = () => {
  getDictByCode('stat_type').then((res) => {
    deviceStatusList.value = res.data
  })
}
getCollectionType()
getDeviceStatus()
fetchDeviceList()
// 新增数据
const createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      areaForm.value.uploadTime = dayjs().format('YYYY-MM-DD')
      btnLoading.value = true
      addCollectList(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
      updateCollectList(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="collectionType">
            <el-select v-model="areaForm.collectionType" class="m-2" :placeholder="dialogStatus === 'create' ? '请选择采集类型' : ''" style="width: 100%;">
              <el-option
                v-for="item in collectTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <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 :gutter="20">
        <el-col :span="20">
          <el-form-item label="上传时间:" prop="uploadTime">
            <el-date-picker
              v-model="areaForm.uploadTime"
              type="datetime"
              value-format="YYYY-MM-DD"
              :placeholder="dialogStatus === 'create' ? '请选择上传时间' : ''"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="上报频率:" prop="frequency">
            <el-input v-model="areaForm.frequency" :placeholder="dialogStatus === 'create' ? '请输入上报频率' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="设备状态:" prop="deviceId">
            <el-select v-model="areaForm.deviceStat" class="m-2" :placeholder="dialogStatus === 'create' ? '请选择状态' : ''" style="width: 100%;">
              <el-option
                v-for="item in deviceStatusList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </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>
