<script lang="ts" setup name="EditTransformer">
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addTransformerList, updateTransformerList } from '@/api/api/electricity'
const emits = defineEmits(['refresh'])
const dataFormRef = ref()
const dialogFormVisible = ref(false) // 对话框是否显示
const dialogStatus = ref('') // 对话框类型：create,update
const isEditMode = ref(true)
const areaForm = ref({
  name: '', // 变压器名称
  model: '', // 型号
  installPosition: '', // 安装位置
  lat: '', // 纬度
  lng: '', // 经度
  mvaRate: '', // 额定容量
  volRegulatingMode: '', // 调压方式
  voltageType: '', // 最高电压等级
  runningState: '', // 运行状态
  operateDate: '', // 投运日期
  expiryDate: '', // 停运日期
}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  name: [{ required: true, message: '请输入变压器名称', trigger: ['blur', 'change'] }],
  model: [{ required: true, message: '请输入变压器型号', trigger: ['blur', 'change'] }],
  installPosition: [{ required: true, message: '请输入安装位置', trigger: ['blur', 'change'] }],
  lat: [{ required: true, message: '请选择经纬度坐标', trigger: ['blur', 'change'] }],
  mvaRate: [{ required: true, message: '请输入额定容量', trigger: ['blur', 'change'] }],
  volRegulatingMode: [{ required: true, message: '请选择调压方式', trigger: ['blur', 'change'] }],
  voltageType: [{ required: true, message: '请输入最高电压等级', trigger: ['blur', 'change'] }],
  runningState: [{ required: true, message: '请选择运行状态', trigger: ['blur', 'change'] }],
  operateDate: [{ required: true, message: '请选择投运日期', trigger: ['blur', 'change'] }],
  expiryDate: [{ required: true, message: '请选择停运日期', trigger: ['blur', 'change'] }],
} // 前端校验规则
// 重置表单
const resetForm = () => {
  areaForm.value = {
    name: '', // 变压器名称
    model: '', // 型号
    installPosition: '', // 安装位置
    lat: '', // 纬度
    lng: '', // 经度
    mvaRate: '', // 额定容量
    volRegulatingMode: '', // 调压方式
    voltageType: '', // 最高电压等级
    runningState: '', // 运行状态
    operateDate: '', // 投运日期
    expiryDate: '', // 停运日期
  }
}
const locationData = ref<number[]>([]) // 经纬度 - 展示用
const locationDataStr = computed(() => locationData.value.join())
watch(() => locationData.value, (newVal: number[]) => {
  if (newVal.length) {
    areaForm.value.lng = newVal[0].toString()
    areaForm.value.lat = newVal[1].toString()
  }
}, { deep: true })
const selectRef = ref()
// 选择经纬度
const selectLocation = () => {
  selectRef.value.initDialog(locationData.value)
}
// 确定经纬度
const confirm = (data: number[]) => {
  locationData.value = data
}
// 初始化对话框
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
      addTransformerList(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
      updateTransformerList(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>
    <select-location-map ref="selectRef" @confirm="confirm" />
    <el-form ref="dataFormRef" :rules="rules" :model="areaForm" label-position="right" label-width="140px">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="名称:" prop="name">
            <el-input v-model="areaForm.name" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号:" prop="model">
            <el-input v-model="areaForm.model" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="安装位置:" prop="installPosition">
            <el-input v-model="areaForm.installPosition" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经纬度坐标:" prop="lat">
            <el-input v-model="locationDataStr" :disabled="dialogStatus === 'detail'" @focus="selectLocation" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="额定容量(MVA):" prop="mvaRate">
            <el-input v-model="areaForm.mvaRate" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="调压方式:" prop="volRegulatingMode">
            <el-input v-model="areaForm.volRegulatingMode" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="最高电压等级:" prop="voltageType">
            <el-input v-model="areaForm.voltageType" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="运行状态:" prop="runningState">
            <el-input v-model="areaForm.runningState" :disabled="dialogStatus === 'detail'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="投运日期:" prop="operateDate">
            <el-date-picker v-model="areaForm.operateDate" type="datetime" :disabled="dialogStatus === 'detail'" placeholder="投运日期" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="停运日期:" prop="expiryDate">
            <el-date-picker v-model="areaForm.expiryDate" type="datetime" :disabled="dialogStatus === 'detail'" placeholder="停运日期" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" />
          </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%;
}
</style>
