<template>
  <view class="personal-info">
    <!-- 上传 -->
    <view class="upload-box">
      <up-upload
        @afterRead="
          async (e) => {
            await afterRead(e);
            getImage();
          }
        "
        name="1"
        :maxCount="1"
        :previewImage="false"
        :deletable="false"
        :multiple="false"
      >
        <!-- <template #default> -->
        <view class="upload-block">
          <up-avatar
            size="160rpx"
            shape="circle"
            :src="userInfo.avatar"
            mode="aspectFill"
          ></up-avatar>
        </view>
        <!-- </template> -->
      </up-upload>
    </view>
		<view class="flex-center-between personal-info-item">
			<text class="label_width">昵称</text>
			<up-input
          class="title-input"
          placeholder="请输入"
          type="text"
          confirmType="完成"
          maxlength="50"
          :adjustPosition="false"
          border="none"
          :showWordLimit="true"
          v-model="userInfo.nickname"
					inputAlign="right"
          @blur="changeName"
        ></up-input>
		</view>
		<view class="flex-center-between personal-info-item">
			<text class="label_width">手机号</text>
			<text class="gray">{{telEncrypt(userInfo.phone)}}</text>
		</view>
		<view class="flex-center-between personal-info-item" @click="pickerSexShow = true">
			<text class="label_width">性别</text>
			<view class="flex-center-between">
				<text>{{sexText}}</text>
				<uni-icons type="right" size="21"  color="#888"></uni-icons>
			</view>
		</view>
		<view class="flex-center-between personal-info-item">
			<text class="label_width">地址</text>
      <picker mode="multiSelector" @change="bindRegionChange" @columnchange="bindMultiPickerColumnChange"
        :value="valueRegion" :range="multiArray">
        <view class='flex-center-between'>
          <view class="picker line1">{{ region[0] }}，{{ region[1] }}，{{ region[2] }}</view>
					<uni-icons type="right" size="21"  color="#888"></uni-icons>
        </view>
      </picker>
      <!-- <up-input
          class="title-input"
          placeholder="请输入"
          type="text"
          confirmType="完成"
          maxlength="50"
          :adjustPosition="false"
          border="none"
          :showWordLimit="true"
          v-model="userInfo.addres"
					inputAlign="right"
          @blur="change"
        ></up-input> -->
    </view>
    <view class="flex-center-between personal-info-item">
      <text class="label_width">年龄</text>
      <up-input
        class="title-input"
        placeholder="请输入"
        type="text"
        confirmType="完成"
        maxlength="50"
        :adjustPosition="false"
        border="none"
        :showWordLimit="true"
        v-model="userInfo.age"
        inputAlign="right"
      ></up-input>
    </view>
    <view class="flex-center-between personal-info-item">
      <text class="label_width">个人简介</text>
      <up-input
        class="title-input"
        placeholder="请输入"
        type="text"
        confirmType="完成"
        maxlength="50"
        :adjustPosition="false"
        border="none"
        :showWordLimit="true"
        v-model="userInfo.mark"
        inputAlign="right"
      ></up-input>
    </view>
<!--    <view-->
<!--      class="flex-center-between border-bottom personal-info-item"-->
<!--      @tap.stop="setPayword"-->
<!--    >-->
<!--      <text class="label_width">支付密码</text>-->
<!--      &lt;!&ndash; <up-input-->
<!--        class="title-input"-->
<!--        placeholder="请输入"-->
<!--        type="text"-->
<!--        confirmType="完成"-->
<!--        maxlength="6"-->
<!--        :adjustPosition="false"-->
<!--        border="none"-->
<!--        :showWordLimit="true"-->
<!--        v-model="userInfo.payPassword"-->
<!--        inputAlign="right"-->
<!--        :password="true"-->
<!--        :disabled="true"-->
<!--        :passwordVisibilityToggle="false"-->
<!--        disabledColor=""-->
<!--      ></up-input> &ndash;&gt;-->
<!--      <text>* * * * * *</text>-->
<!--    </view>-->
    <up-picker
      @confirm="changeSex"
      @cancel="pickerSexShow = false"
      :show="pickerSexShow"
      :columns="[
        [
          { label: '男', id: 1 },
          { label: '女', id: 2 },
          { label: '保密', id: 3 },
        ],
      ]"
      keyName="label"
      valueName="id"
    ></up-picker>
    <button
      @click="submitFn"
      class="submit-btn"
    >提交</button>
    <!-- 页面内 容结束 -->
    <PayPop ref="paypopRef" :pwdlength="6" @pwd_e="handlerPwd"></PayPop>
  </view>
</template>

<script setup>
import { ref, computed, nextTick } from "vue";
import PayPop from "../../../components/pay-pop/pay-pop.vue";
import { useImageUpload } from "@/hooks/useImageUpload";
import { useAppStore } from "@/stores/app";
import { onLoad } from "@dcloudio/uni-app";
import { useToast } from "@/hooks/useToast";
import { getUserInfo, userEdit, registerpayPasswordAPI } from "@/api/user";
import { getCity } from "@/api/api.js";
import Cache from "@/utils/cache";
import { telEncrypt } from "@/utils/util.js";
const paypopRef = ref(null);
const { Toast } = useToast();
const { imageList, afterRead, deletePic, uploadLoading } = useImageUpload({
  pid: 5,
  model: "book",
});
const appStore = useAppStore();
const userInfo = ref({
  avatar: "",
  nickname: "",
  addres: "",
  mark: "",
  sex: "",
  age: "",
});
const pickerSexShow = ref(false);
const sexText = computed(() => {
  return userInfo.value.sex == 1
    ? "男"
    : userInfo.value.sex == 2
    ? "女"
    : userInfo.value.sex == 3
    ? "保密"
    : "未知";
});

//省市区选择
const district = ref([]);
const multiArray = ref([[], [], []]);
const multiIndex = ref([0, 0, 0]);
const region = ref(["省", "市", "区"]);
const valueRegion = ref([0, 0, 0]);

onLoad(() => {
  console.log("personal_info 页面 onLoad");
  fetchUserInfo();
  getCityList();
});

const changeSex = (e) => {
  console.log("changeSex", e.value[0]);
  userInfo.value.sex = e.value[0].id;
  pickerSexShow.value = false;
  // change();
};
// 设置支付密码
const setPayword = () => {
  console.log(111111);

  console.log(paypopRef.value);
  nextTick(() => {
    paypopRef.value.Open();
  });
};
const handlerPwd = async (e) => {
  const res = await registerpayPasswordAPI({
    account: appStore.userInfo.phone,
    payPassword: e,
  });
  uni.showToast({
    title: "修改成功",
    duration: 2000,
  });
  change();
};
// 获取用户头像
async function getImage() {
  console.log("getImage", imageList.value[0]);
  if (imageList.value.length > 0) {
    if (imageList.value[0].status == "success") {
      userInfo.value.avatar = imageList.value[0].info.url;
      // change();
    } else {
      Toast({ title: "上传失败" });
    }
  }
  imageList.value = [];
}
function submitFn() {
  change();
}
function changeName(e) {
  // console.log(e)
  // console.log(userInfo.value)
}
const change = async () => {
  await userEdit(userInfo.value);
  Toast({ title: "修改成功", endtime: 1500 });
  appStore.USERINFO();
  setTimeout(() => {
    uni.navigateBack();
  }, 1600);
  // const { data } = await getUserInfo(appStore.uid);
  // appStore.UPDATE_userPanelInfo(data);
};
// 获取用户信息
async function fetchUserInfo() {
  try {
    const { data } = await getUserInfo(appStore.uid);
    userInfo.value = data;
    userInfo.value.addres = userInfo.value.addres || "";
    const list = userInfo.value.addres.split("-");
    if (list.length > 0) {
      region.value = [list[0], list[1], list[2]];
    }
  } catch (error) {
    console.error("otherUserinfo", error);
    Toast({ title: "获取用户信息失败" });
  }
}

function bindRegionChange(e) {
  const mi = multiIndex.value;
  const province = district.value[mi[0]] || { child: [] };
  const ma = multiArray.value;
  const value = e.detail.value;
  region.value = [ma[0][value[0]], ma[1][value[1]], ma[2][value[2]]];
  userInfo.value.addres = region.value.join("-");
  valueRegion.value = [0, 0, 0];
  //   change();
  initialize();
}

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 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];
}
</script>

<style lang="scss">
.personal-info {
  padding: 0 30rpx;

  .upload-block {
    display: flex;
    justify-content: center;
    width: 90vw;
    box-sizing: border-box;
    padding: 80rpx 0;
  }
  .personal-info-item {
    height: 100rpx;
    line-height: 100rpx;
    padding: 0 30rpx;
    box-sizing: border-box;
    border-radius: 16rpx;
    background-color: #FFF;
    margin-bottom: 30rpx;
    .label_width {
      width: 200rpx;
      display: inline-block;
    }
  }
  .submit-btn {
    font-size: 32rpx;
    color: #333;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 16rpx;
    background-color: #F8C008;
    border: none;
    margin-top: 20px;
  }
}
</style>
