<template>
  <view>
    <view class="flex-center h-44px text-white" :style="{ color: color }">
      <view class="flex-center flex-1" @click="openRegions">
        <view class="line-clamp-1">{{ regionseText }}</view>
        <uv-icon
          :color="color"
          class="ml-10rpx"
          size="20rpx"
          name="arrow-down-fill"
        ></uv-icon>
      </view>
      <view class="flex-center flex-1" @click="openStore">
        <view class="line-clamp-1">{{ storeText }}</view>
        <uv-icon
          :color="color"
          class="ml-10rpx"
          size="20rpx"
          name="arrow-down-fill"
        ></uv-icon>
      </view>
    </view>
    <uv-picker
      ref="regionsRef"
      :columns="addressList"
      @change="regionsChange"
      keyName="name"
      @confirm="regionsConfirm"
    >
    </uv-picker>

    <uv-picker
      ref="storeRef"
      :columns="storeList"
      keyName="title"
      @confirm="storeConfirm"
    >
    </uv-picker>
  </view>
</template>
<script setup>
import { http } from '@/utils/request'
import { onMounted, ref, reactive, computed, toRaw } from 'vue'
import debounce from '@climblee/uv-ui/libs/function/debounce'
const props = defineProps({
  color: {
    type: String,
    default: '#fff',
  },
})
onMounted(() => {
  getData()
  getStoreData()
})

const regionsRef = ref(null)
const storeRef = ref(null)
// 筛选结果
const result = ref([])
// 地区数据
const regions = ref([])
const provinces = ref([])
const citys = ref([])
const areas = ref([])
const store = ref([])
const addressList = computed(() => {
  return [provinces.value, citys.value]
})
const storeList = computed(() => {
  return [store.value]
})
const emit = defineEmits(['change'])

const regionseText = computed(() => {
  if (result.value.length == 0) {
    return '全部区域'
  } else {
    const province = result.value.find((item) => item.name == 'province_code')
    const city = result.value.find((item) => item.name == 'city_code')
    let text = province?.label
    if (city?.value)
      text = truncateString(text, 3) + `/${truncateString(city?.label, 3)}`
    return text
  }
})

const storeText = computed(() => {
  if (result.value.length == 0) {
    return '全部门店'
  } else {
    const store = result.value.find((item) => item.name == 'store_id')
    return store?.label
  }
})


function truncateString(str, maxLength) {
  if (str.length <= maxLength) {
    return str;
  }
  if (maxLength <= 3) {
    return str.substring(0, maxLength) + '...';
  }
  return str.substring(0, maxLength - 3) + '...';
}

const selectMenu = (e) => {
  e.forEach((item) => {
    const findIndex = result.value.findIndex((el) => el.name == item.name)
    if (findIndex >= 0) {
      result.value[findIndex] = item
    } else {
      result.value.push(item)
    }
  })

  debounce(
    () => {
      emit('change', toRaw(arrayToObject(result.value)))
    },
    500,
    false
  )
}

function arrayToObject(arr) {
  const obj = {}
  arr.forEach((item) => {
    obj[item.name] = item.value
  })
  return obj
}

const getData = async () => {
  http.get('/region').then((res) => {
    regions.value = res
    provinces.value = [{ name: '全部区域', code: null }].concat(res.province)
    citys.value = getCityByCode()
    regionsConfirm({
      value: [provinces.value[0], citys.value[0]],
    })
  })
}

const regionsConfirm = (e) => {
  const { value } = e
  const parmas = [
    {
      name: 'province_code',
      value: value[0].code,
      label: value[0].name,
    },
    {
      name: 'city_code',
      value: value[1].code,
      label: value[1].name,
    },
  ]
  selectMenu(parmas)
  getStoreData()
}

const getStoreData = () => {
  storeRef.value?.setIndexs([0], true)
  const params = {
    province_code: result.value.find((item) => item.name == 'province_code')
      ?.value,
    city_code: result.value.find((item) => item.name == 'city_code')?.value,
  }
  http
    .get('/auth/stores', {
      // params: params,
    })
    .then((res) => {
      store.value = [{ title: '全部门店', id: null }].concat(res)
      storeConfirm({ value: [store.value[0]] })
    })
}

const openRegions = () => {
  regionsRef.value?.open()
}

const openStore = () => {
  storeRef.value?.open()
}

const regionsChange = (e) => {
  const { columnIndex, index, indexs } = e
  if (columnIndex === 0) {
    const { code } = provinces.value[index]
    citys.value = getCityByCode(code)
    regionsRef.value?.setIndexs([index, 0], true)
  }
}

const getCityByCode = (code) => {
  const _citys = regions.value.city
  const _city = _citys[code]
  let arr = [{ name: '全部市', code: null }]
  if (_city == null) {
    arr = arr.concat(Object.values(_citys).flat())
  } else {
    arr = arr.concat(_city)
  }
  return arr
}

const storeConfirm = (e) => {
  const parmas = [
    {
      name: 'store_id',
      value: e.value[0].id,
      label: e.value[0].title,
    },
  ]
  selectMenu(parmas)
}
</script>
