<template>
  <view>
    <!-- #ifdef APP-->
    <view class="status"></view>
    <!-- #endif -->
    <form @submit="formSubmit" report-submit="true">
      <view class="addAddress pad30">
        <view class="list borRadius14">
          <view class="item acea-row row-between-wrapper" style="border: none">
            <view class="name">姓名</view>
            <input
              type="text"
              placeholder="请输入姓名"
              placeholder-style="color:#ccc;"
              name="realName"
              :value="userAddress.realName"
              placeholder-class="placeholder"
            />
          </view>
          <view class="item acea-row row-between-wrapper">
            <view class="name">联系电话</view>
            <input
              type="number"
              placeholder="请输入联系电话"
              placeholder-style="color:#ccc;"
              name="phone"
              :value="userAddress.phone"
              placeholder-class="placeholder"
              maxlength="11"
            />
          </view>
          <view class="item acea-row row-between-wrapper relative">
            <view class="name">所在地区</view>
            <view class="address">
              <picker
                mode="multiSelector"
                @change="bindRegionChange"
                @columnchange="bindMultiPickerColumnChange"
                :value="valueRegion"
                :range="multiArray"
              >
                <view class="acea-row">
                  <view class="picker line1"
                    >{{ region[0] }}，{{ region[1] }}，{{ region[2] }}</view
                  >
                  <view class="iconfont icon-xiangyou abs_right"></view>
                </view>
              </picker>
            </view>
          </view>
          <view class="item acea-row row-between-wrapper relative">
            <view class="name">详细地址</view>
            <input
              type="text"
              placeholder="请填写具体地址"
              placeholder-style="color:#ccc;"
              name="detail"
              placeholder-class="placeholder"
              v-model="userAddress.detail"
              maxlength="100"
            />
            <view
              class="iconfont icon-dizhi font-color abs_right"
              @tap="chooseLocation"
            ></view>
          </view>
        </view>
        <view class="default acea-row row-middle borRadius14">
          <up-checkbox-group @change="ChangeIsDefault" shape="circle" class="check-box">
            <up-checkbox :checked="userAddress.isDefault" activeColor="#F8C008" />设置为默认地址
          </up-checkbox-group>
        </view>

        <button class="keepBnt bg-color" form-type="submit">立即保存</button>
        <!-- #ifdef MP -->
        <view class="wechatAddress" v-if="!id" @click="getWxAddress"
          >导入微信地址</view
        >
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <view
          class="wechatAddress"
          v-if="wechat.isWeixin() && !id"
          @click="getAddress"
          >导入微信地址</view
        >
        <!-- #endif -->
      </view>
    </form>
    <!-- #ifdef MP -->
    <!-- <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize> -->
    <!-- #endif -->
    <!-- <home></home> -->
  </view>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive, watch } from "vue";
import { useAppStore } from "@/stores/app.js";
import { editAddress, getAddressDetail } from "@/api/user.js";
import { getCity } from "@/api/api.js";
import { toLogin } from "@/libs/login.js";
import { useToast } from "@/hooks/useToast.js";
import wechat from "@/libs/wechat.js";
import Cache from "@/utils/cache";
// #ifdef MP
// import authorize from '@/components/Authorize';
// #endif
// import home from "@/components/home";

const { Toast } = useToast();
const appStore = useAppStore();

const regionDval = ["浙江省", "杭州市", "滨江区"];
const cartId = ref("");
const pinkId = ref(0);
const couponId = ref(0);
const id = ref(0);
const userAddress = reactive({
  isDefault: false,
  realName: "",
  phone: "",
  detail: "",
});
const region = ref(["省", "市", "区"]);
const valueRegion = ref([0, 0, 0]);
const isAuto = ref(false);
const isShowAuth = ref(false);
const district = ref([]);
const multiArray = ref([[], [], []]);
const multiIndex = ref([0, 0, 0]);
const cityId = ref(0);
const defaultRegion = ["广东省", "广州市", "番禺区"];
const defaultRegionCode = "440113";
const bargain = ref(false);
const combination = ref(false);
const secKill = ref(false);
const preOrderNo = ref(0);

watch(
  () => appStore.isLogin,
  (newV) => {
    if (newV) {
      getUserAddress();
      getCityList();
    }
  }
);

onLoad((options) => {
  if (appStore.isLogin) {
    preOrderNo.value = options.preOrderNo || 0;
    id.value = options.id || 0;
    uni.setNavigationBarTitle({
      title: options.id ? "修改地址" : "添加地址",
    });
    getUserAddress();
    if (Cache.has("cityList")) {
      district.value = Cache.getItem("cityList");
      initialize();
    } else {
      getCityList();
    }
  } else {
    toLogin();
  }
});

function getCityList() {
  getCity().then((res) => {
    district.value = res.data;
    let oneDay = 24 * 3600 * 1000;
    Cache.setItem({ name: "cityList", value: res.data, expires: oneDay * 7 }); //设置七天过期时间
    initialize();
  });
}

function initialize() {
  if (district.value.length) {
    let province = [],
      city = [],
      area = [];
    let cityChildren = district.value[0].child || [];
    let areaChildren = cityChildren.length ? cityChildren[0].child || [] : [];
    district.value.forEach((item) => province.push(item.name));
    cityChildren.forEach((item) => city.push(item.name));
    areaChildren.forEach((item) => area.push(item.name));
    multiArray.value = [province, city, area];
  }
}

function bindRegionChange(e) {
  const mi = multiIndex.value;
  const province = district.value[mi[0]] || { child: [] };
  const city = province.child[mi[1]] || { cityId: 0 };
  const ma = multiArray.value;
  const value = e.detail.value;
  region.value = [ma[0][value[0]], ma[1][value[1]], ma[2][value[2]]];
  cityId.value = city.cityId;
  valueRegion.value = [0, 0, 0];
  initialize();
}

function bindMultiPickerColumnChange(e) {
  const column = e.detail.column;
  const value = e.detail.value;
  const ma = multiArray.value;
  const mi = multiIndex.value;
  mi[column] = value;
  switch (column) {
    case 0:
      const currentCity = district.value[value] || { child: [] };
      const areaList = currentCity.child[0] || { child: [] };
      ma[1] = currentCity.child.map((item) => item.name);
      ma[2] = areaList.child.map((item) => item.name);
      break;
    case 1:
      const cityList = district.value[mi[0]].child[mi[1]].child || [];
      ma[2] = cityList.map((item) => item.name);
      break;
    case 2:
      break;
  }
  multiArray.value = [...ma];
  multiIndex.value = [...mi];
}

function getUserAddress() {
  if (!id.value) return;
  getAddressDetail(id.value).then((res) => {
    const regionArr = [res.data.province, res.data.city, res.data.district];
    Object.assign(userAddress, res.data);
    region.value = regionArr;
    cityId.value = res.data.cityId;
  });
}

function chooseLocation() {
  uni.chooseLocation({
    success: (res) => {
      userAddress.detail = res.address.replace(
        /.+?(省|市|自治区|自治州|县|区)/g,
        ""
      );
    },
  });
}

// 导入微信地址（小程序）
function getWxAddress() {
  uni.authorize({
    scope: "scope.address",
    success: function () {
      uni.chooseAddress({
        success: function (res) {
          let addressP = {
            province: res.provinceName,
            city: res.cityName,
            district: res.countyName,
            cityId: 0,
          };
          editAddress({
            address: addressP,
            isDefault: 1,
            realName: res.userName,
            postCode: res.postalCode,
            phone: res.telNumber,
            detail: res.detailInfo,
            id: 0,
          })
            .then((res2) => {
              setTimeout(() => {
                if (cartId.value) {
                  let url = `/pages/users/order_confirm/index?cartId=${
                    cartId.value
                  }&addressId=${id.value ? id.value : res2.data.id}&pinkId=${
                    pinkId.value
                  }&couponId=${couponId.value}&secKill=${
                    secKill.value
                  }&combination=${combination.value}&bargain=${bargain.value}`;
                  cartId.value = "";
                  pinkId.value = "";
                  couponId.value = "";
                  uni.navigateTo({ url });
                } else {
                  uni.navigateBack({ delta: 1 });
                }
              }, 1000);
              Toast({ title: "添加成功", icon: "success" });
            })
            .catch((err) => {
              Toast({ title: err });
            });
        },
        fail: function (res) {
          if (res.errMsg == "chooseAddress:cancel")
            return Toast({ title: "取消选择" });
        },
      });
    },
    fail: function () {
      uni.showModal({
        title: "您已拒绝导入微信地址权限",
        content: "是否进入权限管理，调整授权？",
        success(res) {
          if (res.confirm) {
            uni.openSetting({});
          } else if (res.cancel) {
            Toast({ title: "已取消！" });
          }
        },
      });
    },
  });
}

// 导入共享地址（微信）；
function getAddress() {
  wechat
    .openAddress()
    .then((userInfo) => {
      editAddress({
        id: id.value,
        realName: userInfo.userName,
        phone: userInfo.telNumber,
        address: {
          province: userInfo.provinceName,
          city: userInfo.cityName,
          district: userInfo.countryName,
          cityId: 0,
        },
        detail: userInfo.detailInfo,
        isDefault: 1,
        postCode: userInfo.postalCode,
      })
        .then((res2) => {
          setTimeout(() => {
            if (cartId.value) {
              let url = `/pages/users/order_confirm/index?cartId=${
                cartId.value
              }&addressId=${id.value ? id.value : res2.data.id}&pinkId=${
                pinkId.value
              }&couponId=${couponId.value}&secKill=${
                secKill.value
              }&combination=${combination.value}&bargain=${bargain.value}`;
              cartId.value = "";
              pinkId.value = "";
              couponId.value = "";
              uni.navigateTo({ url });
            } else {
              uni.navigateTo({ url: "/pages/users/user_address_list/index" });
            }
          }, 1000);
          Toast({ title: "添加成功", icon: "success" });
        })
        .catch((err) => {
          Toast({ title: err || "添加失败" });
        });
    })
    .catch((err) => {
      console.log(err);
    });
}

function formSubmit(e) {
  const value = e.detail.value;
  if (!value.realName) return Toast({ title: "请填写收货人姓名" });
  if (!value.phone) return Toast({ title: "请填写联系电话" });
  if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value.phone))
    return Toast({ title: "请输入正确的手机号码" });
  if (region.value == "省-市-区") return Toast({ title: "请选择所在地区" });
  if (!value.detail) return Toast({ title: "请填写详细地址" });
  value.id = id.value;
  let regionArray = region.value;
  value.address = {
    province: regionArray[0],
    city: regionArray[1],
    district: regionArray[2],
    cityId: cityId.value,
  };
  value.isDefault = userAddress.isDefault;

  uni.showLoading({
    title: "保存中",
    mask: true,
  });
  editAddress(value)
    .then((res2) => {
      Toast({
        title: id.value ? "修改成功" : "添加成功",
        icon: "success",
      });
      setTimeout(() => {
        if (preOrderNo.value > 0) {
          uni.redirectTo({
            url: `/pages/users/order_confirm/index?preOrderNo=${
              preOrderNo.value
            }&addressId=${id.value ? id.value : res2.data.id}`,
          });
        } else {
          // #ifdef H5
          history.back();
          // #endif
          // #ifndef H5
          uni.navigateBack({ delta: 1 });
          // #endif
        }
      }, 1000);
    })
    .catch((err) => {
      Toast({ title: err });
    });
}

function ChangeIsDefault() {
  userAddress.isDefault = !userAddress.isDefault;
}
</script>

<style scoped lang="scss">
.addAddress {
  padding-top: 20rpx;
}

.addAddress .list {
  background-color: #fff;
  padding: 0 24rpx;
}

.addAddress .list .item {
  border-top: 1rpx solid #eee;
  height: 90rpx;
  line-height: 90rpx;
}

.addAddress .list .item .name {
  // width: 195rpx;
  font-size: 30rpx;
  color: #333;
}

.addAddress .list .item .address {
  flex: 1;
  margin-left: 50rpx;
}

.addAddress .list .item input {
  width: 475rpx;
  font-size: 30rpx;
  font-weight: 400;
}

.addAddress .list .item .placeholder {
  color: #ccc;
}

.addAddress .list .item picker .picker {
  width: 410rpx;
  font-size: 30rpx;
}

.addAddress .default {
  padding: 0 30rpx;
  height: 90rpx;
  background-color: #fff;
  margin-top: 23rpx;
}

.addAddress .default checkbox {
  margin-right: 15rpx;
}

.addAddress .keepBnt {
  width: 690rpx;
  height: 86rpx;
  border-radius: 50rpx;
  text-align: center;
  line-height: 86rpx;
  margin: 80rpx auto 24rpx auto;
  font-size: 32rpx;
  color: #fff;
}

.addAddress .wechatAddress {
  width: 690rpx;
  height: 86rpx;
  border-radius: 50rpx;
  text-align: center;
  line-height: 86rpx;
  margin: 0 auto;
  font-size: 32rpx;
  color: #F8C008;
  border: 1px solid #F8C008;
}

.relative {
  position: relative;
}

.icon-dizhi {
  font-size: 44rpx;
  z-index: 100;
}

.abs_right {
  position: absolute;
  right: 0;
}

.status {
  display: flex;
  width: 750rpx;
  // background-color: #E93323;
  height: var(--status-bar-height);
}
:deep(.u-checkbox-group){
  align-items: center;
}
</style>
