<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.addrId ? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <!-- 表单 -->
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="80px"
      @keyup.enter="onSubmit()"
    >
      <!-- 自提点名称 -->
      <el-form-item label="名称" prop="addrName">
        <el-input v-model="dataForm.addrName" placeholder="自提点名称" />
      </el-form-item>

      <!-- 省份、城市、区县选择 -->
      <el-form-item label="省份">
        <el-col :span="8">
          <el-form-item prop="province">
            <el-select
              v-model="dataForm.provinceId"
              placeholder="请选择"
              @change="selectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="city">
            <el-select
              v-model="dataForm.cityId"
              placeholder="请选择"
              @change="selectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="area">
            <el-select v-model="dataForm.areaId" placeholder="请选择">
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>

      <!-- 地址 -->
      <el-form-item label="地址" prop="addr">
        <el-input v-model="dataForm.addr" placeholder="地址" />
      </el-form-item>

      <!-- 手机号 -->
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" maxlength="11" placeholder="手机号" />
      </el-form-item>
    </el-form>

    <!-- 对话框底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { isMobile } from '@/utils/validate'
import { Debounce } from '@/utils/debounce'
import { ref, reactive, nextTick, defineEmits, defineExpose } from 'vue'

// 定义事件发射器，用于向父组件发送事件
const emit = defineEmits(['refreshDataList'])

// 控制对话框显示/隐藏的布尔值
const visible = ref(false)

// 验证手机号格式
const validateMobile = (rule, value, callback) => {
  if (!isMobile(value)) {
    callback(new Error('手机号格式错误'))
  } else {
    callback()
  }
}

// 表单验证规则
const dataRule = {
  addrName: [
    { required: true, message: '自提点名称不能为空', trigger: 'blur' },
    { pattern: /\s\S+|S+\s|\S/, message: '请输入正确的自提点名称', trigger: 'blur' }
  ],
  addr: [
    { required: true, message: '地址不能为空', trigger: 'blur' },
    { pattern: /\s\S+|S+\s|\S/, message: '请输入正确的地址', trigger: 'blur' }
  ],
  city: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
  province: [
    { required: true, message: '省份不能为空', trigger: 'blur' }
  ],
  area: [{ required: true, message: '区/县不能为空', trigger: 'blur' }],
  mobile: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ]
}

// 省列表
const provinceList = ref([])

// 表单引用
const dataFormRef = ref(null)

// 城市列表
const cityList = ref([])

// 区/县列表
const areaList = ref([])

// 表单数据对象，初始化默认值
const dataForm = reactive({
  addrId: 0,
  addr: '',
  addrName: '',
  mobile: '',
  area: '',
  city: '',
  province: '',
  areaId: null,
  cityId: null,
  provinceId: null
})

// 分页信息
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

/**
 * 初始化方法，接受可选的ID作为参数
 * @param id - 自提点地址条目ID，如果存在则为编辑模式
 */
const init = (id) => {
  dataForm.addrId = id || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    cityList.value = []
    areaList.value = []
    dataForm.provinceId = null
    dataForm.cityId = null
    dataForm.areaId = null
  })
  listAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  if (dataForm.addrId) {
    http({
      url: http.adornUrl(`/shop/pickAddr/info/${dataForm.addrId}`),
      method: 'get',
      params: http.adornParams()
    })
      .then(({ data }) => {
        dataForm.addr = data.addr
        dataForm.mobile = data.mobile
        dataForm.addrName = data.addrName
        dataForm.areaId = data.areaId
        dataForm.cityId = data.cityId
        dataForm.provinceId = data.provinceId
        listAreaByParentId(data.provinceId).then(({ data }) => {
          cityList.value = data
        })
        listAreaByParentId(data.cityId).then(({ data }) => {
          areaList.value = data
        })
      })
  }
}
defineExpose({ init })

/**
 * 根据父级ID获取地区列表
 * @param pid - 父级地区ID，默认为0表示获取省级列表
 */
const listAreaByParentId = (pid) => {
  if (!pid) pid = 0
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams({ pid })
  })
}

/**
 * 选择省时触发
 * @param val - 省ID
 */
const selectProvince = (val) => {
  dataForm.cityId = null
  dataForm.city = ''
  dataForm.areaId = null
  dataForm.area = ''
  listAreaByParentId(val).then(({ data }) => {
    cityList.value = data
  })
}

/**
 * 选择市时触发
 * @param val - 市ID
 */
const selectCity = (val) => {
  dataForm.areaId = null
  dataForm.area = ''
  listAreaByParentId(val).then(({ data }) => {
    areaList.value = data
  })
}

/**
 * 表单提交
 */
const onSubmit = Debounce(() => {
  // 设置省市区的名字
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.provinceId) {
      dataForm.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.cityId) {
      dataForm.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.areaId) {
      dataForm.area = areaList.value[i].areaName
    }
  }

  dataFormRef.value?.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/shop/pickAddr'),
        method: dataForm.addrId ? 'put' : 'post',
        data: http.adornData({
          addrId: dataForm.addrId || undefined,
          addr: dataForm.addr,
          addrName: dataForm.addrName,
          mobile: dataForm.mobile,
          area: dataForm.area,
          city: dataForm.city,
          province: dataForm.province,
          areaId: dataForm.areaId,
          cityId: dataForm.cityId,
          provinceId: dataForm.provinceId
        })
      })
        .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false
              emit('refreshDataList', page)
            }
          })
        })
    }
  })
})
</script>
