<template>
  <view class="edit">
    <uv-navbar title="修改资料" placeholder autoBack></uv-navbar>
    <form @submit="formSubmit">
      <view class="middle">
        <view class="item">
          <view class="left"> 头像 </view>
          <view class="right">
            <image
              v-if="unserInfo.headPhoto"
              :src="unserInfo.headPhoto"
              @click="uploadImg"
              mode="aspectFill"
            >
            </image>
            <image
              v-else
              :src="$defaultAvatar"
              mode="aspectFill"
              @click="uploadImg"
            ></image>
            <text class="iconfont">&#xe6c7;</text>
          </view>
        </view>
        <view class="name-item">
          <view class="name-left"> 姓名 </view>
          <view class="name-right">
            <input
              type="text"
              :value="unserInfo.nickname"
              maxlength="32"
              @input="onName"
              class="my-name"
            />
            <text class="iconfont">&#xe6c7;</text>
          </view>
        </view>
        <view class="item">
          <view class="left"> 手机号 </view>
          <view class="right">
            <view class="phone">
              {{ unserInfo.mobile }}
            </view>
          </view>
        </view>
        <view class="item">
          <view class="left"> 性别 </view>
          <view class="right" v-if="platform.length > 0">
            <picker
              class="choice"
              @change="bindPickerChange"
              :value="unserInfo.gender"
              :range="platform"
              range-key="name"
            >
              <view class="uni-input"
                >{{ platform[index].name
                }}<text class="iconfont">&#xe6c7;</text>
              </view>
            </picker>
          </view>
        </view>
        <view class="item">
          <view class="left"> 生日 </view>
          <view class="right" style="flex: 1">
            <picker
              style="flex: 1; height: 38rpx; text-align: right"
              mode="date"
              :value="date"
              :start="startDate"
              :end="endDate"
              @change="bindDateChange"
            >
              <view class="uni-input">{{ date ? date : "未知" }}</view>
            </picker>
            <text class="iconfont">&#xe6c7;</text>
          </view>
        </view>
      </view>

      <view class="submit-top">
        <button class="submit" form-type="submit">修改资料</button>
      </view>
    </form>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { userInfo, personalDataUpdate_Api } from "@/api/login.js";
import { commonUpload_api } from "@/api/index";
const platform = ref([
  {
    name: "保密",
  },
  {
    name: "男",
  },
  {
    name: "女",
  },
]);
// 获取日期
const getDate = (type) => {
  const date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  if (type === "start") {
    year = year - 150;
  } else if (type === "end") {
    year = year + 150;
  }
  month = month > 9 ? month : "0" + month;
  day = day > 9 ? day : "0" + day;
  return `${year}-${month}-${day}`;
};

const imgSize = ref(4);
const index = ref(0);
const date = ref(getDate({ format: true }));
const startDate = ref(getDate("start"));
const endDate = ref(getDate("end"));
const unserInfo = ref({});
const imgType = ref(["jpeg", "png", "jpg"]);

// 获取个人信息
const getUserInfo = () => {
  userInfo().then((res) => {
    index.value = res.data.gender; //男女
    date.value = res.data.birthday;
    unserInfo.value = res.data;
  });
};

const formSubmit = (e) => {
  let gender = index.value.toString();
  let param = {
    realName: unserInfo.value.realName,
    headPhoto: unserInfo.value.headPhoto, //this.unserInfo.headPhoto, //图像
    gender: gender, //性别
    birthday: date.value, //生日
    nickname: unserInfo.value.realName,
  };
  console.log(param, "param");
  personalDataUpdate_Api(param).then((res) => {
    if (res.code == 200) {
      uni.$uv.toast("修改成功");
    } else {
      uni.$uv.toast("修改失败");
    }
  });
};

const updataImg = (filePath, nameStr) => {
  console.log(filePath, nameStr);
  let shopid = uni.getStorageSync("shop");
  let id = 0;
  if (!shopid) {
    id = 0;
  } else {
    id = shopid.id;
  }
  commonUpload_api(filePath)
    .then((res) => {
      uni.hideLoading();
      if (res.code != 200) {
        return;
      }
      // let resObj = JSON.parse(res.data);
      let imgurl = res.data.url;
      uni.showToast({
        title: "上传成功",
        icon: "success",
        duration: 1000,
      });
      unserInfo.value.headPhoto = imgurl;
    })
    .catch((err) => {
      uni.hideLoading();
      uni.showModal({
        content: err.errMsg,
        showCancel: false,
      });
    });
  // uni.uploadFile({
  //   url: uni.$mConfig.baseUrl + "/sys/oss/upload",
  //   filePath: filePath,
  //   fileType: "image",
  //   name: "file",
  //   success: (res) => {},
  //   fail: (err) => {},
  // });
};
// 随机字符串
const random_string = (len) => {
  len = len || 32;
  var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
  var maxPos = chars.length;
  var pwd = "";
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
};
//更换图片
const uploadImg = () => {
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album"], //从相册选择
    success: (res) => {
      if (res) {
        let filePath = res.tempFilePaths[0];
        let nameStr =
          random_string(8) + "." + res.tempFilePaths[0].split(".").pop();
        if (res.tempFiles) {
          for (let item of res.tempFiles) {
            if (item.size > imgSize.value * 1024 * 1024) {
              uni.showToast({
                title: `图片不能大于${imgSize.value}M`,
                icon: "none",
              });
              return false;
            }
            if (item.type) {
              let r = imgType.value.some((v) => {
                let type = item.type.split("/");
                if (type.length) return v === type[1];
              });
              if (!r) {
                uni.showToast({
                  title: `只允许上传${imgType.value}的类型`,
                  icon: "none",
                });
                return false;
              }
            }
          }
        }
        updataImg(filePath, nameStr);
      }
    },
  });
};

const onName = (e) => {
  console.log(e.detail.value, "e.detail.value");
  unserInfo.value.realName = e.detail.value;
};

const bindPickerChange = (e) => {
  console.log("picker发送选择改变，携带值为", e.detail.value);
  index.value = e.detail.value;
};

const bindDateChange = (e) => {
  console.log("picker发送选择改变，携带值为", e.detail.value);
  date.value = e.detail.value;
};

onLoad(() => {
  getUserInfo();
});

onShow(() => {});
</script>

<style scoped lang="scss">
.name-item {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #e6e6e6;
  padding: 34rpx 0 30rpx 0;

  .name-right {
    flex: 1;
    padding-left: 30rpx;
    text-align: right;
    display: flex;
    align-items: center;

    .my-name {
      width: 100%;
    }
  }
}

.submit-top {
  box-sizing: border-box;

  width: 100%;
  padding: 0 30rpx;
  position: fixed;
  bottom: 60rpx;
}

.submit {
  box-sizing: border-box;

  text-align: center;
  border-radius: 43rpx;
  margin-top: 350rpx;
  font-size: 36rpx;
  color: #ffffff;
  font-weight: 400;
  background-color: #eb5153;
}

.distance {
  height: 10rpx;
  background-color: #f5f5f5;
}

.middle {
  padding: 0 30rpx;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1rpx solid #e6e6e6;
    padding: 34rpx 0 30rpx 0;

    .left {
      font-size: 28rpx;
      color: #1a1a1a;
      font-weight: 400;
    }

    .right {
      display: flex;
      align-items: center;

      .my-phone {
        text-align: right;
      }

      .my-name {
        text-align: right;
      }

      .name {
        font-size: 28rpx;
        color: #1a1a1a;
        font-weight: 400;
      }

      image {
        width: 76rpx;
        height: 76rpx;
        border-radius: 50%;
      }

      .iconfont {
        margin-left: 15rpx;
      }
    }
  }
}
</style>
