<template>
  <div class="flx-center" style="flex-direction: column">
    <div class="container">
      <div class="title">编辑公司信息</div>
      <el-form
        ref="formRef"
        :model="state.form"
        :rules="state.rules"
        label-width="110px"
        label-position="left"
        hide-required-asterisk
        style="width: 774px"
      >
        <div class="position-info">
          <div class="position-info-title">
            <img src="@/assets/img/position.png" width="24" height="24" />
            <span>职位基本信息</span>
          </div>
          <div style="margin-left: 42px">
            <el-form-item label="公司：">
              <span>{{ userInfoStore.companyInfo?.FNAME }}</span>
            </el-form-item>
            <el-form-item label="招聘类型：" prop="FRecruitmentType">
              <el-select v-model="state.form.FRecruitmentType" placeholder="请选择招聘类型">
                <el-option label="社招" value="A" />
                <el-option label="校招" value="B" />
              </el-select>
            </el-form-item>
            <el-form-item label="招聘人数：" prop="FRecruitsNumber">
              <el-input
                v-model="state.form.FRecruitsNumber"
                type="number"
                placeholder="请输入招聘人数"
              />
            </el-form-item>
            <el-form-item label="职位名称：" prop="FName">
              <el-input v-model="state.form.FName" placeholder="请输入职位名称" />
            </el-form-item>
            <el-form-item label="职位描述：" prop="FJobDescription_Tag">
              <el-input
                v-model="state.form.FJobDescription_Tag"
                type="textarea"
                :rows="6"
                :maxlength="5000"
                show-word-limit
                placeholder="请勿填写QQ、微信、电话等联系方式及特殊符号、性别歧视词、违反劳动法相关内容，否则有可能会导致您的账号被封禁。"
              />
            </el-form-item>
            <el-form-item label="职位类型：" prop="FJobType">
              <el-cascader
                v-model="state.form.FJobType"
                :options="state.cascaderOptions"
                :props="state.cascaderProps"
                placeholder="请选择职位类型"
                @change="handleChange"
              />
            </el-form-item>
          </div>
          <div class="position-info-title" style="margin: 30px 0 5px">
            <img src="@/assets/img/position1.png" width="24" height="24" />
            <span>职位基本信息</span>
          </div>
          <div style="margin-left: 42px">
            <p>我们将通过以下条件，为您精确推荐合适的牛人，请尽量详细填写</p>
            <div class="flx-align-center">
              <el-form-item label="经验和学历 ：" style="width: 56.5%" prop="FExperience">
                <el-select v-model="state.form.FExperience" placeholder="请选择经验">
                  <el-option
                    v-for="item in state.informationData?.Experience"
                    :key="item.FNUMBER"
                    :label="item.FDATAVALUE"
                    :value="item.FNUMBER"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label=""
                class="empty-label"
                style="width: 43.5%"
                prop="FEducationalBackground"
              >
                <el-select v-model="state.form.FEducationalBackground" placeholder="请选择学历">
                  <el-option
                    v-for="item in state.informationData?.Degree2"
                    :key="item.FNUMBER"
                    :label="item.FDATAVALUE"
                    :value="item.FNUMBER"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="flx-align-center">
              <el-form-item label="薪资范围：" style="width: 56.5%" prop="FMinimumWage">
                <el-select
                  v-model="state.form.FMinimumWage"
                  placeholder="请选择最低工资"
                  @change="salaryChange"
                >
                  <el-option
                    v-for="item in state.lowSalary"
                    :key="item.FNUMBER"
                    :label="item.FDATAVALUE"
                    :value="item.FNUMBER"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="" class="empty-label" style="width: 22%" prop="FMaximumSalary">
                <el-select
                  v-model="state.form.FMaximumSalary"
                  :disabled="!state.form.FMinimumWage"
                  placeholder="请选择最高工资"
                >
                  <el-option
                    v-for="item in state.tallSalary"
                    :key="item.FNUMBER"
                    :label="item.FDATAVALUE"
                    :value="item.FNUMBER"
                  />
                </el-select>
              </el-form-item>
              <span
                style="display: inline-block; height: 30px; line-height: 20px; margin-left: 12px"
                >*</span
              >
              <el-form-item label="" class="empty-label" style="width: 19%" prop="FMonthlySalary">
                <el-select v-model="state.form.FMonthlySalary" placeholder=" ">
                  <el-option
                    v-for="item in state.informationData?.Month"
                    :key="item.FNUMBER"
                    :label="item.FDATAVALUE"
                    :value="item.FNUMBER"
                  />
                </el-select>
              </el-form-item>
            </div>

            <el-form-item label="职位关键词：" prop="FJobKeywords">
              <el-tag
                v-for="tag in state.form.FJobKeywords"
                :key="tag"
                closable
                size="large"
                :disable-transitions="false"
                style="margin: 0 12px 12px 0"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="state.inputVisible"
                ref="InputRef"
                v-model="state.inputValue"
                style="width: 14%; margin: 0 12px 12px 0"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button v-else style="margin: 0 12px 12px 0" @click="showInput">
                + 关键词
              </el-button>
            </el-form-item>
            <el-form-item label="工作地点：" prop="FWorkPlace">
              <el-input v-model="state.form.FWorkPlace" placeholder="请输入工作地点" />
            </el-form-item>
            <p style="margin-left: 110px">请填写真实有效地址，若查实造假，将受到平台处罚。</p>
          </div>
        </div>
      </el-form>
      <div class="agree">已阅读并遵守《南山就业帮职位信息发布规则》</div>
    </div>
    <div style="margin-bottom: 76px">
      <el-button style="background-color: #cccccc; color: #ffffff" @click="router.back()"
        >取消</el-button
      >
      <el-button type="primary" style="background-color: #177cfa" @click="submit"
        >保存并发布</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { getInformation } from '@/services/api/common'
import { getPosition, postPosition } from '@/services/api/recruitmentManagement'
import { useUserInfoStore } from '@/stores/modules/userInfo'
import { CascaderProps } from 'element-plus'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const state = reactive({
  form: {
    FID: 0, //新增为0
    FName: '', //岗位名称
    FDocumentStatus: 'C', //（无需填写）
    FCompany: {
      FNUMBER: ''
    }, //所属公司(无需填写)
    FEducationalBackground: '', //学历要求
    FPositionStatus: 'A', //岗位状态（无需填写）
    FJobType: '', //岗位类型
    FJobDescription: '', // 无需填写
    FJobDescription_Tag: '', // 岗位描述
    FRecruitmentType: '', //招聘类型
    FExperience: '', //经验
    FMinimumWage: '', //最低薪资
    FMaximumSalary: '', //最高薪资
    FWorkPlace: '', //工作地址
    FJobKeywords: [], //职位关键词
    FRecruitsNumber: null, //招聘人数
    FMonthlySalary: '', //月薪数
    FPublisher: '' //发布人（无需填写）
  } as any,
  rules: {
    FName: [{ required: true, message: '请输入职位描述', trigger: 'blur' }],
    FJobDescription_Tag: [{ required: true, message: '请输入职位描述', trigger: 'blur' }],
    FEducationalBackground: [{ required: true, message: '请选择学历要求', trigger: 'change' }],
    FJobType: [{ required: true, message: '请选择职位类型', trigger: 'change' }],
    FRecruitmentType: [{ required: true, message: '请选择招聘类型', trigger: 'change' }],
    FExperience: [{ required: true, message: '请选择经验', trigger: 'change' }],
    FMinimumWage: [{ required: true, message: '请选择最低薪资', trigger: 'change' }],
    FMaximumSalary: [{ required: true, message: '请选择最高薪资', trigger: 'change' }],
    FWorkPlace: [{ required: true, message: '请输入工作地址', trigger: 'blur' }],
    FJobKeywords: [{ required: true, message: '请输入职位关键词', trigger: 'blur' }],
    FRecruitsNumber: [{ required: true, message: '请输入招聘人数', trigger: 'blur' }],
    FMonthlySalary: [{ required: true, message: '请选择月薪数', trigger: 'change' }]
  },
  inputValue: '',
  inputVisible: false,
  cascaderProps: {
    children: 'JobS',
    label: 'FDATAVALUE',
    value: 'FNUMBER'
  } as CascaderProps,
  cascaderOptions: [],
  informationData: {} as any,
  lowSalary: [] as any,
  tallSalary: [] as any
})
let initTallSalary: any = []

const formRef = ref()
const InputRef = ref()

const handleChange = (value: any) => {
  console.log(value, 'dsada')
}

// 控制工资范围
const salaryChange = (Val: string) => {
  // 低工资
  const row = state.informationData?.Salary.find((item: any) => item.FNUMBER === Val)
  // 高工资
  const tallRow = state.informationData?.Salary.find(
    (item: any) => item.FNUMBER === state.form.FMaximumSalary
  )
  state.tallSalary = initTallSalary?.filter(
    (item: any) => Number(item.FDESCRIPTION) > Number(row.FDESCRIPTION) || item.FNUMBER === '~'
  )
  if (tallRow?.FDESCRIPTION === '不限' || !tallRow) return
  if (row) {
    if (!tallRow || Number(tallRow.FDESCRIPTION) <= Number(row.FDESCRIPTION)) {
      const index = state.informationData.Salary.findIndex((item: any) => item.FNUMBER === Val)
      state.form.FMaximumSalary = state.informationData?.Salary[index + 1].FNUMBER
    }
  }
}

const handleClose = (tag: string) => {
  state.form.FJobKeywords.splice(state.form.FJobKeywords.indexOf(tag), 1)
}

const showInput = () => {
  state.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (state.inputValue) {
    state.form.FJobKeywords.push(state.inputValue)
  }
  state.inputVisible = false
  state.inputValue = ''
}

const handleResult = () => {
  let data = {
    Type: 0,
    Parmeter: {
      NeedUpDateFields: [
        'FName',
        'FDocumentStatus',
        'FEducationalBackground',
        'FCompany',
        'FJobType',
        'FJobDescription',
        'FJobDescription_Tag',
        'FRecruitmentType',
        'FExperience',
        'FMinimumWage',
        'FMaximumSalary',
        'FWorkPlace',
        'FJobKeywords',
        'FRecruitsNumber',
        'FMonthlySalary'
      ],
      Model: {
        FID: 0,
        FName: '',
        FDocumentStatus: '',
        FCompany: { FNUMBER: '' },
        FSubjectRecruit: { FNUMBER: '' },
        FEducationalBackground: { FNumber: '' },
        FPositionStatus: '',
        FJobType: { FNumber: '' },
        FJobDescription: '',
        FJobDescription_Tag: '',
        FRecruitmentType: '',
        FExperience: { FNumber: '' },
        FMinimumWage: { FNumber: '' },
        FMaximumSalary: { FNumber: '' },
        FWorkPlace: '',
        FJobKeywords: '',
        FRecruitsNumber: 0,
        FMonthlySalary: { FNumber: '' },
        FPublisher: ''
      }
    }
  }
  const { form } = state
  data.Parmeter.Model = { ...data.Parmeter.Model, ...form }
  const { Model } = data.Parmeter

  Model.FJobType = { FNumber: form.FJobType.slice(-1)[0] }
  Model.FEducationalBackground = { FNumber: form.FEducationalBackground }
  Model.FExperience = { FNumber: form.FExperience }
  Model.FMonthlySalary = { FNumber: form.FMonthlySalary }
  Model.FMinimumWage = { FNumber: form.FMinimumWage }
  Model.FMaximumSalary = { FNumber: form.FMaximumSalary === '~' ? '' : form.FMaximumSalary }
  Model.FJobKeywords = form.FJobKeywords.join(',')
  console.log(data)

  return data
}

const submit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      ElMessageBox.confirm('确定保存并发布?', '保存发布', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const data = handleResult()
          const res: any = await postPosition(data)
          if (res.code === 200) {
            ElNotification.success({ title: '发布职位', message: res.msg })
            router.back()
          }
        })
        .catch(() => {})
    }
  })
}

const init = async () => {
  const res: any = await getPosition()
  if (res.code === 200) {
    state.cascaderOptions = res.data.LevelJobS
  }
  const info: any = await getInformation({
    AuxiliaryS: ['Experience', 'Month', 'Salary', 'Degree2']
  })
  if (info.code === 200) {
    state.informationData = info.data
    state.lowSalary = info.data?.Salary.slice(0, info.data?.Salary.length - 1)
    info.data?.Salary.push({
      FDATAVALUE: '不限',
      FDESCRIPTION: '不限',
      FNUMBER: '~'
    })
    initTallSalary = info.data?.Salary
  }
}

init()
</script>

<style lang="scss" scoped>
@import url(./style/editPosition.scss);
</style>
