<script lang="ts" setup name="EditArea">
import type { Ref } from 'vue'
import { defineExpose, nextTick, reactive, ref } from 'vue'
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import AreaSelectTree from './areaSelectTree.vue'
import type { IareaForm } from './area-interface'
import { addArea, getAreaType, updateArea } from '@/api/system/area'
const emits = defineEmits(['watchChild'])
const dataFormRef = ref()
const areaSelect = ref()
const dialogFormVisible = ref(false) // 对话框是否显示
const dialogStatus = ref('') // 对话框类型：create,update
const isEditMode = ref(true)
const areaForm: Ref<IareaForm> = ref({
  pid: '', // 父级编号
  pName: '', // 父级名称
  areaName: '', // 区域名
  simpleName: '', // 别名，
  level: '',
  num: 99, // 排序
}) // 表单
const areaSelectShow = ref(false)
const areaLevelList = ref([]) as any // 区域树列表数据
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  id: [{ required: true, message: '区域编号不能为空', trigger: ['blur', 'change'] }],
  areaName: [{ required: true, message: '区域名称不能为空', trigger: ['blur', 'change'] }],
  simpleName: [{ required: true, message: '区域简称不能为空', trigger: ['blur', 'change'] }],
  pName: [{ required: true, message: '上级区域必选', trigger: ['blur', 'change'] }],
  level: [{ required: true, message: '区域等级必选', trigger: ['blur', 'change'] }],
  num: [{ required: true, message: '排序必填' }, { type: 'number', message: '必须为数字值' }],
} // 前端校验规则

// const areaTree = computed(() => {
//   const tree = toTreeList(areaTreeList)
//   return tree
// })
// 重置表单
const resetForm = () => {
  areaForm.value = {
    id: '', // 编号
    pid: '', // 父级编号
    pName: '', // 父级名称
    areaName: '', // 区域名
    simpleName: '', // 别名，
    level: '',
    num: 99, // 排序
  }
}
// 获取区域类型
const fetchAreaType = () => {
  getAreaType().then((response) => {
    areaLevelList.value = response.data
  })
}

fetchAreaType()
// 初始化对话框

const initDialog = (dialogStatusValue: string, row: IareaForm) => {
  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 = {
      id: row.id, // 编号
      pid: row.pid, // 父级编号
      pName: row.pName, // 父级编号
      areaName: row.areaName, // 区域名
      simpleName: row.simpleName, // 别名，
      level: `${row.level}`,
      num: row.num, // 排序
    }
    isEditMode.value = true
  }
}
defineExpose({
  initDialog,
})
// 打开区域选择弹窗
const openAreaSelect = () => {
  areaSelectShow.value = true
  setTimeout(areaSelect.value.initDialog(), 200)
}

// 修改pid
const changeParent = (node: any) => {
  areaForm.value.pid = node.id
  areaForm.value.pName = node.name
}

// 新增数据
const createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      addArea(areaForm.value).then((response) => {
        if (response.code === 200) {
          ElMessageBox.confirm('新增成功，是否继续新增?', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'info',
          }).then(() => { // 选是
            resetForm()
            btnLoading.value = false
            nextTick(() => {
              dataFormRef.value.clearValidate()
            })
          }).catch(() => { // 选否,关闭窗口，并刷新页面
            emits('watchChild')
            dialogFormVisible.value = false
          })
        }
      }).catch((_) => { // 异常情况，loading置为false
        btnLoading.value = false
      })
    }
  })
}

// 修改数据
const updateData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      updateArea(areaForm.value).then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          dataFormRef.value.clearValidate()
          emits('watchChild')
          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
  // this.$emit('watchChild')
}
</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="80px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="区域名称" prop="areaName">
            <el-input v-model.trim="areaForm.areaName" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="区域简称" prop="simpleName">
            <el-input v-model.trim="areaForm.simpleName" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="区域编码" prop="id">
            <el-input v-model.trim="areaForm.id" :disabled="isEditMode" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上级区域" prop="pName">
            <el-input :value="areaForm.pName" type="text" placeholder="必选" @focus="openAreaSelect" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="区域等级" prop="level">
            <el-select v-model="areaForm.level" placeholder="必选">
              <el-option
                v-for="item in areaLevelList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="num">
            <el-input-number v-model.number="areaForm.num" style="width: 100%;" placeholder="必填" />
          </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>

    <area-select-tree ref="areaSelect" @selectDone="changeParent" />
  </el-dialog>
</template>

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

.el-select {
  width: 100%;
}
</style>
