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

  https://www.mall4j.com/

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

  版权所有，侵权必究！
-->

<template>
  <view
    v-show="visible"
    class="component-picker-address"
  >
    <view
      class="picker-mask"
      @tap.stop="cancel"
    />
    <view class="content">
      <view
        class="header"
        @tap.stop="submitAddr"
      >
        {{ $t('queDing') }}
      </view>
      <picker-view
        v-if="visible"
        :value="addrValue"
        :indicator-style="indicatorStyle"
        class="picker-view"
        @change="bindChange"
      >
        <!--省-->
        <picker-view-column>
          <view
            v-for="item in provArray"
            :key="item.areaId"
            class="item"
          >
            {{ item.areaName }}
          </view>
        </picker-view-column>
        <!--地级市-->
        <picker-view-column>
          <view
            v-for="item in cityArray"
            :key="item.areaId"
            class="item"
          >
            {{ item.areaName }}
          </view>
        </picker-view-column>
        <!--区县-->
        <picker-view-column>
          <view
            v-for="item in areaArray"
            :key="item.areaId"
            class="item"
          >
            {{ item.areaName }}
          </view>
        </picker-view-column>
      </picker-view>
    </view>
  </view>
</template>

<script setup>
import { reactive } from 'vue'

const emit = defineEmits(['getAddrData', 'cancel'])

const Data = reactive({
  visible: false,
  indicatorStyle: 'height: 50rpx;',
  provinceId: 0,
  provArray: [],
  cityId: 0,
  cityArray: [],
  areaId: 0,
  areaArray: [],
  addrValue: [0, 0, 0],
  addrIds: [],
  isFirst: true
})

const { visible, indicatorStyle, provArray, cityArray, areaArray, addrValue } = toRefs(Data)

/**
 *
 * @param {Array} addrIds 这是回显的地址id数组[省, 市, 区]
 */
const init = async (addrIds) => {
  // 获取地址列表信息
  Data.addrIds = addrIds
  if (Data.addrIds[0] && Data.addrIds[1] && Data.addrIds[2]) {
    Data.provinceId = Data.addrIds[0]
    Data.cityId = Data.addrIds[1]
    Data.areaId = Data.addrIds[2]
    getProvinceArray(1)
  } else {
    getProvinceArray()
  }
}

// 获取当前id下的地址信息
const listAreaByParentId = (pid) => {
  let paramData = {}
  if (!pid) {
    paramData = { level: 1 }
  } else {
    paramData = { pid }
  }
  return new Promise((resolve) => {
    http.request({
      url: '/admin/area/listByPid',
      method: 'GET',
      data: paramData
    }).then(({ data }) => {
      resolve(data)
    })
  })
}

/**
 * 获取全部省份
 */
const getProvinceArray = async (isTrue) => {
  if (!Data.provArray.length) {
    // eslint-disable-next-line require-atomic-updates
    Data.provArray = await listAreaByParentId()
  }
  for (let i = 0; i < Data.provArray.length; i++) {
    if (Data.provinceId === Data.provArray[i].areaId) {
      Data.addrValue.splice(0, 1, i)
      break
    }
  }
  if (!isTrue) {
    Data.provinceId = Data.provArray[0].areaId
  }
  getCityArray(isTrue)
}

// 获取当前节点下的地址
const getCurrentAreas = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}

/**
 * 根据省份ID获取 城市数据
 */
const getCityArray = async (isTrue) => {
  const { curNode, areas } = getCurrentAreas(Data.provArray, Data.provinceId)
  if (areas) {
    Data.cityArray = areas
  } else {
    // eslint-disable-next-line require-atomic-updates
    Data.cityArray = await listAreaByParentId(Data.provinceId)
    curNode.areas = Data.cityArray
  }
  for (let i = 0; i < Data.cityArray.length; i++) {
    if (Data.cityId === Data.cityArray[i].areaId) {
      Data.addrValue.splice(1, 1, i)
      break
    }
  }
  if (!isTrue) {
    Data.cityId = Data.cityArray[0].areaId
  }
  getAreaArray(isTrue)
}

// 根据市id，获取区
const getAreaArray = async (isTrue) => {
  const { curNode, areas } = getCurrentAreas(Data.cityArray, Data.cityId)
  if (areas) {
    Data.areaArray = areas
  } else {
    // eslint-disable-next-line require-atomic-updates
    Data.areaArray = await listAreaByParentId(Data.cityId)
    curNode.areas = Data.areaArray
  }
  for (let i = 0; i < Data.areaArray.length; i++) {
    if (Data.areaId === Data.areaArray[i].areaId) {
      Data.addrValue.splice(2, 1, i)
      break
    }
  }
  if (!isTrue) {
    Data.areaId = Data.areaArray[0].areaId
    Data.addrValue.splice(2, 1, 0)
  }
  Data.visible = true
}

const bindChange = (e) => {
  const value = e.detail.value
  Data.addrValue = [value[0] || 0, value[1] || 0, value[2] || 0]
  const index1 = e.detail.value[0]
  const provId = Data.provArray[index1] && Data.provArray[index1].areaId

  // 切换省份
  if (Data.provinceId !== provId && provId) {
    Data.provinceId = provId
    Data.addrValue[1] = 0
    getCityArray()
  }

  const index2 = e.detail.value[1] || 0
  const cityId = Data.cityArray[index2] && Data.cityArray[index2].areaId
  if (Data.cityId !== cityId && cityId) {
    Data.addrValue[2] = 0
    Data.cityId = cityId
    getAreaArray()
  }
}

const submitAddr = () => {
  const data = {
    province: Data.provArray[Data.addrValue[0]].areaName, // 省
    provinceId: Data.provArray[Data.addrValue[0]].areaId, // 省id
    city: Data.cityArray[Data.addrValue[1]].areaName, // 市
    cityId: Data.cityArray[Data.addrValue[1]].areaId, // 市id
    area: Data.areaArray[Data.addrValue[2]].areaName, // 区
    areaId: Data.areaArray[Data.addrValue[2]].areaId // 区id
  }
  emit('getAddrData', data)
}

const cancel = () => {
  emit('cancel')
}

defineExpose({
  init
})
</script>

<style scoped lang="scss">
.component-picker-address {
  @keyframes window-open {
    0% {
      bottom: -530rpx;
    }

    100% {
      bottom: 0;
    }
  }

  .picker-view {
    width: 100%;
    height: 310rpx;
    margin-top: 50rpx;
    font-size: 28rpx;
  }

  .item {
    height: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
  }

  .picker-mask {
    z-index: 1999;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #000000;
    opacity: 0.4;
  }

  .content {
    z-index: 2109;
    height: 530rpx;
    background: #FFFFFF;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    animation: window-open 0.4s 1;
  }

  .header {
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20rpx;
    font-size: 28rpx;
    border-bottom: #F2F2F2 solid 2rpx;
  }
}
</style>
