<template>
	<view class="f-straight wrapper">
    <uni-forms ref="form" :modelValue="formData" :rules="rules" validateTrigger="bind" label-width="90px">
      <uni-forms-item label="企业名称" name="enterpriseName" required>
				<uni-combox :candidates="enterpriseData" placeholder="企业名称" v-model="formData.enterpriseName" @input="handleSearchEnterprise"></uni-combox>
			</uni-forms-item>
      <uni-forms-item label="职位名称" name="positionName" required>
				<uni-combox :candidates="positionData" placeholder="职位名称" v-model="formData.positionName"></uni-combox>
			</uni-forms-item>
      <uni-forms-item label="开始时间" name="startTime" required>
				<picker mode="date" :value="formData.startTime" fields="month" :end="endDate" @change="e => formData.startTime = e.detail.value">
					<view class="uni-input ss-m-t-20">{{ formData.startTime }}</view>
				</picker>
			</uni-forms-item>
      <uni-forms-item label="结束时间" name="endTime" required>
				<view class="d-flex">
          <picker mode="date" :value="formData.endTime" :disabled="endDisabled" fields="month" :end="endDate" @change="e => formData.endTime = e.detail.value">
            <view class="uni-input ss-m-t-20" :style="{'opacity': endDisabled ? '0.5' : '1'}">{{ formData.endTime }}</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>
        </view>
			</uni-forms-item>
      <uni-forms-item label="工作内容" name="content" required>
				<uni-easyinput type="textarea" v-model="formData.content" autoHeight  placeholder="请输入内容"></uni-easyinput>
			</uni-forms-item>
    </uni-forms>
	</view>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, watch, unref } from 'vue'
import { getDict } from '@/hooks/useDictionaries.js'
import { convertYearMonthToTimestamp, timesTampChange } from '@/utils/date.js'
import { removeEmptyProperties } from "@/utils/index"
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  text: {
    type: String,
    default: ''
  },
  data: {
    type: Object,
    default: () => ({})
  }
})

let formData = ref({
  startTime: '2014-01',
  endTime: '2018-01'
})
const sofar = ref([])
const endDisabled = ref(false)
const enterpriseData = ref([])
const positionData = ref([])
const form = ref()
const date = new Date()
const endDate = date.getFullYear() + '-' + (date.getMonth() + 1) // 不可选时间
const searchData = ref({
  enterprise: [],
  position: []
})

const getInfo = (data) => {
  data.startTime = data.startTime ? timesTampChange(data.startTime, 'Y-M') : '2014-01'
  data.endTime = data.endTime ? timesTampChange(data.endTime, 'Y-M') : null
  if (!data.endTime) {
    endDisabled.value = true
    data.endTime = '2018-01'
    sofar.value = [1]
  }
  formData.value = cloneDeep(data) || {
    startTime: '2014-01',
    endTime: '2018-01'
  }
}

watch(
  () => props.data,
  (newVal) => {
    if (newVal && Object.keys(newVal)) {
      const data = removeEmptyProperties(newVal)
      getInfo(data)
    }
  },
  { immediate: true },
)

const rules = {
	enterpriseName:{
		rules: [{required: true, errorMessage: '请输入企业名称' }]
	},
	positionName:{
		rules: [{required: true, errorMessage: '请输入职位名称' }]
	},
	startTime:{
		rules: [{required: true, errorMessage: '请选择开始时间' }]
	},
  content:{
		rules: [{required: true, errorMessage: '请输入工作内容' }]
	}
}


// 企业搜索
const handleSearchEnterprise = (e) => {
  if (!e) return enterpriseData.value = []
  enterpriseSearchByName({ name: e }).then(res => {
    searchData.value.enterprise = res.data
    enterpriseData.value = res.data && res.data?.length ? res.data.map(e => e.value) : []
  })
}

let positionTreeChildrenData = []
getDict('positionTreeData', null, 'positionTreeData').then(({ data }) => {
  data = data.data?.length && data.data || []
  data.forEach(e => {
    if (e?.children?.length) positionTreeChildrenData = positionTreeChildrenData.concat(e.children)
  })
  searchData.value.position = positionTreeChildrenData
  positionData.value = positionTreeChildrenData.map(e => e.nameCn)
})

// 至今
const handleChangeSofar = (e) => {
  const value = e.detail.value.length ? e.detail.value[0] : ''
  endDisabled.value = value ? true : false
}

const submit = async () => {
  try {
    const valid = await unref(form).validate()
    // if (!valid) return { id: props.id, data: null}
    if (!formData.value.endTime && !sofar.value.length) return uni.showToast({ icon: 'none', title: '请选择工作经历的结束时间' })
    //
    const startTime = convertYearMonthToTimestamp(formData.value.startTime)
    const endTime = sofar.value.length ? null : convertYearMonthToTimestamp(formData.value.endTime)
    if (endTime && startTime > endTime) {
      uni.showToast({ icon: 'none', title: '开始时间不能大于结束时间' })
      return
    }
    return { id: props.id, data: { ...formData.value, startTime, endTime }}
  } catch (error) {
    return { text: props.text }
  }
}

defineExpose({
  id: props.id,
  submit
})


</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>