<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%;">
        <!-- 期望岗位 -->
        <template #positionId="{ item }">
          <v-menu :close-delay="1" :open-delay="0" v-bind="$attrs">
            <template v-slot:activator="{  props }">
              <textUI
                :modelValue="item.value"
                :item="item"
                v-bind="props"
                style="position: relative;"
              ></textUI>
            </template>
            <jobTypeCard class="jobTypeCardBox" :select="[query.positionId].filter(Boolean)" :isSingle="true" @handleJobClick="handleJobClickItem"></jobTypeCard>
          </v-menu>
        </template>
        <!-- 期望行业 -->
        <template #industryIdList="{ item }">
          <v-menu :close-delay="1" :open-delay="0" v-bind="$attrs" :close-on-content-click="false">
            <template v-slot:activator="{  props }">
              <textUI
                v-model="item.value"
                :item="item"
                v-bind="props"
              >
                <template #default>
                  <v-chip v-for="k in currentSelect" :key="k.id" class="mr-1" closable @click:close="handleIndustryClear(k)">{{ k.nameCn }}</v-chip>
                </template>
              </textUI>
            </template>
            <industryTypeCard :select="query.industryIdList" :currentData="currentSelect" showSelect @handleClickIndustry="handleIndustry"></industryTypeCard>
          </v-menu>
        </template>
        <!-- 其它感兴趣的城市 -->
        <template #interestedAreaIdList="{ item }">
          <v-menu :close-delay="1" :open-delay="0" v-bind="$attrs" :close-on-content-click="false">
            <template v-slot:activator="{  props }">
              <TextInput
                v-model="item.value"
                :item="item"
                v-bind="props"
                style="position: relative;"
              >
                <template #default>
                  <v-chip v-for="k in areaSelect" :key="k.id" class="mr-1" closable @click:close="handleAreaClear(k)">{{ k.name }}</v-chip>
                </template>
              </TextInput>
            </template>
            <AreaSelect :select="query.interestedAreaIdList" :currentData="areaSelect" :limit="false" showSelect @handleClick="handleArea"></AreaSelect>
          </v-menu>
        </template>
      </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 textUI from '@/components/FormUI/TextInput'
import jobTypeCard from '@/components/jobTypeCard'
import industryTypeCard from '@/components/industryTypeCard'
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'
import { cityToProvince } from '@/utils/areaDeal'
const emit = defineEmits(['complete'])

const isAdd = ref(false)
const formPageRef = ref()
const editId = ref(null)
let query = reactive({})
const items = ref({
  options: [
    {
      slotName: 'positionId',
      key: 'positionId',
      value: '',
      col: 6,
      label: '期望岗位 *',
      flexStyle: 'mr-3',
      valueKey: 'position', 
      hideDetails: true,
      outlined: true,
      rules: [v => !!v || '请选择期望岗位']
    },
    {
      slotName: 'industryIdList',
      key: 'industryIdList',
      value: '',
      outlined: true,
      placeholder: '期望行业 *',
      col: 6,
      // rules: [v => !!v || '请选择期望行业']
    },
    {
      type: 'number',
      key: 'payFrom',
      value: null,
      label: '期望薪资（最低要求） *',
      col: 4,
      suffix: '元',
      outlined: true,
      rules: [v => !!v || '请输入薪资最低要求']
    },
    {
      type: 'number',
      key: 'payTo',
      value: null,
      label: '期望薪资（最高要求） *',
      col: 4,
      suffix: '元',
      outlined: true,
      flexStyle: 'mx-3',
      rules: [v => !!v || '请输入薪资最高要求']
    },
    {
      type: 'autocomplete',
      key: 'jobType',
      value: null,
      label: '求职类型 *',
      outlined: true,
      itemText: 'label',
      col: 4,
      itemValue: 'value',
      rules: [v => !!v || '请选择求职类型'],
      items: [
        { label: '全职', value: '0' },
        { label: '兼职', value: '1' },
        { label: '临时', value: '2' },
        { label: '实习', value: '3' }
      ]
    },
    {
      type: 'autocomplete',
      key: 'workAreaProvinceId',
      value: null,
      label: '工作城市：省 *',
      outlined: true,
      itemText: 'name',
      itemValue: 'id',
      returnSelect: true,
      col: 6,
      flexStyle: 'mr-3',
      rules: [v => !!v || '请选择工作城市：省'],
      items: [],
      change: null
    },
    {
      type: 'autocomplete',
      key: 'workAreaId',
      value: null,
      label: '工作城市：市 *',
      outlined: true,
      itemText: 'name',
      itemValue: 'id',
      col: 6,
      rules: [v => !!v || '请选择工作城市：市'],
      items: [],
      change: null
    },
    {
      slotName: 'interestedAreaIdList',
      key: 'interestedAreaIdList',
      value: '',
      placeholder: '其它感兴趣的城市'
      // label: '其它感兴趣的城市'
    }
  ]
})

const provinceChange = (value, val, obj) => {
  const item = items.value.options.find(e => e.key === 'workAreaId')
  if (!item) return
  item.items = obj.children || []
  item.value = null
}
getDict('areaTreeData', null, 'areaTreeData').then(({ data }) => {
  data = data?.length && data || []
  if (!data?.length) return console.error('areaTreeData获取失败！')
  //
  // const china = data.find(e => e.id === '1')
  // const chinaTreeData = china?.children?.length ? china.children : []
  const chinaTreeData = data
  //
  if (!chinaTreeData?.length) return console.error('chinaTreeData获取失败！')
  const item = items.value.options.find(e => e.key === 'workAreaProvinceId')
  if (item?.items) {
    item.items = chinaTreeData
    item.change = provinceChange
  }
})

// 获取求职意向
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 setValue = (key, value) => {
  items.value.options.find(e => e.key === key).value = value
}

// 期望职位
const handleJobClickItem = (list, name) => {
  if (!list.length) return
  query.positionId = list[0]
  setValue('positionId', name)
}

// 行业类型
let currentSelect = reactive([])
const handleIndustry = (list, arr) => {
  if (!list.length) return setValue('industryIdList', '')
  query.industryIdList = list
  currentSelect = arr
  // const str = arr.map(e => e.nameCn).join('、')
  // setValue('industryIdList', str)
}

const handleIndustryClear = (k) => {
  query.industryIdList = query.industryIdList.filter(i => i !== k.id)
  const index = currentSelect.findIndex(i => i.id === k.id)
  if (index !== -1) currentSelect.splice(index, 1)
  console.log(k, 'industry', query.industryIdList, currentSelect)
}

// 其它感兴趣的城市
let areaSelect = reactive([])
const handleArea = (list, arr) => {
  if (!list.length) return setValue('interestedAreaIdList', '')
  query.interestedAreaIdList = list
  areaSelect = arr
}
const handleAreaClear = (k) => {
  query.interestedAreaIdList = query.interestedAreaIdList.filter(i => i !== k.id)
  const index = areaSelect.findIndex(i => i.id === k.id)
  if (index !== -1) areaSelect.splice(index, 1)
}

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

const arr = ['payFrom', 'payTo', 'jobType', 'workAreaId']
const handleSave = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return
  items.value.options.forEach(e => {
    if (arr.includes(e.key)) query[e.key] = e.value 
  })
  if (!query.industryIdList || !query.industryIdList.length) return Snackbar.warning('请选择您的期望行业')
  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
  let workAreaId = ''
  items.value.options.forEach(e => {
    query[e.key] = item[e.key] 
    if (e.valueKey) {
      e.value = item[e.valueKey]
    } else e.value = item[e.key]
    if (e.key === 'industryIdList') e.value = null
    if (e.key === 'interestedAreaIdList') {
      e.value = null
      query.interestedAreaIdList = item.interestedAreaIdList && item.interestedAreaIdList.length ? item.interestedAreaIdList : []
    }
    if (e.key === 'workAreaId' && item[e.key]) workAreaId = item[e.key]
  })
  if (workAreaId) { // 省份回显
    const province = items.value.options.find(pv => pv.key === 'workAreaProvinceId')
    if (province) {
      const dealReturnObj = await cityToProvince(workAreaId, {}, province.items || [])
      const city = items.value.options.find(pv => pv.key === 'workAreaId')
      if (city) city.items = dealReturnObj.cityList || []
      province.value = dealReturnObj.pid || ''
    }
  }
  currentSelect = item.industry
  areaSelect = item.interestedArea && item.interestedArea.length ? item.interestedArea : []
  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: 200px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.line {
  color: #e0e0e0;
  margin: 0 10px;
}
</style>
