<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <el-dialog
    v-model="visible"
    :title="dataForm.supplierRefundAddrId? $t('multishop.shopRefundAddr.editRefundAddr'): $t('multishop.shopRefundAddr.addRefundAddr')"
    :modal-append-to-body="blVisible"
    :append-to-body="true"
    class="Mall4j"
    @close="handleClose"
  >
    <el-form
      ref="dataFormRef"
      :inline="true"
      :rules="dataRule"
      :model="dataForm"
      label-width="90px"
      @submit.prevent
    >
      <!-- 收货人 -->
      <el-form-item
        :label="$t('multishop.shopRefundAddr.consignee')"
        prop="consignee"
      >
        <el-input
          v-model.trim="dataForm.consignee"
          style="width: 293px;"
          maxlength="30"
          :placeholder="$t('multishop.shopRefundAddr.consigneeTips')"
        />
      </el-form-item>
      <!-- 手机 -->
      <el-form-item
        :label="$t('multishop.shopRefundAddr.mobile')"
        prop="mobile"
      >
        <el-input
          v-model.trim="dataForm.mobile"
          maxlength="11"
          style="width: 293px;"
          :placeholder="$t('multishop.shopRefundAddr.mobile')"
          @input="dataForm.mobile=dataForm.mobile.replace(/[^\d|*]/g,'')"
        />
      </el-form-item>
      <!-- 邮编 -->
      <el-form-item
        :label="$t('multishop.shopRefundAddr.postCode')"
        prop="postCode"
        class="postCode-label"
      >
        <el-input
          v-model.trim="dataForm.postCode"
          maxlength="6"
          style="width: 293px;"
          :placeholder="$t('multishop.shopRefundAddr.postCode')"
        />
      </el-form-item>
      <div>
        <el-form-item
          :label="$t('multishop.shopRefundAddr.region')"
          prop="province"
        >
          <el-select
            v-model="dataForm.province"
            :placeholder="$t('tip.select')"
            style="width: 150px;"
            @change="selectProvince"
          >
            <el-option
              v-for="(province, index) in provinceList"
              :key="province.areaId"
              :label="province.areaName"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="city"
          label=""
        >
          <el-select
            v-model="dataForm.city"
            :placeholder="$t('tip.select')"
            style="width: 150px;"
            @change="selectCity"
          >
            <el-option
              v-for="(city, index) in cityList"
              :key="city.areaId"
              :label="city.areaName"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="area"
          label=""
        >
          <el-select
            v-model="dataForm.area"
            :placeholder="$t('tip.select')"
            style="width: 150px;"
            @change="selectArea"
          >
            <el-option
              v-for="(area, index) in areaList"
              :key="area.areaId"
              :label="area.areaName"
              :value="index"
            />
          </el-select>
        </el-form-item>
      </div>
      <!-- 地址 -->
      <el-row>
        <el-col :span="24">
          <el-form-item
            :label="$t('multishop.shopRefundAddr.addr')"
            prop="addr"
            class="addr2"
          >
            <el-input
              v-model.trim="dataForm.addr"
              maxlength="80"
              :placeholder="$t('multishop.shopRefundAddr.addr')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 默认地址 -->
      <el-row>
        <el-col :span="24">
          <el-form-item
            :label="$t('multishop.shopRefundAddr.isDefaultAddr')"
            class="addr2"
          >
            <el-checkbox
              v-model="isDefault"
              :disabled="isDisabled"
            >
              {{ $t('multishop.shopRefundAddr.isDefault') }}
            </el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          plain
          @click="visible = false"
        >
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="onSubmit()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import * as api from '@/api/multishop/shop-refund-addr'
import * as addrApi from '@/api/system/addr-manage'
import { Debounce } from '@/utils/debounce'
import { validNoEmptySpace } from '@/utils/validate'
import { ElMessage } from 'element-plus'

const emit = defineEmits('refreshDataList')
const visible = ref(false)
const blVisible = ref(false)
const isSubmit = ref(false)
const isDefault = ref(false)
const provinceList = ref([])
const cityList = ref([])
const areaList = ref([])
const dataForm = reactive({
  supplierRefundAddrId: 0,
  supplierId: null,
  mobile: null,
  isDefault: 0,
  consignee: null,
  provinceId: null,
  province: null,
  cityId: null,
  city: null,
  areaId: null,
  area: null,
  addr: null,
  postCode: null,
  lng: null,
  lat: null
})
const initDataForm = reactive({
  province: null,
  city: null,
  area: null,
  addr: null
})
const isDisabled = ref(false)
// eslint-disable-next-line no-unused-vars
const validatePostCode = reactive((rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('multishop.shopRefundAddr.errEmpty')))
    return
  }
  if (!/^[0-9]{6}$/.test(value) && value !== '' && value !== null) {
    callback(new Error($t('multishop.shopRefundAddr.errPostalCode')))
    return
  }
  callback()
})

// eslint-disable-next-line no-unused-vars
const validateMobile = (rule, value, callback) => {
  if (isMobile(value) || (dataForm.supplierRefundAddrId && isStarMobile(value))) {
    callback()
  } else {
    callback(new Error($t('multishop.shopRefundAddr.mobileFormattingError')))
  }
}

const dataRule = reactive({
  postCode: [{
    validator: validatePostCode, trigger: 'blur'
  }],
  mobile: [
    { required: true, message: $t('multishop.shopRefundAddr.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ],
  consignee: [
    { required: true, message: $t('multishop.shopRefundAddr.consigneeNotEmpty'), pattern: '[^ \x22]+', trigger: 'blur' }
  ],
  province: [
    { required: true, message: $t('multishop.shopRefundAddr.provinceCannotBeEmpty'), pattern: '[^ \x22]+', trigger: 'change' }
  ],
  city: [
    { required: true, message: $t('multishop.shopRefundAddr.cityCannotBeEmpty'), pattern: '[^ \x22]+', trigger: 'change' }
  ],
  area: [
    { required: true, message: $t('multishop.shopRefundAddr.districtCounEmpty'), pattern: '[^ \x22]+', trigger: 'change' }
  ],
  addr: [
    { required: true, message: $t('multishop.shopRefundAddr.addressCannotBeEmpty'), pattern: '[^ \x22]+', trigger: 'blur' }
  ]
})

const dataFormRef = ref('')
const init = (supplierRefundAddrId) => {
  dataForm.supplierRefundAddrId = supplierRefundAddrId || 0
  visible.value = true
  blVisible.value = false
  isSubmit.value = false
  isDefault.value = false
  dataForm.provinceId = null
  dataForm.province = null
  provinceList.value = []
  cityList.value = []
  areaList.value = []
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (!dataForm.supplierRefundAddrId) {
      return
    }
    api.get(supplierRefundAddrId).then(data => {
      Object.assign(dataForm, data)
      Object.assign(initDataForm, dataForm)
      isDefault.value = data.isDefault === 1
    })
  })
  listArea()
}

defineExpose({ init })
const listArea = () => {
  addrApi.getAreaListInfo().then(data => {
    provinceList.value = data
    if (dataForm.supplierRefundAddrId) {
      provinceList.value.forEach(provincel => {
        if (provincel.areaId === dataForm.provinceId) {
          cityList.value = provincel.areas
          cityList.value.forEach(city => {
            if (city.areaId === dataForm.cityId) {
              areaList.value = city.areas
            }
          })
        }
      })
    }
  })
}
const handleClose = () => {
  blVisible.value = true
}
// 选择省
const selectProvince = (index) => {
  dataForm.cityId = null
  dataForm.city = ''
  dataForm.areaId = null
  dataForm.area = ''
  const province = provinceList.value[index]
  dataForm.provinceId = province.areaId
  dataForm.province = province.areaName
  // 获取城市的select
  cityList.value = province.areas
  areaList.value = []
}
// 选择市
const selectCity = (index) => {
  dataForm.areaId = null
  dataForm.area = ''
  const city = cityList.value[index]
  dataForm.cityId = city.areaId
  dataForm.city = city.areaName
  // 获取区的select
  areaList.value = city.areas
}
// 选择区
const selectArea = (index) => {
  dataForm.areaId = null
  dataForm.area = ''
  const area = areaList.value[index]
  dataForm.areaId = area.areaId
  dataForm.area = area.areaName
}

// 表单提交
const onSubmit = Debounce(() => {
  dataForm.isDefault = isDefault.value ? 1 : 0
  dataFormRef.value?.validate(valid => {
    if (!valid || isSubmit.value) {
      return
    }
    isSubmit.value = true
    const request = dataForm.supplierRefundAddrId ? api.update(dataForm) : api.save(dataForm)
    request.then(() => {
      visible.value = false
      ElMessage({
        message: $t('table.actionSuccess'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          blVisible.value = true
          emit('refreshDataList')
          dataFormRef.value?.resetFields()
        }
      })
      isSubmit.value = false
    }).catch(() => {
      isSubmit.value = false
    })
  })
}, 1000)
</script>
<style lang="scss" scoped>
.addr2 {
  width: 100%;
  display: flex;
  :deep(.el-form-item__content) {
    width: calc(100% - 90px);
    max-width: 685px;
  }
}

</style>
