<template>
	<view class="f-straight wrapper">
		<uni-forms ref="form" :modelValue="formData" :rules="rules" validateTrigger="bind" label-width="90px" label-align="right">
			<uni-forms-item label="企业LOGO" name="logoUrl" class="f-straight" required>
        <view style="display: flex;flex-wrap: wrap;">
          <view class="upload-img" v-if="formData?.logoUrl">
            <uni-icons size="35" type="clear" color="#fe574a" style="position: absolute;right: -15px; top: -15px; z-index: 9" @click="formData.logoUrl = ''"></uni-icons>
            <image :src="formData?.logoUrl" mode="contain" style="width: 200rpx;height: 200rpx;" @click="handlePreviewImage"></image>
          </view>
          <view v-else class="upload-file" @click="uploadPhotos">
            <uni-icons type="plusempty" size="50" color="#f1f1f1"></uni-icons>
          </view>
        </view>
			</uni-forms-item>
			<uni-forms-item label="企业全称" name="name" required>
        <uni-easyinput v-model="formData.name" placeholder="请输入企业全称" />
			</uni-forms-item>
      <uni-forms-item label="展示名称" name="anotherName" required>
				<uni-easyinput v-model="formData.anotherName" placeholder="请输入对外展示名称" />
			</uni-forms-item>
      <uni-forms-item label="企业官网" name="website" clearable>
        <uni-easyinput v-model="formData.website" placeholder="请输入企业官网" />
			</uni-forms-item>
      <uni-forms-item label="联系人" name="contact" clearable>
        <uni-easyinput v-model="formData.contact" placeholder="请输入联系人" />
			</uni-forms-item>
      <uni-forms-item label="联系电话" name="phone" clearable>
        <uni-easyinput v-model="formData.phone" placeholder="请输入联系电话" />
			</uni-forms-item>
      <uni-forms-item label="开业时间" name="openTime">
        <picker mode="date" :value="formData.openTime" :disabled="endDisabled" fields="month" :end="endDate" @change="e => formData.openTime = e.detail.value">
          <view class="uni-input ss-m-t-20" :style="{'opacity': endDisabled ? '0.5' : '1'}">{{ formData.openTime || '请选择开业时间' }}</view>
        </picker>
        <uni-data-checkbox selectedColor="#00B760" class="ss-m-l-50 ss-m-t-14" multiple v-model="sofar" :localdata="[{ text: '筹备中（如果贵企业正在筹备，请勾选）', value: 1 }]" @change="handleChangeSofar"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item label="所在行业" name="industryId" required>
				<uni-data-picker
          v-model="formData.industryId"
          :localdata="dictObj.industryTreeData"
          :clear-icon="false"
          popup-title="请选择所在行业"
          :clear="false"
          :map="{ text: 'nameCn', value: 'id' }"
        ></uni-data-picker>
			</uni-forms-item>
      <uni-forms-item label="企业规模" name="scale" required>
				<uni-data-picker
          v-model="formData.scale"
          :localdata="dictObj.scale"
          :clear-icon="false"
          popup-title="请选择企业规模"
          :clear="false"
          :map="{ text: 'label', value: 'value' }"
        ></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item label="企业介绍" name="introduce" required>
				<uni-easyinput v-model="formData.introduce" type="textarea" placeholder="请输入企业介绍" />
			</uni-forms-item>
			<view class="f-horizon-center">
				<button type="primary" size="default" class="send-button"  @click="submit">提 交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script setup>
import { ref, unref } from 'vue'
import { userStore } from '@/store/user'
import { dictObj } from '@/utils/position.js'
import { uploadFile } from '@/api/file'
import { timesTampChange, convertYearMonthToTimestamp } from '@/utils/date'
import { updateEnterpriseInfo, updateEnterpriseLogo, getEnterpriseInfo } from '@/api/enterprise'

const form = ref()
const useUserStore = userStore()

const sofar = ref([])
const date = new Date()
const endDate = date.getFullYear() + '-' + (date.getMonth() + 1) // 不可选时间

const formData = ref({})

// 获取企业信息
const getInfo = async () => {
  const { data } = await getEnterpriseInfo()
  formData.value = data || {
    logoUrl: '',
    name: '',
    anotherName: '',
    website: '',
    openTime: '',
    contact: '',
    phone: '',
    industryId: '',
    scale: '',
    introduce: ''
  }
  if (!data.openTime) {
    endDisabled.value = true
  }
  if (data.prepare) {
    sofar.value = [1]
  }
  formData.value.openTime = formData.value.openTime ? timesTampChange(data.openTime, 'Y-M') : null
}
getInfo()

// 筹备中
const endDisabled = ref(false)
const handleChangeSofar = (e) => {
  const value = e.detail.value.length ? e.detail.value[0] : ''
  endDisabled.value = value ? true : false
}

// 图片预览
const handlePreviewImage = () => {
  uni.previewImage({
    current: 0,
    urls: [formData.value.logoUrl]
  })
}

// 选择头像
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.logoUrl = res.data
      }).catch(error => {
        uni.showToast({
          icon: 'error',
          title: '图片上传失败!',
          duration: 2000
        })
      })
    }
  })
}

const rules = {
	logoUrl:{
		rules: [{required: true, errorMessage: '请上传企业logo' }]
	},
	name:{
		rules: [{required: true, errorMessage: '请输入企业全称' }]
	},
  introduce:{
		rules: [{required: true, errorMessage: '请输入企业介绍' }]
	},
	anotherName : {
		rules: [{required: true, errorMessage: '请选择企业对外展示名称' }]
	},
	industryId: {
		rules: [{required: true, errorMessage: '请选择企业所在行业' }]
	},
  scale: {
		rules: [{required: true, errorMessage: '请选择企业规模' }]
	}
}

const submit = async () => {
  const valid = await unref(form).validate()
  if (!valid) return
  
  formData.value.openTime = sofar.value.length ? null : formData.value.openTime ? convertYearMonthToTimestamp(formData.value.openTime) : null
  formData.value.prepare = sofar.value.length ? true : false
  
  const { logoUrl, ...rest } = formData.value
  
  await updateEnterpriseLogo(logoUrl)
  await updateEnterpriseInfo(rest)

  uni.showToast({ title: '编辑成功', icon: 'success' })
  await useUserStore.getUserInfos()
  getInfo()

  setTimeout(() => {
		uni.navigateBack({
			delta: 1
		})
	}, 1000)
}
</script>

<style lang="less" scoped>
.wrapper{
	padding: 15px;
  padding-top: 30px;
}
.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>