<script lang="ts" setup name="EditArea">
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: '', // 配电网名称
  basePower: '', // 基准功率
  nodeNum: '', // 系统节点数
  genNum: '', // 发电机数
  loadNum: '', // 系统负荷数
  branchNum: '', // 节点之间支路数
}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  electricityName: [{ required: true, message: '请输入配电网名称', trigger: ['blur', 'change'] }],
  basePower: [{ required: true, message: '请输入基准功率', trigger: ['blur', 'change'] }],
  nodeNum: [{ required: true, message: '请输入系统节点数', trigger: ['blur', 'change'] }],
  genNum: [{ required: true, message: '请输入发电机数', trigger: ['blur', 'change'] }],
  loadNum: [{ required: true, message: '请输入系统负荷数', trigger: ['blur', 'change'] }],
  branchNum: [{ required: true, message: '请输入节点之间支路数', trigger: ['blur', 'change'] }],
} // 前端校验规则
// 重置表单
const resetForm = () => {
  areaForm.value = {
    electricityName: '', // 配电网名称
    basePower: '', // 基准功率
    nodeNum: '', // 系统节点数
    genNum: '', // 发电机数
    loadNum: '', // 系统负荷数
    branchNum: '', // 节点之间支路数
  }
}
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
  }
  else if (dialogStatus.value === 'detail') {
    areaForm.value = row
    isEditMode.value = false
  }
}
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) {
      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" :class="[dialogStatus === 'detail' ? 'isDetail' : '']" :rules="rules" :model="areaForm" label-position="right" label-width="140px">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="配电网名称:" prop="electricityName">
            <el-input v-model="areaForm.electricityName" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="基准功率:" prop="basePower">
            <el-input v-model="areaForm.basePower" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="系统节点数:" prop="nodeNum">
            <el-input v-model="areaForm.nodeNum" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发电机数:" prop="genNum">
            <el-input v-model="areaForm.genNum" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="系统负荷数:" prop="loadNum">
            <el-input v-model="areaForm.loadNum" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="节点之间支路数:" prop="branchNum">
            <el-input v-model="areaForm.branchNum" :disabled="dialogStatus === 'detail'" />
          </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="electricityArea">
            <el-input v-model="areaForm.electricityArea" :placeholder="dialogStatus === 'create' ? '请输入配电网区域' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="上传人:" prop="uploader">
            <el-select v-model="areaForm.uploader" class="m-2" :placeholder="dialogStatus === 'create' ? '请选择上传人' : ''" style="width: 100%;">
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :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="electricityDetail">
            <show-photo :minio-file-name="areaForm.electricityDetail" width="100%" height="125px" />
            <el-button type="primary" :style="{ 'margin-left': areaForm.electricityDetail === '' ? '0px' : '20px', 'margin-top': areaForm.electricityDetail === '' ? '0px' : '56px' }" @click="upload">
              {{ areaForm.electricityDetail === '' ? '上传' : '更换图片' }}
            </el-button>
            <input v-show="areaForm.electricityDetail === '1.2.3'" ref="fileRef" type="file" accept="image/*" @change="onFileChange">
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <template v-if="dialogStatus !== 'detail'" #footer>
      <div class="dialog-footer">
        <el-button :loading="btnLoading" type="primary" @click="saveData">
          保存
        </el-button>
        <el-button @click="cancel">
          取消
        </el-button>
      </div>
    </template>
    <template v-else #footer>
      <div class="dialog-footer">
        <el-button :loading="btnLoading" type="primary" @click="dialogFormVisible = false">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

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

.el-select {
  width: 100%;
}

.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      display: none;
    }
  }
}
</style>
