<template>
  <view class="pd20">
    <steps-component :current="0"/>
    <view class="cell-box">
      <uni-section title="宠物基本信息" type="line">
        <view class="example">
          <!-- 基础表单校验 -->
          <uni-forms ref="valForm" :rules="rules" :modelValue="formData" label-width="100px">
            <uni-forms-item label="姓名" required name="name">
              <uni-easyinput v-model="formData.name" placeholder="请输入姓名" :inputBorder="false"/>
            </uni-forms-item>
            <uni-forms-item label="性别" required name="gender">
              <uni-data-checkbox selectedColor="#FFBF60" v-model="formData.gender" :localdata="actions"/>
            </uni-forms-item>
            <uni-forms-item label="年龄" required name="age">
              <uni-easyinput v-model="formData.age" placeholder="请输入年龄" :inputBorder="false"/>
            </uni-forms-item>
            <uni-forms-item label="养宠经验" name="feedingAge">
              <uni-easyinput type="number" v-model="formData.feedingAge" placeholder="请输入养宠经验"
                             :inputBorder="false">
                <template #right>
                  <view>年</view>
                </template>
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="宠物类型" name="petType" required>
              <uni-data-checkbox selectedColor="#FFBF60" multiple v-model="formData.petType"
                                 :localdata="typeData"></uni-data-checkbox>
            </uni-forms-item>
          </uni-forms>
        </view>
      </uni-section>

      <view class="personal-pet-info-title border-bottom ">
        <view class="mb20">爱宠图片</view>
        <view class="font24" style="color: #999999">请上传3~6张个人所养宠物的照片，并保证和上面选择的宠物相同</view>
      </view>
      <uni-file-picker v-model="fileList" @select="successUpload" limit="6" title="最多选择6张图片"
                       :image-styles="imageStyles"></uni-file-picker>
    </view>
  </view>
  <submitBut text="下一步" @click="handleClick"></submitBut>

  <!-- 客服组件 -->
  <CustomerService />
</template>

<script setup>
import {ref} from "vue";
import StepsComponent from "../../../components/stepsComponent/index.vue"
import submitBut from "../../../components/submitBut/index.vue"
import modal from "@/plugins/modal";
import {saveBaseInfo} from "../../../api/work/work";
import {getStorage, setStorage} from "../../../utils/auth";
import {getPersonalInfo} from "../../../api/system/user";
import tab from "../../../plugins/tab";

const current = ref(1)
const valForm = ref()
const fileList = ref([])
const model = ref({})
const actions = ref([
  {text: '男', value: 1},
  {text: '女', value: 2}
])
const typeData = ref(
    [
      {value: '1', text: "猫咪"},
      {value: '2', text: "狗狗"},
      {value: '3', text: "异宠"}
    ]
)
const imageStyles = ref({
  width: 100,
  height: 100,
})
const formData = ref({})
const rules = ref({
  name: {rules: [{required: true, errorMessage: '姓名不能为空'}]},
  gender: {rules: [{required: true, errorMessage: '请选择宠物性别'}]},
  age: {rules: [{required: true, errorMessage: '请输入宠物年龄'}]},
  feedingAge: {rules: [{required: true, errorMessage: '请输入养宠经验'}]},
  petType: {rules: [{required: true, errorMessage: '请输选择宠物类型'}]},
})
const initForm = () => {
  let userInfo = getStorage('userInfo')
  formData.value = {
    id: userInfo.id,
    name: userInfo.name,
    gender: userInfo.gender > 0 ? userInfo.gender : null,
    age: userInfo.age,
    feedingAge: userInfo.feedingAge,
    petType: userInfo.petType ? userInfo.petType.split(',') : []
  }
  console.log(formData.value);
  fileList.value = userInfo.petImages ? userInfo.petImages : []
}
initForm()
// 下一步
const handleClick = async () => {
  valForm.value.validate().then(async () => {
    if (fileList.value.length <= 0) {
      modal.msgError("请上传宠物照片")
      return
    }
    await saveBaseInfo({
      ...formData.value,
      petImages: fileList.value,
      petType: formData.value.petType.join(',')
    })
    getUserInfo()
  }).catch(err => {
    console.log(err);
  })
}
const getUserInfo = async () => {
  const {data} = await getPersonalInfo()
  setStorage('userInfo', data)
  tab.navigateTo("/otherPages/workbenchManage/examNotice/index")
}
// 新增图片
const successUpload = async (event) => {
  console.log(event);
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.tempFiles)
  let fileListLen = fileList.value.length
  lists.map((item) => {
    fileList.value.push({
      ...item
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url)
    let item = fileList.value[fileListLen]
    fileList.value.splice(fileListLen, 1, Object.assign(item, {
      status: 'success',
      message: '',
      url: result
    }))
    fileListLen++
  }
}
const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://store-test.catmdogd.com/test-api/h5/oss/upload', // 仅为示例，非真实的接口地址
      filePath: url,
      name: 'file',
      formData: {
        user: 'test'
      },
      success: (res) => {
        setTimeout(() => {
          if (res && res.data) {
            let resData = JSON.parse(res.data);
            resolve(resData.url);
          }
          reject("上传失败");
        }, 1000)
      }
    });
  })
}

</script>

<style scoped lang="scss">
@import "index";

</style>