<!-- 添加 / 编辑 -->
<script name="AddLocateDialog" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IDictType } from '../common-interface'
import { phoneValidator } from '../common-interface'
import type { ILocateInfo } from './locate-info'
import { addLocate, updateLocate } from '@/api/basic/locate'
import { validatePhone } from '@/utils/validate'

const emit = defineEmits(['recordSaved'])

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

const title = ref('')

const infoFormRef = ref()

const locateInfo = ref<ILocateInfo>({
  id: '',
  wellCode: '',
  wellName: '',
  wellType: '',
  deptid: '',
  responsibleDept: '',
  position: '',
  staff: '',
  tel: '',
})

const locateInfoRules = ref({
  wellCode: [{ required: true, message: '点位编号不能为空', trigger: 'blur' }],
  wellName: [{ required: true, message: '点位名称不能为空', trigger: 'blur' }],
  wellType: [{ required: true, message: '点位类型不能为空，请选择', trigger: ['blur', 'change'] }],
  deptid: [{ required: true, message: '权属部门不能为空，请选择', trigger: ['blur', 'change'] }],
  responsibleDept: [{ required: true, message: '责任部门不能为空，请选择', trigger: ['blur', 'change'] }],
  tel: [{ validator: phoneValidator, trigger: 'blur' }],
}) // 表单验证规则

const locateTypeDict = ref<Array<IDictType>>([])

const showDialog = ref<boolean>(false)

// 逻辑
const resetForm = () => {
  sessionStorage.removeItem('locateInfo') // 返回列表时 将缓存中的数据删除

  locateInfo.value = {
    id: '',
    wellCode: '',
    wellName: '',
    wellType: '',
    deptid: '',
    responsibleDept: '',
    position: '',
    staff: '',
    tel: '',
  }

  infoFormRef.value.clearValidate()
  showDialog.value = false
}

// 添加
const saveInfo = () => {
  // 将创建时间改为提交的时间
  addLocate(locateInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')

      emit('recordSaved')
      resetForm()
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}
// 编辑
const updateInfoById = () => {
  updateLocate(locateInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')

      emit('recordSaved')
      resetForm()
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 保存
const saveForm = async () => {
  if (!infoFormRef) { return }

  await infoFormRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (type.value === 'create') {
          saveInfo()
        }
        else if (type.value === 'update') {
          updateInfoById()
        }
      })
    }
  })
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  if (sessionStorage.getItem('locateType') !== undefined) {
    locateTypeDict.value = JSON.parse(sessionStorage.getItem('locateType')!)
  }

  switch (params.type) {
    case 'create' :
      title.value = '新增点位'

      break
    case 'update':
      title.value = '编辑点位'

      locateInfo.value = JSON.parse(sessionStorage.getItem('locateInfo')!)
      locateInfo.value.wellType = locateInfo.value.wellType.toString()

      break
    default:
      title.value = ''
      break
  }

  nextTick(() => {
    infoFormRef.value.clearValidate()
  })

  showDialog.value = true
}

defineExpose({
  initDialog,
})
</script>

<template>
  <el-dialog v-model="showDialog" :title="title" :append-to-body="true" :close-on-click-modal="false" @closed="resetForm">
    <detail-block title="">
      <el-form ref="infoFormRef" :model="locateInfo" :rules="locateInfoRules" label-position="right" label-width="110px" stripe>
        <el-row :gutter="24">
          <el-col :span="9" :offset="3">
            <el-form-item label="点位编号" prop="wellCode">
              <el-input v-model="locateInfo.wellCode" placeholder="请输入点位编号" :disabled="type === 'update'" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="9">
            <el-form-item label="点位名称" prop="wellName">
              <el-input v-model="locateInfo.wellName" placeholder="请输入点位名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="9" :offset="3">
            <el-form-item label="点位类型" prop="wellType">
              <el-select v-model="locateInfo.wellType" placeholder="请选择点位类型" clearable>
                <el-option v-for="dict in locateTypeDict" :key="dict.id" :value="dict.value" :label="dict.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="9" :offset="3">
            <el-form-item label="所属单位" prop="deptid">
              <dept-select v-model="locateInfo.deptid" placeholder="请选择所属单位" clearable filterable />
            </el-form-item>
          </el-col>

          <el-col :span="9">
            <el-form-item label="责任单位" prop="responsibleDept">
              <dept-select v-model="locateInfo.responsibleDept" placeholder="请选择责任单位" clearable filterable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="9" :offset="3">
            <el-form-item label="联系人">
              <el-input v-model="locateInfo.staff" placeholder="请输入联系人" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="9">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="locateInfo.tel" placeholder="请输入联系人电话" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="18" :offset="3">
            <el-form-item label="详细地址">
              <el-input v-model="locateInfo.position" placeholder="请在地图上选点" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="saveForm">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
