<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
  <view v-if="user">
    <cu-custom bgImage="/static/bg.png" :isBack="true">
      <template v-slot:content>
        <text class="text-black">用户信息</text>
      </template>
    </cu-custom>
    <view class="padding">
      <uni-forms ref="userForm" :model="user" :rules="rules">
        <view class="cu-form-group padding" style="justify-content: center;">
          <view class="bg-img">
            <image :src="user.avatar" class="cu-avatar round xl logo-xxl" mode="aspectFill"
                   @tap="chooseImage"></image>
          </view>
        </view>
        <uni-forms-item class="text-bold text-black" label="姓名" name="name">
          <uni-easyinput type="text" v-model="user.name" placeholder="请输入姓名" :clearable="false"/>
        </uni-forms-item>
        <uni-forms-item class="text-bold text-black" label="邮箱" name="email">
          <uni-easyinput type="text" v-model="user.email" placeholder="请输入邮箱" :clearable="false"/>
        </uni-forms-item>
        <uni-forms-item class="text-bold text-black" label="手机" name="mobile">
          <uni-easyinput type="text" v-model="user.mobile" placeholder="请输入手机" :clearable="false"/>
        </uni-forms-item>
        <uni-forms-item class="text-bold text-black" label="性别" name="sex">
          <uni-data-select :clear="false"
                           v-model="user.sex"
                           :localdata="range"
                           @change="change"
          ></uni-data-select>
        </uni-forms-item>
        <view class="margin-top text-center">
          <button class="cu-btn bg-zblue border lg margin-top" style="width: 100%;" @tap="save">保存</button>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script setup lang="ts">
import CuCustom from '@/colorui/components/cu-custom.vue'
import UserApi from '@/api/UserApi';
import type User from '@/mode/User';
import {reactive, ref} from "vue";
import {useUserStore} from "@/store/userStore";
import Auth from '@/api/Auth';
import FetchRequest from '@/api/FetchRequest';
import UniForms from "@/uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import UniFormsItem from "@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import UniEasyinput from "@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import UniDataSelect from "@/uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import MessageUtils from "@/utils/MessageUtils";
import VimConfig from "@/config/VimConfig";

const fontValue=ref(Auth.getfontSize());

const userForm = ref();
const range = [
  {value: "0", text: "男"},
  {value: "1", text: "女"},
  {value: "2", text: "未知"},
]

const rules = {
  name: {
    rules: [{
      required: true,
      errorMessage: '请输入姓名',
    },
      {
        minLength: 2,
        maxLength: 10,
        errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符',
      }
    ]
  },
  // 对email字段进行必填验证
  email: {
    rules: [{
      format: 'email',
      errorMessage: '请输入正确的邮箱地址',
    },
      {
        minLength: 3,
        maxLength: 64,
        errorMessage: '邮箱地址长度在 {minLength} 到 {maxLength} 个字符',
      }]
  },
  // 对mobile字段进行必填验证
  mobile: {
    rules: [{
      validateFunction: function (rule: string, value: string, data: string, callback: Function) {
        // const pattern =/^1[3456789]\d{9}$/
        // if (!pattern.test(value)) {
        //   callback('手机号格式不对')
        // }
		if(value.length<6){
			callback('手机号格式不对')
		}
        return true
      }
    }]
  },
  sex: {
    rules: [{
      required: true,
      errorMessage: '请选择性别',
    }]
  }
}
const userStore = useUserStore();
const user = reactive<User>({
  id: "",
  name: "",
  mobile: "",
  email: "",
  avatar: "",
  deptId: "",
  sex: "",
  canAddFriend: false,
});

const change = (e: string) => {
  user.sex = e
}

UserApi.currentUser()
    .then(res => {
	  console.log('currentUser',res.data)
      user.id = res.data.id;
      user.name = res.data.name;
      user.deptId = res.data.deptId;
      user.mobile = res.data.mobile;
      user.email = res.data.email;
      user.avatar = res.data.avatar === "" ? null : res.data.avatar;
      user.sex = res.data.sex;
    })

const chooseImage = (e: any) => {
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: (res) => {

      uni.uploadFile({
        url: `${FetchRequest.getHost()}/${VimConfig.uploadType}/upload`, //仅为示例，非真实的接口地址
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          "Access-Control-Allow-Origin": "*",
          "Authorization": "Bearer " + Auth.getToken(),
        },
        formData: {
          'type': 'image'
        },
        success: (res) => {
          user.avatar = JSON.parse(res.data).url
        },
        fail: () => {
          MessageUtils.message('上传失败')
        },
      });
    }
  });
}

const save = () => {
  userForm.value.validate().then(() => {
    UserApi.update(user.id, user)
        .then(() => {
          return UserApi.getUser(user.id);
        })
        .then((res) => {
          userStore.setUser(res.data);
          MessageUtils.message('操作成功')
        });
  }).catch((err: any) => {
    console.log('表单错误信息：', err);
  })

}
</script>

<style scoped>
.bg-img {
  display: flex;
  justify-content: center;

}

.avatar {
  display: inline-block;
  background-color: antiquewhite;
  width: 100px;
  height: 100px;
}
</style>
