<template>
  <layout>
    <uv-navbar
        :fixed="false"
        :title="title"
        left-arrow
        @leftClick="goBack"
    />
    <view class="create-address">

      <view class="list noBorder">
        <view class="list-main">
          <view class="list-label w-158">
            收货地址
          </view>
          <view
              class="list-content"
              @click="handleChooseAddress"
          >
            <template v-if="addressData.address.cityId">
              {{ addressData.address.province }} {{ addressData.address.city }} {{ addressData.address.district }}
            </template>
            <template v-else>
              <span class="chooise">
              点击选择
                <uv-icon name="arrow-right"></uv-icon>
              </span>
            </template>
          </view>
        </view>
      </view>
      <view class="list">
        <view class="list-main">
          <view class="list-label w-158">
            详细地址
          </view>
          <view class="list-content">
            <input
                type="text"
                placeholder="请输入详细地址"
                v-model="addressData.detail"
            />

          </view>
        </view>
      </view>
      <view class="list">
        <view class="list-main">
          <view class="list-label w-158">
            姓名
          </view>
          <view class="list-content">
            <input
                type="text"
                placeholder="请输入姓名"
                v-model="addressData.realName"
            />

          </view>
        </view>
      </view>
      <view class="list">
        <view class="list-main">
          <view class="list-label w-158">
            电话
          </view>
          <view class="list-content">
            <input
                type="number"
                placeholder="请输入电话"
                v-model="addressData.phone"
            />
          </view>
        </view>
      </view>
    </view>
    <view class="form-checkbox">
      <uv-checkbox-group v-model="isDefaultList">
        <uv-checkbox
            shape="circle"
            label="设为默认地址"
            name="isDefault"
            labelColor="#999999"
            activeColor="#EE6D46"
            @change="changeDefault"
        ></uv-checkbox>
      </uv-checkbox-group>
    </view>
    <view class="form-buttons">
      <uv-button
          type="primary"
          text="提交"
          customStyle="margin-top: 10px"
          @click="onSave"
      ></uv-button>
    </view>
    <uv-picker
        ref="addressPickerRef"
        :columns="columns"
        keyName="name"
        @change="handlePickerChange"
        @confirm="handlePickerConfirm"
    ></uv-picker>
  </layout>
</template>

<script setup>
import { computed, nextTick, onMounted, ref, unref, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useMainStore } from '@/store/store'
import { getAddressAddAndEdit, getAddressDel, } from '@/api/address'
import { useRouter } from "@/hooks/useRouter";
import { storeToRefs } from "pinia";
import UvPicker from "@/uni_modules/uv-picker/components/uv-picker/uv-picker.vue";

const main = useMainStore()
const {getParams, push, goBack} = useRouter()

const {areaList, address} = storeToRefs(main)
// const areaList = ref(main.areaList)
const title = ref('')

const editId = ref('')

const addressData = ref({
  realName: undefined,
  phone: undefined,
  detail: undefined,
  isDefault: undefined,
  address: {
    cityId: undefined,
    city: undefined,
    district: undefined,
    province: undefined,
  }
});

const isDefaultList = ref([])
const changeDefault = (props) => {
  addressData.value.isDefault = props
}
const actionType = ref('')
const onSave = async () => {
  if (!addressData.value.address?.cityId) {
    uni.showToast({
      title: "请选择收货地址",
      icon: "none",
      duration: 2000
    });
    return;
  }
  if (!addressData.value.detail) {
    uni.showToast({
      title: "请输入详细地址!",
      icon: "none",
      duration: 2000
    });
    return;
  }
  if (!addressData.value.realName) {
    uni.showToast({
      title: "请输入姓名!",
      icon: "none",
      duration: 2000
    });
    return;
  }
  if (!addressData.value.phone || !(/^1[34578]\d{9}$/.test(addressData.value.phone))) {
    uni.showToast({
      title: "请输入正确手机号!",
      icon: "none",
      duration: 2000
    });
    return;
  }
  uni.showLoading({
    title: '保存中',
    mask: true,
  })
  try {
    let res = await getAddressAddAndEdit({
      id: editId.value,
      realName: addressData.value.realName,
      postCode: addressData.value.postCode,
      isDefault: addressData.value.isDefault ? 1 : 0,
      detail: addressData.value.detail,
      phone: addressData.value.phone,
      address: {
        cityId: addressData.value.address.cityId,
        city: addressData.value.address.city,
        district: addressData.value.address.district,
        province: addressData.value.address.province,
      }
    })

    uni.showToast({
      title: "保存成功",
      icon: "none",
      duration: 2000
    });
    uni.hideLoading()
    main.restAddress()
    if (actionType.value == 'select') {
      push({url: '/pages/address/address'}, {data: {type: 'select'},type:'redirectTo'})
    } else {
      main.getAddressList(1)
      goBack()
    }
  } catch (error) {
    console.log(error, 'err')
    // closeToast()
    if (error.msg) {
      // showFailToast(error.msg);
    }
  }


};

const onDelete = async () => {
  getAddressDel()
  main.getAddressList(1)

};

const result = (values) => {
  addressData.value.address = {
    province: values.province.name || '',
    city: values.city.name || '',
    district: values.district.name || '',
    cityId: values.city.id,
  }
}

const addressPickerRef = ref()
const provinces = ref([])
const citys = ref([])
const areas = ref([])
const pickerValue = ref([0, 0, 0])
const defaultValue = ref([0, 0, 0])

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

function handleSetDefaultColumns() {
  console.log(addressPickerRef.value)
  pickerValue.value[0] = provinces.value.findIndex((item, index) => index === defaultValue.value[0])
  citys.value = provinces.value[pickerValue.value[0]].children || []
  pickerValue.value[1] = citys.value.findIndex((item, index) => index === defaultValue.value[1])
  areas.value = citys.value[pickerValue.value[1]].children || []
  pickerValue.value[2] = areas.value.findIndex((item, index) => index === defaultValue.value[2])
  // 重置下位置
  // addressPickerRef.value.setColumnValues(0,provinces.value)
  // addressPickerRef.value.setColumnValues(1,citys.value)
  // addressPickerRef.value.setColumnValues(2,areas.value)
  nextTick(() => {
    addressPickerRef.value.setIndexs([pickerValue.value[0], pickerValue.value[1], pickerValue.value[2]], true);
    console.log('设置完毕')
  })
}

function handlePickerChange(e) {
  const {columnIndex, index, indexs} = e
  // 改变了省
  if (columnIndex === 0) {
    citys.value = provinces.value[index]?.children || []
    areas.value = citys.value[0]?.children || []
    addressPickerRef.value.setIndexs([index, 0, 0], true)
  } else if (columnIndex === 1) {
    areas.value = citys.value[index]?.children || []
    addressPickerRef.value.setIndexs(indexs, true)
  }
}

function handlePickerConfirm(e) {
  const {indexs, value} = e
  defaultValue.value = indexs
  addressData.value.address = {
    province: value[0].name || '',
    city: value[1].name || '',
    district: value[2].name || '',
    cityId: value[1].id,
  }
}

function handleFindDefault(data) {
  const provinceIndex = areaList.value.findIndex(item => item.name === data.province);
  const cityIndex = areaList.value[provinceIndex].children.findIndex(item => item.name === data.city);
  const areasIndex = areaList.value[provinceIndex].children[cityIndex].children.findIndex(item => item.name === data.district);
  defaultValue.value = [provinceIndex, cityIndex, areasIndex]
}

function handleChooseAddress() {
  provinces.value = areaList.value
  handleSetDefaultColumns()
  unref(addressPickerRef).open()
}

onLoad(async (options) => {
  const params = getParams(options)
  let id = params.id
  actionType.value = params.type
  // main.restAddress()
  await main.getAddressCityList()
  if (id) {
    editId.value = id
    title.value = '编辑地址'
    let data = address.value.filter(item => item.id == id)[0]
    if (!data) return
    addressData.value = {
      realName: data.realName,
      phone: data.phone,
      detail: data.detail,
      isDefault: data.isDefault,
      address: {
        cityId: data.cityId,
        city: data.city,
        district: data.district,
        province: data.province,
      }
    }
    // 设置默认选择
    handleFindDefault(data)
    isDefaultList.value = data.isDefault ? ['isDefault'] : []
  } else {
    title.value = '新增地址'
  }
})
onMounted(() => {
})
</script>

<style lang="scss">
.create-address {
  background: #fff;
}

.form-checkbox {
  padding-left: 35rpx;
}

.w-158 {
  flex: 0 0 158rpx;
}

.chooise {
  @include useFlex(space-between, center);
  color: #999;
}
</style>
