<template>
  <scroll-view class="scrollBox" scroll-y="true">
    <view class="content">
      <uni-forms
        ref="infoRef"
        v-model="formData"
        :rules="formRules"
        validateTrigger="bind"
        label-width="86px"
        labelAlign="right"
      >
        <uni-forms-item name="enterpriseId" label="实习企业" required>
          <uni-data-picker v-model="formData.enterpriseId" :localdata="companyList" :clear-icon="false" popup-title="请选择实习企业" :clear="false" :map="{ text: 'enterpriseName', value: 'id' }"></uni-data-picker>
        </uni-forms-item>
        <uni-forms-item label="实习报告" name="report" class="f-straight">
          <view style="display: flex;flex-wrap: wrap;">
            <view v-for="(img, index) of reportList" :key="index">
              <view class="upload-img" v-if="img">
                <uni-icons size="35" type="clear" color="#fe574a" style="position: absolute;right: -15px; top: -15px; z-index: 9" @click="delReport(index)"></uni-icons>
                <image :src="img" mode="contain" style="width: 200rpx;height: 200rpx;" @click="handlePreviewImage(index)"></image>
              </view>
            </view>
            <view v-if="reportList?.length < 9" class="upload-file" @click="uploadPhotos">
              <uni-icons type="plusempty" size="50" color="#f1f1f1"></uni-icons>
            </view>
          </view>
        </uni-forms-item>
        <view class="uploadTip text-center">*请上传实习报告图片（最多可上传9张图片）</view>
        <view class="uploadTip text-center">*只支持JPG、JPEG、PNG类型的图片</view>
      </uni-forms>
    </view>
    <view class="bottom-sticky">
      <button type="primary" size="default" class="recomm-button" @click="submit">确认</button>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, unref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { uploadFile } from '@/api/file'
import { saveStudentReport } from '@/api/student.js'

const companyList = ref([])
onLoad((options) => {
  if (options.companyList) {
    companyList.value = JSON.parse(options.companyList)
  }
})

const formData = ref({
  enterpriseId: null,
})
const formRules = {
  enterpriseId: {
		rules: [{required: true, errorMessage: '请选择实习企业' }]
	},
}

const infoRef = ref()
const submit = async () => {
  const validate = await unref(infoRef).validate()
  if (!validate) return uni.showToast({ title: '请选择企业', icon: 'none' })
  if (!reportList.value?.length) return uni.showToast({ title: '请上传实习报告', icon: 'none' })
  try {
    await saveStudentReport({
      ...formData.value,
      urlList: reportList.value
    })
    uni.showToast({ title: '保存成功', icon: 'none' })
    setTimeout(() => {
      uni.navigateBack({
        delta: 1
      })
    }, 500)
  } catch (err) {
    uni.showToast({ title: err?.msg || '保存失败', icon: 'none' })
  }
}

const reportList = ref([])
const delReport = (index) => {
  reportList.value.splice(index, 1)
}

// 图片预览
const handlePreviewImage = (index) => {
  uni.previewImage({
    current: 0,
    urls: [reportList.value[index]]
  })
}
// 上传
const uploadPhotos = () => {
  wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: function(res){
      const size = res.tempFiles[0]?.size || 0
      if (size >= 31457280) {
        uni.showToast({
          icon: 'none',
          title: '头像上传大小不得超过 20MB !',
          duration: 2000
        })
        return
      }
      const path = res.tempFilePaths[0]
      uploadFile(path, 'img').then(res => {
        formData.value.avatar = res.data
        reportList.value.push(res.data)
      }).catch(error => {
        uni.showToast({
          icon: 'error',
          title: '图片上传失败!',
          duration: 2000
        })
      })
    }
  })
}

</script>

<style lang="scss" scoped>
.img{
  width: 28%;
  height: 200rpx;
  margin: 10rpx;
  border: 1px solid #f4f4f4;
}
.wrapper{
  height: 84vh;
  overflow: auto;
}
:deep(.uni-section .uni-section-header__decoration) {
  background-color: #00B760 !important;
}
.line {
  border-top: 1px solid #ccc;
}
.picker {
  flex: 1;
  overflow: hidden;
  margin-right: 12px;
}
.content {
  padding: 20rpx;
  padding-bottom: 50rpx;
  .uploadTip {
    color: #00B760;
    margin-bottom: 20px;
    font-size: 13px;
  }
}
.upload-img{
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border: 1px solid #f1f1f1;
  margin: 10rpx;
}
.upload-file{
  width: 200rpx;
  height: 200rpx;
  border: 1px solid #f1f1f1;
  margin: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10rpx;
}
</style>
