<!--
  Description: 设备监测新增或修改
  Author: 李亚光
  Date: 2023-04-21
 -->
<script lang="ts" setup name="deviceAdd">
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import showPhoto from './showPhoto.vue'
import { addElectricityList, updateElectricityList, uploadApi } from '@/api/api/index'
import { getUserList } from '@/api/system/user'
const emits = defineEmits(['refresh'])
const dataFormRef = ref()
const dialogFormVisible = ref(false) // 对话框是否显示
const dialogStatus = ref('') // 对话框类型：create,update
const isEditMode = ref(true)
const areaForm = ref({
  electricityName: '', // 配电网名称
  electricityArea: '', // 配电网区域
  uploaderName: '', // 上传人
  uploader: '',
  uploadTime: '', // 上传时间
  electricityDetail: '', // 详情图片
}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  electricityName: [{ required: true, message: '请输入配电网名称', trigger: ['blur', 'change'] }],
  electricityArea: [{ required: true, message: '请输入配电网区域', trigger: ['blur', 'change'] }],
  uploader: [{ required: true, message: '请选择上传人', trigger: ['blur', 'change'] }],
  uploadTime: [{ required: true, message: '请选择上传时间', trigger: ['blur', 'change'] }],
  electricityDetail: [{ required: true, message: '请上传附件', trigger: ['blur', 'change'] }],
} // 前端校验规则
// 获取用户列表
const userList = ref<any[]>([])
const fetchUserList = () => {
  getUserList({ limit: 9999, offset: 1 }).then((res) => {
    userList.value = res.data.rows
  })
}
fetchUserList()
// 重置表单
const resetForm = () => {
  areaForm.value = {
    electricityName: '', // 配电网名称
    electricityArea: '', // 配电网区域
    uploaderName: '', // 上传人+
    uploader: '',
    uploadTime: '', // 上传时间
    electricityDetail: '',
  }
}
const deviceTypeList = ref([])
// 初始化对话框
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 createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      areaForm.value.uploadTime = dayjs().format('YYYY-MM-DD')
      btnLoading.value = true
      addElectricityList(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
      updateElectricityList(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 fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('file', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        dataFormRef.value?.clearValidate('electricityDetail')
        areaForm.value.electricityDetail = res.data
        ElMessage.success('上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
</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="140px">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="设备编号:" prop="electricityName">
            <el-input v-model="areaForm.electricityName" :placeholder="dialogStatus === 'create' ? '请输入设备编号' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="安装位置:" prop="electricityName">
            <el-input v-model="areaForm.electricityName" :placeholder="dialogStatus === 'create' ? '请输入安装位置' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="负荷有功功率:" prop="electricityName">
            <el-input v-model="areaForm.electricityName" :placeholder="dialogStatus === 'create' ? '请输入负荷有功功率' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="负荷无功功率:" prop="electricityName">
            <el-input v-model="areaForm.electricityName" :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>
