<template>
  <view>
    <uv-form-item
      :labelWidth="100"
      :label="item?.taskFiledValue"
      :borderBottom="false"
      labelPosition="left"
      :required="item?.isMustfill == '1'"
      @click="showAreaPicker"
    >
      <uv-input
        input-align="right"
        v-model="propsMessage"
        disabled
        disabledColor="#ffffff"
        :placeholder="`请选择${item?.taskFiledValue}`"
        border="none"
      />
      <template v-slot:right>
        <uv-icon name="arrow-right"></uv-icon>
      </template>
    </uv-form-item>
    <uv-picker
      ref="areaPickerRef"
      keyName="name"
      @change="change"
      :columns="addressList"
      @confirm="confirm"
    />
  </view>
</template>

<script setup lang="ts">
import { computed, ref, reactive } from 'vue'
import regions from '@/regions/regions.json'

const area = reactive({
  provinces: [] as any[],
  citys: [] as any[],
  areas: [] as any[]
})

function getData() {
  area.provinces = regions.sort((left, right): any => {
    return Number(left.code) - Number(right.code)
  })
  handlePickValueDefault()
}
const pickerValue = ref([0, 0, 0])
const defaultValue = ref([3442, 1, 2])
const areaPickerRef = ref()

function handlePickValueDefault() {
  // 设置省
  pickerValue.value[0] = area.provinces.findIndex(
    (item) => Number(item.id) === defaultValue.value[0]
  )
  // 设置市
  area.citys = area.provinces[pickerValue.value[0]]?.children || []
  pickerValue.value[1] = area.citys.findIndex((item) => Number(item.id) === defaultValue.value[1])
  // 设置区
  area.areas = area.citys[pickerValue.value[1]]?.children || []
  pickerValue.value[2] = area.areas.findIndex((item) => Number(item.id) === defaultValue.value[2])
}

const emmits = defineEmits(['update:areaValue'])

let props = defineProps({
  item: Object,
  index: Number,
  areaValue: String
})

const showAreaPicker = () => {
  areaPickerRef.value.open()
}
const change = (e: any) => {
  const { columnIndex, index, indexs } = e
  // 改变了省
  if (columnIndex === 0) {
    area.citys = area.provinces[index]?.children || []
    area.areas = area.citys[0]?.children || []
    areaPickerRef.value.setIndexs([index, 0, 0], true)
  } else if (columnIndex === 1) {
    area.areas = area.citys[index]?.children || []
    areaPickerRef.value.setIndexs(indexs, true)
  }
}

const confirm = (e: any) => {
  const areaLabel = e.value[0].name + '-' + e.value[1].name + '-' + e.value[2].name
  emmits('update:areaValue', areaLabel)
}

const propsMessage = computed({
  get: () => {
    return props.areaValue
  },
  set: (val) => {
    emmits('update:areaValue', val)
  }
})

const addressList = computed(() => {
  return [area.provinces, area.citys, area.areas]
})

getData()
</script>

<style lang="scss" scoped></style>
