<template>
  <view class="pt-60 pb-20 flex-center">
    <uv-navbar title="支付详情" bgColor="#C6171E" leftIconColor="#FFFFFF" :titleStyle="{ color: '#FFFFFF' }" :autoBack="true" :placeholder="true"></uv-navbar>
    <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 state.menuList"
        :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 {onHide, onShow} from "@dcloudio/uni-app";
import {reactive, ref} from "vue";
import {body, get, upload} from "@/utils/https"

const avatar = ref<string>();
const menu = ref<any[]>([]);
const MENU_TEMPLATE = [
  {
    title: "昵称",
    key: "nickname",
    value: "",
  },
  {
    title: "电话",
    key: "",
    disabled: true,
  },
  {
    title: "车牌号",
    key: "defaultPlateNo",
    value: "",
  },
  {
    title: "VIN码",
    key: "vin",
    value: "",
  },
  // {
  //   value: "",
  // },
];


const initState = () => ({
  user: {},
  menuList: []
})

const state = reactive(initState())

const refresh = () => {
  const _menu = [...MENU_TEMPLATE];
  get(`user/profile`).then(res => {
    getApp<any>().globalData.user = res;
  })
  // 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 body(`user/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: "上传中",
    });
    let params = {
      url: `file/upload`,
      filePath: e.detail.avatarUrl,
      success: (res) => {
        body(`user/updateAvatar`, {
          avatar: res.url,
        })
            .then(() => {
              uni.hideLoading();
              uni.showToast({
                title: "已更新",
                icon: "success",
              });
              avatar.value = res.url;
            })
            .catch((err) => {
              uni.hideLoading();
              uni.showModal({
                content: `${err.errMsg},请重试`,
              });
            });
      }
    }
    upload(params)
  } 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) => {
      },
    });
    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: "#2d9e95",
    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) => {
};

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;
    });
  }
});

onHide(() => {
  Object.assign(state, initState());
})
</script>

<style lang="scss" scoped>
.avatar {
  position: relative;
  height: 116rpx !important;
  width: 116rpx !important;
  border-radius: 50%;
  border: 2rpx solid $uni-border-color;
  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: $uni-text-color-inverse;
    font-size: 26rpx;
  }
}

.menu {
  background-color: $uni-bg-color-card;
  height: 120rpx;
  border-bottom: 1rpx solid $uni-border-color-light;

  &:last-child {
    border-bottom: none;
  }
}
</style>
