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

 https://www.mall4j.com/

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

 版权所有，侵权必究！
-->
<template>
  <el-dialog
    v-model="visible"
    :title="$t('order.order.modifyUseAddress')"
    :modal="false"
    top="200px"
    :close-on-click-modal="false"
    class="components-order-addr-update"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="80px"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-alert
        :title="$t('order.order.consultWithUsers')"
        type="warning"
        show-icon
      />
      <br>
      <el-form-item
        :label="$t('constant.consignee')"
        prop="consignee"
      >
        <el-input
          v-model="dataForm.consignee"
          :placeholder="$t('shop.consigneeName')"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        :label="$t('constant.mobilePhone')"
        prop="mobile"
      >
        <el-input
          v-model="dataForm.mobile"
          :placeholder="$t('constant.mobilePhone')"
          maxlength="11"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('multishop.shopRefundAddr.province')"
        prop="province"
      >
        <el-col :span="7">
          <el-form-item prop="province">
            <el-select
              v-model="dataForm.province"
              :placeholder="$t('tip.select')"
              @change="onSelectProvince"
            >
              <el-option
                v-for="(province, index) in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="index"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="city">
            <el-select
              v-model="dataForm.city"
              :placeholder="$t('tip.select')"
              @change="onSelectCity"
            >
              <el-option
                v-for="(city, index) in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="index"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="area">
            <el-select
              v-model="dataForm.area"
              :placeholder="$t('tip.select')"
              @change="onSelectArea"
            >
              <el-option
                v-for="(area, index) in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="index"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <!-- 地址 -->
      <el-form-item
        :label="$t('address.detailed')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          :placeholder="$t('address.detailed')"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button
          plain
          @click="visible = false"
        >{{ $t("table.cancel") }}</el-button>
        <el-button
          type="primary"
          @click="onGetChangeAmount()"
        >{{ $t("table.confirm") }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import * as addrApi from '@/api/system/addr-manage'
import * as api from '@/api/order/order'
import Big from 'big.js'
import { ElMessage, ElMessageBox } from 'element-plus'

const emit = defineEmits([
  'refreshUserAddrOrder'
])

const provinceList = reactive([])
const cityList = reactive([])
const areaList = reactive([])
const dataForm = reactive({
  addr: '',
  addrId: 0,
  area: '',
  areaId: null,
  city: '',
  cityId: null,
  consignee: '',
  mobile: '',
  orderAddrId: 0,
  orderId: 0,
  province: '',
  provinceId: null
})
// eslint-disable-next-line no-unused-vars
const validateMobile = reactive((rule, value, callback) => {
  if (!isStarMobile(value)) {
    callback(new Error($t('order.order.mobilePhoneError')))
  } else {
    callback()
  }
})
// eslint-disable-next-line no-unused-vars
const validateConsignee = reactive((rule, value, callback) => {
  if (value.match(/^\s+$/) || !value) {
    callback(new Error($t('shop.coneeNameCanEmpty')))
  } else {
    callback()
  }
})
// eslint-disable-next-line no-unused-vars
const validateArea = reactive((rule, value, callback) => {
  if (value.match(/^\s+$/) || !value) {
    callback(new Error($t('shop.addressCannotBeEmpty')))
  } else {
    callback()
  }
})

const dataRule = computed(() => {
  return {
    consignee: [
      { required: true, validator: validateConsignee, trigger: 'blur' }
    ],
    addr: [{ required: true, validator: validateArea, trigger: 'blur' }],
    city: [{ required: true, message: $t('shop.cityCannotBeEmpty'), trigger: 'blur' }],
    province: [
      { required: true, message: $t('shop.provinceCannotBeEmpty'), trigger: 'blur' }
    ],
    area: [{ required: true, message: $t('shop.districtCounEmpty'), trigger: 'blur' }],
    mobile: [
      { required: true, message: $t('order.order.mobilePhoneNoNull'), trigger: 'blur' },
      { validator: validateMobile, trigger: 'blur' }
    ]
  }
})

// 初始化
const dataListLoading = ref(false)
const freightAmount = ref(0)
const oldOrder = ref('')
const order = ref()
const orderStatus = ref(0)
const visible = ref(false)
const init = (orderParam) => {
  const orderInfo = Object.assign({}, orderParam)
  order.value = orderInfo
  dataForm.orderAddrId = orderInfo.orderAddrId || 0
  visible.value = true
  dataListLoading.value = true
  freightAmount.value = orderInfo.freightAmount
  orderStatus.value = orderInfo.status
  oldOrder.value = JSON.parse(JSON.stringify(orderInfo))
  nextTick(() => {
    getOrderAddrById(orderInfo.orderAddrId)
  })
  onListArea()
  dataListLoading.value = false
}

const getOrderAddrById = (orderAddrId) => {
  api.getOrderAddr(orderAddrId).then((data) => {
    onHandleDataForm(data)
  })
}

const onHandleDataForm = (data) => {
  dataForm.orderAddrId = data.orderAddrId
  dataForm.addr = data.addr
  dataForm.consignee = data.consignee
  dataForm.mobile = data.mobile
  dataForm.area = data.area
  dataForm.city = data.city
  dataForm.province = data.province
  dataForm.areaId = data.areaId
  dataForm.cityId = data.cityId
  dataForm.provinceId = data.provinceId
}

const onListArea = () => {
  addrApi.getAreaListInfo().then(data => {
    onHandleArr(provinceList, data)
    if (dataForm.orderAddrId) {
      provinceList.forEach(provincel => {
        if (provincel.areaId === dataForm.provinceId) {
          onHandleArr(cityList, provincel.areas)
          cityList.forEach(city => {
            if (city.areaId === dataForm.cityId) {
              onHandleArr(areaList, city.areas)
            }
          })
        }
      })
    }
  })
}

const onHandleArr = (arr, data) => {
  arr.length = 0
  arr.push(...data)
}

// 选择省
const onSelectProvince = (index) => {
  dataForm.cityId = null
  dataForm.city = ''
  dataForm.areaId = null
  dataForm.area = ''
  const province = provinceList[index]
  dataForm.provinceId = province.areaId
  dataForm.province = province.areaName
  // 获取城市的select
  onHandleArr(cityList, province.areas)
  areaList.length = 0
}

// 选择市
const onSelectCity = (index) => {
  dataForm.areaId = null
  dataForm.area = ''
  const city = cityList[index]
  dataForm.cityId = city.areaId
  dataForm.city = city.areaName
  // 获取区的select
  onHandleArr(areaList, city.areas)
}

// 选择区
const onSelectArea = (index) => {
  dataForm.areaId = null
  dataForm.area = ''
  const area = areaList[index]
  dataForm.areaId = area.areaId
  dataForm.area = area.areaName
}

const dataFormRef = ref()
const onGetChangeAmount = () => {
  oldOrder.orderId = order.value.orderId
  oldOrder.orderNumber = order.value.orderNumber
  dataFormRef.value?.validate(valid => {
    if (valid) {
      const params = {
        orderId: oldOrder.orderId,
        areaId: dataForm.areaId
      }
      api.getChangeAmount(params).then((data) => {
        const amount = new Big(data).div(100).toFixed(2)
        const msg = `由于地址变更，运费应${amount > 0 ? '多' : '少'}收${amount < 0 ? amount * -1 : amount}元，此操作不会变更订单金额，是否确认直接修改订单地址？`
        ElMessageBox.confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          onSubmit()
        })
      })
    }
  })
}

// 确定事件
const onSubmit = () => {
  dataFormRef.value?.validate(valid => {
    if (valid) {
      dataForm.orderId = order.value.orderId
      api.updateOrderAddr(dataForm).then(() => {
        ElMessage({
          message: $t('table.actionSuccess'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshUserAddrOrder')
          }
        })
      })
    }
  })
}

defineExpose({
  init
})
</script>

<style scoped>
</style>
