<template>
  <div class="resume-box elevation-2 mb-3" id="jobIntention">
    <div class="resume-header mb-3">
      <div class="resume-title">{{ $t('resume.jobIntention') }}</div>
      <v-btn v-if="!isAdd" variant="text" color="primary" prepend-icon="mdi-plus-box" @click="isAdd = true">{{ $t('common.add') }}</v-btn>
    </div>
    <div v-if="!isAdd">
      <div v-if="interestList.length">
        <div
          :class="['position-item', 'mx-n2', 'px-2']" 
          v-for="(k, i) in interestList" 
          :key="i" 
          @mouseenter="k.active = true" 
          @mouseleave="k.active = false"
        >
          <div class="d-flex">
            <div>{{ k.position }}</div>
            <div class="line">|</div>
            <div v-if="!k.payFrom && !k.payTo">面议</div>
            <div v-else>{{k.payFrom ? k.payFrom + '-' : ''}}{{k.payTo}}</div>
            <div class="line">|</div>
            <div class="grey-text text-box">{{ k.industry && k.industry?.length ? k.industry.map(e => e.nameCn).join('、') : '' }}</div>
            <div class="line" v-if="k.industry?.length && k.jobTypeName">|</div>
            <div class="grey-text">{{ k.jobTypeName }}</div>
            <div class="line" v-if="k.jobTypeName && k.workArea">|</div>
            <div class="grey-text ellipsis" style="max-width: 160px;">
              {{ k.interestedArea && k.interestedArea.length ? k.workArea + '，' + k.interestedArea.map(e => e.name).join('，') : k.workArea }}
            </div>
          </div>
          <div class="float-right" v-if="k.active">
            <v-btn variant="text" color="primary" prepend-icon="mdi-square-edit-outline" @click="handleEdit(k)">{{ $t('common.edit') }}</v-btn>
            <v-btn variant="text" color="primary" prepend-icon="mdi-trash-can-outline" @click="handleDelete(k)">{{ $t('common.delete') }}</v-btn>
          </div>
        </div>
      </div>
      <div v-else class="resumeNoDataText">{{ $t('resume.dataDefaultPrompt') }}{{ $t('resume.jobIntention') }}...</div>
    </div>
    <div v-if="isAdd" class="mt-2">
      <CtForm ref="formPageRef" :items="items" style="width: 100%;"></CtForm>
      <div class="text-end">
        <v-btn class="half-button mr-3" variant="tonal" @click="isAdd = false; resetForm()">{{ $t('common.cancel') }}</v-btn>
        <v-btn color="primary" class="half-button" @click="handleSave">{{ $t('common.save') }}</v-btn>
      </div>
    </div>
  </div>
</template>

<script setup name="jobIntention">
import { ref, reactive } from 'vue'
import CtForm from '@/components/CtForm'
import Snackbar from '@/plugins/snackbar'
import Confirm from '@/plugins/confirm'
import { saveResumeJobInterested, getResumeJobInterested, deleteResumeJobInterested } from '@/api/recruit/personal/resume'
import { dealJobData } from './dict'
import { getDict } from '@/hooks/web/useDictionaries'
const emit = defineEmits(['complete'])

const isAdd = ref(false)
const formPageRef = ref()
const editId = ref(null)
let query = reactive({})
const items = ref({
  options: [
    {
      type: 'cascade',
      key: 'positionId',
      value: null,
      default: null,
      label: '期望岗位',
      itemText: 'nameCn',
      itemValue: 'id',
      required: true,
      clearable: false,
      col: 6,
      flexStyle: 'mr-3',
      rules: [v => !!v || '请选择期望岗位'],
      items: [],
    },
    {
      type: 'cascade',
      key: 'industryIdList',
      value: [],
      default: [],
      label: '期望行业',
      itemText: 'nameCn',
      itemValue: 'id',
      required: true,
      collapseTags: true,
      clearable: false,
      multiple: true,
      col: 6,
      rules: [v => !!v || '请选择期望行业'],
      items: [],
    },
    {
      type: 'number',
      key: 'payFrom',
      value: '',
      col: 6,
      label: '最低薪资 *',
      flexStyle: 'mr-3',
      suffix: '元',
      rules: [
        value => {
          if (value) return true
          return '请填写最低薪资'
        },
        value => {
          if (value >= 1) return true
          return '数额不得小于1'
        },
        value => {
          const payTo = items.value.options.find(e => e.key === 'payTo').value
          if (!payTo || (Number(value) < payTo ? Number(payTo) : 0)) return true
          return '应低于最高薪资'
        }
      ]
    },
    {
      type: 'number',
      key: 'payTo',
      value: '',
      col: 6,
      label: '最高薪资 *',
      suffix: '元',
      rules: [
        value => {
          if (value) return true
          return '请填写最高薪资'
        },
        value => {
          if (value >= 1) return true
          return '数额不得小于1'
        },
        value => {
          const payFrom = items.value.options.find(e => e.key === 'payFrom').value
          if (!payFrom || (Number(value) > payFrom ? Number(payFrom) : 0)) return true
          return '应高于最低薪资'
        }
      ]
    },
    {
      type: 'autocomplete',
      key: 'jobType',
      value: null,
      label: '求职类型 *',
      outlined: true,
      itemText: 'label',
      col: 6,
      flexStyle: 'mr-3',
      itemValue: 'value',
      rules: [v => !!v || '请选择求职类型'],
      items: []
    },
    {
      type: 'cascade',
      key: 'workAreaId',
      value: null,
      default: null,
      label: '期望城市',
      itemText: 'name',
      itemValue: 'id',
      required: true,
      clearable: false,
      checkStrictly: true,
      col: 6,
      items: [],
    },
    {
      type: 'cascade',
      key: 'interestedAreaIdList',
      value: [],
      label: '其它感兴趣的城市',
      itemText: 'name',
      itemValue: 'id',
      collapseTags: true,
      checkStrictly: true,
      clearable: false,
      multiple: true,
      items: []
    }
  ]
})

// 期望城市、其它感兴趣的城市
getDict('areaTreeData', null, 'areaTreeData').then(({ data }) => {
  data = data?.length && data || []
  items.value.options.find(e => e.key === 'workAreaId').items = data
  items.value.options.find(e => e.key === 'interestedAreaIdList').items = data
})

// 求职类型
getDict('menduner_job_type').then(({ data }) => {
  data = data?.length && data || []
  items.value.options.find(e => e.key === 'jobType').items = data
})
// 岗位tree
getDict('positionTreeData', null, 'positionTreeData').then(({ data }) => {
  data = data?.length && data || []
  items.value.options.find(e => e.key === 'positionId').items = data
})

// 期望行业
getDict('industryTreeData', null, 'industryTreeData').then(({ data }) => {
  data = data?.length && data || []
  items.value.options.find(e => e.key === 'industryIdList').items = data
})

// 获取求职意向
const interestList = ref([])
const getJobInterested = async () => {
  const data = await getResumeJobInterested()
  // 完成度展示
  emit('complete', { status: Boolean(data?.length), id: 'jobIntention' })
  if (!data.length) {
    interestList.value = []
    return
  }
  interestList.value = dealJobData(data)
}
getJobInterested()

const resetForm = () => {
  items.value.options.forEach(e => {
    if (e.key === 'industryIdList') e.value = []
    else e.value = null
  })
  editId.value = null
  query = {}
}

const handleSave = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return
  items.value.options.forEach(e => {
    query[e.key] = e.value 
  })
  if (editId.value) query.id = editId.value
  await saveResumeJobInterested(query)
  Snackbar.success('保存成功')
  isAdd.value = false
  resetForm()
  getJobInterested()
}

const handleEdit = async (item) => {
  editId.value = item.id
  items.value.options.forEach(e => {
    query[e.key] = item[e.key] 
    e.value = item[e.key]
    if (e.key === 'interestedAreaIdList') {
      e.value = item[e.key] && item[e.key].length ? item[e.key].map(e => Number(e)) : []
    }
  })
  isAdd.value = true
}

const handleDelete = ({ id }) => {
  Confirm('系统提示', '是否确认删除此项求职意向？').then(async () => {
    await deleteResumeJobInterested(id)
    Snackbar.success('删除成功！')
    getJobInterested()
  })
}
</script>

<style scoped lang="scss">
.jobTypeCardBox {
  position: absolute;
  top: -22px;
  left: 0;
}
.position-item {
  display: flex;
  justify-content: space-between;
  cursor: pointer;
  border-radius: 6px;
  line-height: 40px;
  font-size: 15px;
  &:hover {
    background-color: var(--color-f8);
  }
  span {
    font-size: 15px;
  }
  .grey-text {
    color: var(--color-999);
  }
}
.text-box {
  max-width: 300px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.line {
  color: #e0e0e0;
  margin: 0 10px;
}
</style>
