<template>
  <!-- 求职目标设置弹窗 -->
  <el-dialog
    v-model="visible"
    width="480px"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    :align-center="false"
    :style="{ marginLeft: 'auto', marginRight: '0.2rem' }"
    class="job-goal-dialog"
    @close="handleClose"
  >
    <!-- 头部区域 -->
    <div class="job-goal-dialog__header">
      <!-- 关闭按钮 -->
      <button class="job-goal-dialog__close-btn" @click="handleClose">
        <el-icon><Close /></el-icon>
      </button>
      <!-- 弹窗标题 -->
      <span class="job-goal-dialog__title">求职目标设置</span>
    </div>

    <!-- 岗位选择模块 -->
    <div class="job-goal-dialog__section">
      <div class="job-goal-dialog__label">*岗位</div>
      <JobCategorySelector
        :categoryIds="selectedCategoryIds"
        :maxSelect="3"
        :level="3"
        :allowParentSelect="false"
        :triggerStyle="selectorTriggerStyle"
        :displayStyle="selectorDisplayStyle"
        @update:categoryIds="onCategoryChange"
      />
    </div>

    <!-- 行业选择模块 -->
    <div class="job-goal-dialog__section">
      <div class="job-goal-dialog__label">*行业</div>
      <IndustrySelector
        :industryIds="selectedIndustryIds"
        :maxSelect="3"
        :level="2"
        :allowParentSelect="false"
        :triggerStyle="selectorTriggerStyle"
        :displayStyle="selectorDisplayStyle"
        @update:industryIds="onIndustryChange"
      />
    </div>

    <!-- 城市选择模块 -->
    <div class="job-goal-dialog__section">
      <div class="job-goal-dialog__label">*城市</div>
      <RegionSelector
        :regionCodes="selectedRegionCodes"
        :level="2"
        :maxSelect="3"
        :triggerStyle="selectorTriggerStyle"
        :displayStyle="selectorDisplayStyle"
        @update:regionCodes="onRegionChange"
      />
    </div>

    <!-- 工作类型选择模块 -->
    <div class="job-goal-dialog__section ">
      <div class="job-goal-dialog__label">*工作类型</div>
      <!-- 工作类型按钮组 -->
      <div class="job-goal-dialog__type-group">
        <button
          v-for="t in jobTypes"
          :key="t"
          class="job-goal-dialog__type-btn"
          :class="{ 'job-goal-dialog__type-btn--active': selectedJobType === t }"
          @click="selectedJobType = t"
        >
          {{ t }}
        </button>
      </div>
    </div>

    <!-- 保存按钮区域 -->
    <div class="job-goal-dialog__footer mt10">
      <button class="job-goal-dialog__save-btn" @click="handleSave">保存</button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { Close } from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import RegionSelector from './tools/RegionSelector.vue'
import IndustrySelector from './tools/IndustrySelector.vue'
import JobCategorySelector from './tools/JobCategorySelector.vue'

/** 组件属性：控制弹窗显示/隐藏 */
const props = defineProps<{ modelValue: boolean }>()

/** 组件事件：更新弹窗状态 */
const emit = defineEmits<{
  (e: 'update:modelValue', val: boolean): void
}>()

const store = useStore()

/** 弹窗可见状态 */
const visible = ref(props.modelValue)
/** 监听外部传入的 modelValue 同步弹窗状态 */
watch(() => props.modelValue, (v) => { visible.value = v })
/** 监听弹窗状态变化并通知父组件 */
watch(visible, (v) => { emit('update:modelValue', v) })

/** 本地编辑副本 — 打开弹窗时从 store 拷贝，保存时写回 store */
const selectedCategoryIds = ref<number[]>([])
const selectedIndustryIds = ref<number[]>([])
const selectedRegionCodes = ref<string[]>([])
const selectedJobType = ref('全职')

/** 工作类型选项列表 */
const jobTypes = ['实习', '全职']

/** 弹窗打开时从 store 同步数据到本地编辑副本 */
watch(() => props.modelValue, (v) => {
  if (v) {
    const intention = store.state.jobIntention
    selectedCategoryIds.value = [...(intention.categoryIds || [])]
    selectedIndustryIds.value = [...(intention.industryIds || [])]
    selectedRegionCodes.value = [...(intention.regionCodes || [])]
    selectedJobType.value = intention.employmentType === 1 ? '实习' : '全职'
  }
})

/** 选择器触发按钮的自定义样式，适配弹窗内布局（参考 ProfileEditDrawer 中 regionTriggerStyle） */
const selectorTriggerStyle: Record<string, string> = {
  width: '100%',
  'box-sizing': 'border-box',
  padding: '0.1rem 0.14rem',
  'font-size': '0.13rem',
  color: '#1a1a2e',
  background: '#f6f6f9',
  border: '1px solid transparent',
  'border-radius': '0.06rem',
  'max-width': 'none',
  'justify-content': 'space-between',
}

/** 选择器显示文字的自定义样式，覆盖默认 max-width: 1.6rem */
const selectorDisplayStyle: Record<string, string> = {
  'max-width': 'none',
}

/** 岗位选择变更回调 */
function onCategoryChange(ids: number[]) {
  selectedCategoryIds.value = ids
}

/** 行业选择变更回调 */
function onIndustryChange(ids: number[]) {
  selectedIndustryIds.value = ids
}

/** 地区选择变更回调 */
function onRegionChange(codes: string[]) {
  selectedRegionCodes.value = codes
}

/**
 * 保存表单数据：调用 store action 保存到后端并同步 store，然后关闭弹窗
 */
async function handleSave() {
  try {
    await store.dispatch('saveJobIntention', {
      categoryIds: [...selectedCategoryIds.value],
      industryIds: [...selectedIndustryIds.value],
      regionCodes: [...selectedRegionCodes.value],
      employmentType: selectedJobType.value === '实习' ? 1 : 0,
    })
    visible.value = false
  } catch (e) {
    console.error('保存求职意向失败', e)
  }
}

/**
 * 关闭弹窗
 */
function handleClose() {
  visible.value = false
}
</script>
