<template>
  <div class="position-create-container">
    <div class="header-container">
      <page-header title="新增职位" @back="goBack" />
    <!--   <div class="header-right">应用至人力资源-对外</div> -->
    </div>
    
    <el-card class="form-card">
      <div class="section-title">
        <div class="section-line"></div>
        <span>职位详情</span>
      </div>
      
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="职位名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入职位名称" maxlength="20" show-word-limit />
        </el-form-item>
        
        <el-form-item label="职位类别" prop="job_category">
          <el-select v-model="formData.job_category" placeholder="请选择职位类别">
            <el-option label="技术" value="技术" />
            <el-option label="产品" value="产品" />
            <el-option label="设计" value="设计" />
            <el-option label="运营" value="运营" />
            <el-option label="市场" value="市场" />
            <el-option label="销售" value="销售" />
            <el-option label="行政" value="行政" />
            <el-option label="财务" value="财务" />
            <el-option label="人力资源" value="人力资源" />
            <el-option label="法务" value="法务" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="职位性质" prop="job_type_display">
          <el-select v-model="formData.job_type_display" placeholder="请选择职位性质">
            <el-option label="全职" value="全职" />
            <el-option label="兼职" value="兼职" />
            <el-option label="实习" value="实习" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
       <!--  <el-form-item label="工作城市" prop="city">
          <el-select v-model="formData.city" placeholder="请选择工作城市">
            <el-option label="北京" value="北京" />
            <el-option label="上海" value="上海" />
            <el-option label="广州" value="广州" />
            <el-option label="深圳" value="深圳" />
            <el-option label="杭州" value="杭州" />
            <el-option label="成都" value="成都" />
            <el-option label="武汉" value="武汉" />
            <el-option label="西安" value="西安" />
            <el-option label="南京" value="南京" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item> -->
        
        <el-form-item label="工作地点" prop="location">
          <el-cascader
            v-model="formData.location"
            :options="locationOptions"
            :props="{ 
              expandTrigger: 'hover',
              checkStrictly: false
            }"
            style="width: 100%"
            placeholder="请选择工作地点"
            clearable
            @change="handleLocationChange"
          />
        </el-form-item>
        
        <el-form-item label="门牌号码" prop="address_detail">
          <el-input v-model="formData.address_detail" placeholder="请输入详细地址" />
        </el-form-item>
        
        <el-form-item label="福利待遇" prop="benefits">
          <el-select v-model="formData.benefits" placeholder="请选择福利待遇" multiple>
            <el-option label="五险一金" value="五险一金" />
            <el-option label="年终奖" value="年终奖" />
            <el-option label="带薪年假" value="带薪年假" />
            <el-option label="定期体检" value="定期体检" />
            <el-option label="节日福利" value="节日福利" />
            <el-option label="员工旅游" value="员工旅游" />
            <el-option label="弹性工作" value="弹性工作" />
            <el-option label="免费班车" value="免费班车" />
            <el-option label="餐补" value="餐补" />
            <el-option label="交通补贴" value="交通补贴" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="职位要求" prop="requirements">
          <div class="editor-container">
            <div ref="quillEditor" class="quill-editor"></div>
          </div>
        </el-form-item>
        
        <!-- 添加职位描述字段 -->
        <el-form-item label="职位描述" prop="description">
          <div class="editor-container">
            <div ref="descriptionEditor" class="quill-editor"></div>
          </div>
        </el-form-item>
        
        <!-- 添加职位薪资字段 -->
        <el-form-item label="职位薪资" prop="salary_range">
          <div class="salary-range-container">
            <el-select v-model="formData.salary_type" placeholder="薪资类型" class="salary-type-select">
              <el-option label="月薪" value="月薪" />
              <el-option label="年薪" value="年薪" />
              <el-option label="日薪" value="日薪" />
              <el-option label="时薪" value="时薪" />
            </el-select>
            <el-input v-model="formData.start_salary" placeholder="起始薪资" class="salary-input" />
            <span class="salary-separator">-</span>
            <el-input v-model="formData.end_salary" placeholder="最高薪资" class="salary-input" />
          </div>
        </el-form-item>
        
        <!-- 添加职位条件字段 -->
        <el-form-item label="职位条件">
          <div class="job-conditions-container">
            <el-select v-model="formData.work_experience_required" placeholder="工作经验" class="condition-select">
              <el-option label="不限" value="不限" />
              <el-option label="应届毕业生" value="应届毕业生" />
              <el-option label="1年以下" value="1年以下" />
              <el-option label="1-3年" value="1-3年" />
              <el-option label="3-5年" value="3-5年" />
              <el-option label="5-10年" value="5-10年" />
              <el-option label="10年以上" value="10年以上" />
            </el-select>
            <el-select v-model="formData.education_required" placeholder="学历要求" class="condition-select">
              <el-option label="不限" value="不限" />
              <el-option label="高中" value="高中" />
              <el-option label="大专" value="大专" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </div>
        </el-form-item>
        
        <el-form-item label="胜任力标签" prop="competency_tags">
          <el-select
            v-model="formData.competency_tags"
            multiple
            placeholder="请选择胜任力标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in competencyTags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="formData.department" placeholder="请输入所属部门" />
        </el-form-item>
        
        <el-form-item label="职位状态" prop="job_type">
          <el-select v-model="formData.job_type" placeholder="请选择职位状态">
            <el-option label="未发布" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已结束" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="截止日期" prop="end_date">
          <el-date-picker
            v-model="formData.end_date"
            type="datetime"
            placeholder="请选择截止日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as api from '../list/api';
import type { FormInstance } from 'element-plus';
import Quill from 'quill';
import 'quill/dist/quill.snow.css'; // 引入样式
import axios from 'axios';

const router = useRouter();
const formRef = ref<FormInstance>();

// 添加胜任力标签接口定义
interface CompetencyTag {
  id: number;
  name: string;
  description: string;
}

// 在 PositionFormData 接口中添加胜任力字段
interface PositionFormData {
  title: string;
  job_category: string;
  job_type_display: string;
  city: string;
  location: string[];
  address_detail: string;
  benefits: string[];
  requirements: string;
  job_type?: number;
  salary_type: string;
  start_salary: string;
  end_salary: string;
  work_experience_required: string;
  education_required: string;
  salary_range?: string;
  department?: string;
  end_date?: string;
  description?: string;
  province: string;
  district: string;
  location_str?: string;
  status: number;
  competency_tags: number[]; // 存储选中的胜任力标签ID
}

// 表单数据
const formData = reactive<PositionFormData>({
  title: '',
  job_category: '',
  job_type_display: '',
  city: '',
  location: [],
  address_detail: '',
  benefits: [],
  requirements: '',
  job_type: 0,
  salary_type: '月薪',
  start_salary: '',
  end_salary: '',
  work_experience_required: '',
  education_required: '',
  salary_range: '',
  department: '',
  end_date: '',
  description: '',
  province: '',
  district: '',
  location_str: '',
  status: 0,
  competency_tags: [],
});

// 表单验证规则
const rules = {
  title: [{ required: true, message: '职位名称必填', trigger: 'blur' }],
  job_category: [{ required: true, message: '职位类别必填', trigger: 'change' }],
  job_type_display: [{ required: true, message: '职位性质必填', trigger: 'change' }],
  location: [{ required: true, message: '工作地点必填', trigger: 'change' }],
  department: [{ required: true, message: '所属部门必填', trigger: 'blur' }],
  job_type: [{ required: true, message: '职位状态必填', trigger: 'change' }],
  end_date: [{ required: true, message: '截止日期必填', trigger: 'change' }],
  requirements: [{ required: true, message: '职位要求必填', trigger: 'blur' }],
  description: [{ required: true, message: '职位描述必填', trigger: 'blur' }],
  salary_range: [{ required: true, message: '薪资范围必填', trigger: 'blur' }],
  competency_tags: [
    { required: true, message: '请选择胜任力标签', trigger: 'change' }
  ],
};

// 添加对描述编辑器的引用
const quillEditor = ref<HTMLElement | null>(null);
const descriptionEditor = ref<HTMLElement | null>(null);
let editor: any = null;
let descEditor: any = null;

// 工作地点选项
const locationOptions = [
  {
    value: '上海市',
    label: '上海市',
    children: [
      {
        value: '浦东新区',
        label: '浦东新区',
        children: [
          { value: '张江', label: '张江' },
          { value: '金桥', label: '金桥' },
          { value: '陆家嘴', label: '陆家嘴' }
        ]
      },
      {
        value: '徐汇区',
        label: '徐汇区',
        children: [
          { value: '漕河泾', label: '漕河泾' },
          { value: '徐家汇', label: '徐家汇' }
        ]
      },
    ]
  },
  {
    value: '北京市',
    label: '北京市',
    children: [
      {
        value: '海淀区',
        label: '海淀区',
        children: [
          { value: '中关村', label: '中关村' },
          { value: '上地', label: '上地' }
        ]
      },
      {
        value: '朝阳区',
        label: '朝阳区',
        children: [
          { value: 'CBD', label: 'CBD' },
          { value: '望京', label: '望京' }
        ]
      },
    ]
  },
];

// 处理地点选择变化
const handleLocationChange = (value: any) => {
  console.log('地址选择变化:', value);
  if (value && Array.isArray(value) && value.length > 0) {
    formData.province = value[0];
    formData.city = value[1] || '';
    formData.district = value[2] || '';
  }
};

// 在 setup 中添加胜任力相关的响应式数据
const competencyTags = ref<CompetencyTag[]>([]);
const competencyDescriptions = ref<Record<number, string>>({});

// 添加获取胜任力标签的方法
const fetchCompetencyTags = async () => {
  try {
      const response = await api.GetCompetencyList({page:1,pageSize:1000});
    console.log('response', response);
    competencyTags.value = response.data.items;
    // 构建描述映射
   /*  competencyTags.value.forEach(tag => {
      competencyDescriptions.value[tag.id] = tag.description;
    }); */
  } catch (error) {
    console.error('获取胜任力标签失败:', error);
    ElMessage.error('获取胜任力标签失败');
  }
};

onMounted(() => {
  // 初始化职位要求编辑器
  if (quillEditor.value) {
    editor = new Quill(quillEditor.value, {
      theme: 'snow',
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean']
        ]
      },
      placeholder: '请输入职位要求'
    });
    
    // 设置初始内容
    if (formData.requirements) {
      editor.clipboard.dangerouslyPasteHTML(formData.requirements);
    }
    
    // 监听内容变化
    editor.on('text-change', () => {
      formData.requirements = editor.root.innerHTML;
    });
  }
  
  // 初始化职位描述编辑器
  if (descriptionEditor.value) {
    descEditor = new Quill(descriptionEditor.value, {
      theme: 'snow',
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean']
        ]
      },
      placeholder: '请输入职位描述'
    });
    
    // 设置初始内容
    if (formData.description) {
      descEditor.clipboard.dangerouslyPasteHTML(formData.description);
    }
    
    // 监听内容变化
    descEditor.on('text-change', () => {
      formData.description = descEditor.root.innerHTML;
    });
  }
  
  // 在 onMounted 中调用获取胜任力标签
  fetchCompetencyTags();
});

onBeforeUnmount(() => {
  editor = null;
  descEditor = null;
});

// 返回列表页
const goBack = () => {
  router.push('/position/list');
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  // 确保获取最新内容
  if (editor) {
    formData.requirements = editor.root.innerHTML;
  }
  
  if (descEditor) {
    formData.description = descEditor.root.innerHTML;
  }
  
  // 在验证前设置薪资范围
  if (formData.salary_type && formData.start_salary && formData.end_salary) {
    formData.salary_range = `${formData.salary_type} ${formData.start_salary}-${formData.end_salary}`;
  }
  
  await formRef.value.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      try {
        const formToSubmit = { ...formData };
        
        // 处理地址信息
        if (Array.isArray(formToSubmit.location) && formToSubmit.location.length > 0) {
          formToSubmit.province = formToSubmit.location[0];
          formToSubmit.city = formToSubmit.location[1] || '';
          formToSubmit.district = formToSubmit.location[2] || '';
          // 使用location_str字段存储字符串形式的位置
          formToSubmit.location_str = formToSubmit.location.join(' ');
        }
        
        // 处理胜任力标签数据
        const apiData = {
          ...formToSubmit,
          competency_tags: formToSubmit.competency_tags,
          // ... other fields
        };
        
        const response = await api.AddObj(apiData);
        ElMessage.success('职位添加成功');
        router.push(`/position/detail?id=${response.data.id}`);
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败，请重试');
      }
    } else {
      console.log('验证失败:', fields);
    }
  });
};
</script>

<style scoped>
.position-create-container {
  padding: 20px;
}

.form-card {
  margin: 0 auto;
  margin-top: 20px;
  width: 40%;

}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-weight: bold;
  color: #333;
}

.section-line {
  width: 4px;
  height: 16px;
  background-color: #67C23A;
  margin-right: 8px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.editor-toolbar {
  display: flex;
  padding: 8px;
  border-bottom: 1px solid #dcdfe6;
  background-color: #f5f7fa;
}

.toolbar-btn {
  margin-right: 5px;
  padding: 4px 8px;
  background: none;
  border: none;
  cursor: pointer;
  border-radius: 3px;
}

.toolbar-btn:hover {
  background-color: #e6e6e6;
}

.toolbar-btn.active {
  background-color: #ffecd1;
}

.toolbar-select {
  margin-right: 5px;
  padding: 4px;
  border: 1px solid #dcdfe6;
  border-radius: 3px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  color: #909399;
  font-size: 14px;
}

.editable-content {
  min-height: 200px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-top: none;
  overflow-y: auto;
  background-color: #fff;
}

.quill-editor {
  height: 300px;
}

.salary-range-container {
  display: flex;
  align-items: center;
}

.salary-type-select {
  width: 100px;
  margin-right: 10px;
}

.salary-input {
  width: 120px;
}

.salary-separator {
  margin: 0 10px;
}

.job-conditions-container {
  display: flex;
  gap: 20px;
}

.condition-select {
  width: 200px;
}
</style> 