<template>
  <view class="pt-60 pb-20 flex-center">
    <button
      class="avatar"
      open-type="chooseAvatar"
      @chooseavatar="chooseAvatar"
    >
      <image class="avatar_image" :src="avatar" @error="errorHandle"></image>
      <view class="avatar_text flex-center">编辑</view>
    </button>
  </view>

  <view class="pl-50 pr-50">
    <view
      class="menu flex-align-center flex-between"
      v-for="(item, index) in menu"
      :key="index"
      @click="edit(index)"
    >
      <view class="fs-30">{{ item.title }}</view>
      <view class="flex">
        <view
          :class="['fs-30', 'fw-500', `mr-${item.disabled ? '0' : '20'}`]"
          style="color: rgba(0, 0, 0, 0.8)"
          >{{ item.value }}</view
        >
        <uni-icons
          type="right"
          size="12"
          color="rgba(0,0,0,0.4)"
          v-if="!item.disabled"
        ></uni-icons>
      </view>
    </view>
  </view>

  <style-bottom-view>
    <view class="pl-60 pr-60 pb-40">
      <style-button type="primary" @click="logoutUser">退出登录</style-button>
    </view>
  </style-bottom-view>
</template>

<script setup lang="ts">
import { clearToken } from "../../api/auth";
import { fetchProfile, updateProfile, logout } from "../../api/user";
import { upload } from "../../utils/uploader";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
const avatar = ref<string>();
const menu = ref<any[]>([]);

const refresh = () => {
  const _menu = [
    {
      title: "昵称",
      key: "nickname",
      value: "",
    },
    {
      title: "电话",
      key: "",
      disabled: true,
    },
    {
      title: "车牌号",
      key: "defaultPlateNo",
      value: "",
    },
    {
      title: "VIN码",
      key: "vin",
      value: "",
    },
    // {
    //   title: "充电卡",
    //   key: "",
    //   value: "",
    // },
  ];
  fetchProfile().then(() => {
    const user = getApp<any>().globalData.user;
    if (user) {
      _menu[0].value = user.nickname;
      _menu[1].value = user.mobilePhone;
      _menu[2].value = user.defaultPlateNo;
      _menu[3].value = user.vin;
      // _menu[4].value = user.card_no;
      avatar.value =
        user.avatar ||
        "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0";
      menu.value = _menu;
    }
  });
};

const save = (form: Record<string, any>) => {
  uni.showLoading({
    title: "保存中",
  });
  return updateProfile(form)
    .then((res) => {
      uni.hideLoading();
      uni.showToast({
        icon: "success",
        title: "保存成功",
      });
      refresh();
      return res;
    })
    .catch((err) => {
      uni.hideLoading();
      uni.showModal({
        content: `${err.errMsg},请重试`,
      });
    });
};

const chooseAvatar = (e: any) => {
  if (e.detail.avatarUrl) {
    uni.showLoading({
      title: "上传中",
    });
    upload(e.detail.avatarUrl, {
      onSuccess: (res) => {
        updateProfile({
          avatar: res.url,
        })
          .then(() => {
            uni.hideLoading();
            uni.showToast({
              title: '已更新',
              icon: 'success'
            });
            avatar.value = res.url;
          })
          .catch((err) => {
            uni.hideLoading();
            uni.showModal({
              content: `${err.errMsg},请重试`,
            });
          });
      },
      onFail: (err) => {
        uni.hideLoading();
        uni.showModal({
          content: `${err.errMsg},请重试`,
        });
      },
    });
  } else {
    uni.showModal({
      content: `${e.detail.errMsg},请重试`,
    });
  }
};
const edit = (index: number) => {
  const menuItem = menu.value[index];
  if (menuItem.disabled) {
    return;
  }
  if (!menuItem.key) {
    uni.showToast({
      icon: "none",
      title: "暂不支持修改",
    });
    return;
  }
  if (/车牌/.test(menuItem.title)) {
    uni.chooseLicensePlate({
      success: (res) => {
        save({
          defaultPlateNo: res.plateNumber,
        });
      },
      fail: (err) => {
        console.log(err);
      },
    });
    return;
  }
  uni.navigateTo({
    url: `/pages-user/profile-edit/profile-edit?key=${menuItem.key}&title=${
      menuItem.title
    }${menuItem.value ? `&value=${encodeURIComponent(menuItem.value)}` : ""}`,
  });
};

const logoutUser = () => {
  uni.showModal({
    title: "温馨提示",
    content: "确定退出登录吗？",
    confirmColor: "#347DFF",
    confirmText: "确定退出",
    cancelText: "手滑了",
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({
          title: "退出中",
        });
        logout()
          .then(() => {
            uni.hideLoading();
            uni.showToast({
              icon: "success",
              title: "已退出",
            });
            clearToken();
            setTimeout(() => {
              uni.reLaunch({
                url: "/pages/map/map",
              });
            }, 1500);
          })
          .catch((err) => {
            uni.hideLoading();
            uni.showModal({
              content: `${err.errMsg},请重试`,
            });
          });
      }
    },
  });
};

const errorHandle = (e: any) => {
  console.log(e);
};

onLoad(() => {
  refresh();
});
onShow(() => {
  if (getApp<any>().globalData.lastData.profile) {
    const { key, value } = getApp<any>().globalData.lastData.profile;
    save({
      [key]: value,
    }).then(() => {
      getApp<any>().globalData.lastData.profile = undefined;
    });
  }
});
</script>

<style lang="scss">
.avatar {
  position: relative;
  height: 116rpx !important;
  width: 116rpx !important;
  border-radius: 50%;
  border: 2rpx solid rgba(0, 0, 0, 0.15);
  overflow: hidden;
  &_image {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    border-radius: 50%;
  }
  &_text {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 40rpx;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 24rpx;
  }
}

.menu {
  background-color: #fff;
  height: 120rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
  &:last-child {
    border-bottom: none;
  }
}
</style>
