<!-- 工作经历 -->
<template>
  <view class="ss-m-x-30 ss-m-y-30">
    <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 class="f-horizon-center">
      <button v-if="editId" size="default" class="delete-button commonBtnStyle" @click="handleDelete">删 除</button>
      <button size="default" :class="{'save-button': editId, 'commonBtnStyle': editId, 'send-button': !editId}"  @click="submit">保 存</button>
    </view>
  </view>
</template>

<script setup>
import { ref, unref } from 'vue'
import { convertYearMonthToTimestamp, timesTampChange } from '@/utils/date.js'
import { enterpriseSearchByName, saveResumeWorkExp, deleteResumeWorkExp, getResumeWorkExp } from '@/api/resume.js'
import { onLoad } from '@dcloudio/uni-app'
import { cloneDeep } from 'lodash-es'
import { getDict } from '@/hooks/useDictionaries.js'

let formData = ref({
  startTime: '2014-01',
  endTime: '2018-01'
})
const sofar = ref([])
const endDisabled = ref(false)
const editId = ref(null)
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 rules = {
	enterpriseName:{
		rules: [{required: true, errorMessage: '请输入企业名称' }]
	},
	positionName:{
		rules: [{required: true, errorMessage: '请输入职位名称' }]
	},
	startTime:{
		rules: [{required: true, errorMessage: '请选择开始时间' }]
	},
  content:{
		rules: [{required: true, errorMessage: '请输入工作内容' }]
	}
}
const getExp = async (id) => {
  const { data } = await getResumeWorkExp()
  if (!data || !data.length) {
    return
  }
  const obj = data.find(e => e.id == id)
  formData.value = cloneDeep(obj)
  formData.value.startTime = timesTampChange(obj.startTime, 'Y-M')
  if (!obj.endTime) {
    endDisabled.value = true
    formData.value.endTime = '2018-01'
    sofar.value = [1]
  } else formData.value.endTime = timesTampChange(obj.endTime, 'Y-M')
  handleSearchEnterprise(obj.enterpriseName)
}

onLoad((options) => {
  if (options.id) {
    editId.value = options.id
    getExp(options.id)
  }
})

// 企业搜索
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 () => {
  const valid = await unref(form).validate()
  if (!valid) return
  formData.value.enterpriseId = searchData.value.enterprise.find(e => e.value === formData.value.enterpriseName)?.key
  formData.value.positionId = searchData.value.position.find(e => e.nameCn === formData.value.positionName)?.id

  const startTime = convertYearMonthToTimestamp(formData.value.startTime)
  const endTime = sofar.value.length ? null : convertYearMonthToTimestamp(formData.value.endTime)
  if (!endTime && !sofar.value.length) return uni.showToast({ icon: 'none', title: '请选择结束时间' })
  if (endTime && startTime > endTime) {
    uni.showToast({ icon: 'none', title: '开始时间不能大于结束时间' })
    return
  }

  try {
		await saveResumeWorkExp({ ...formData.value, startTime, endTime })
    uni.showToast({
			icon: 'success',
			title: '保存成功'
		})
		setTimeout(() => {
      editId.value = null
      uni.navigateBack({
        delta: 1
      })
    }, 1000)
  } catch (err) {
		uni.showToast({
			icon: 'none',
			title: err.msg
		})
	}
}

// 删除
const handleDelete = async () => {
	try {
		await deleteResumeWorkExp(editId.value)
		uni.showToast({
			icon: 'success',
			title: '删除成功'
		})
		setTimeout(() => {
			editId.value = null
			uni.navigateBack({
				delta: 1
			})
		}, 1000)
	} catch (err) {
		uni.showToast({
			icon: 'none',
			title: err.msg
		})
	}
}
</script>

<style lang="scss" scoped>
</style>
