<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务类型" prop="task_type">
        <el-select
          v-model="queryParams.task_type"
          placeholder="请选择类型"
          clearable
          class="!w-200px"
          @change="handleQuery"
        >
          <el-option v-for="(val, index) in taskType" :label="val.label" :value="val.value" :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="task_status">
        <el-select
          v-model="queryParams.task_status"
          placeholder="请选择状态"
          clearable
          class="!w-200px"
          @change="handleQuery"
        >
          <el-option v-for="(val, index) in ['待解析', '部分解析成功', '解析成功', '解析失败']" :label="val" :value="val" :key="index" />
        </el-select>
      </el-form-item>
      <div class="text-center mb-12px">
        <el-button @click="handleQuery"><Icon icon="ep:search" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </div>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="text-right mb-10px">
      <el-button type="primary" plain @click="handleAdd">
        <Icon icon="ep:plus" class="mr-5px" /> 新增人才
      </el-button>
    </div>
    <el-table v-loading="loading" :data="list" :stripe="true">
      <el-table-column label="任务ID" align="center" prop="id" />
      <el-table-column label="任务名称" align="center" prop="task_name" />
      <el-table-column label="任务类型" align="center" prop="task_type" />
      <el-table-column label="任务状态" align="center" prop="task_status">
        <template #default="{ row }">
          <el-tag :type="statusObj[row.task_status]">{{ row.task_status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="created_at" :formatter="dateFormatter" />
      <el-table-column label="更新时间" align="center" prop="updated_at" :formatter="dateFormatter" />
      <el-table-column label="操作" align="center" fixed="right" min-width="110">
        <template #default="scope">
          <el-button
            v-if="['待解析'].includes(scope.row.task_status)"
            link
            type="success"
            @click="handleAnalysis(scope.row)"
          >
            解析
          </el-button>
          <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.per_page"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 选择来源 -->
  <Dialog title="新增" v-model="openSelect" width="550" @close="openSelect = false">
		<el-radio-group v-model="radioValue" size="large" class="radioBox">
			<el-radio
				v-for="item in radioList"
				:key="item.value"
				:value="item.value"
			>
				{{ item.label }}
			</el-radio>
		</el-radio-group>
    <template #footer>
      <el-button type="primary" @click="handleSelect">确 认</el-button>
      <el-button @click="openSelect = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 解析文件上传 -->
  <Dialog :title="radioObject[radioValue]" v-model="dialog_upload" :modalClose="false" :width="DialogWidth" @close="handleCancel">
    <div>
      <!-- 简历解析 -->
      <template v-if="radioValue === 'file'">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :action="uploadUrl"
          :auto-upload="false"
          :data="fileData"
          :before-upload="beforeUpload"
          :on-change="handleChange"
          :on-error="submitFormError"
          :on-exceed="handleExceed"
          :http-request="httpRequest"
          :accept="fileUploadType"
          drag
          :limit="fileUploadLimit"
          multiple
          class="flex-1"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">仅允许导入{{ fileUploadType }}格式文件！ 将文件拖到此处，或 <em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip color-red">
              提示：最多可上传{{ fileUploadLimit }}份简历（{{ fileList.length }}/{{ fileUploadLimit }}）
            </div>
          </template>
        </el-upload>
      </template>
      <!-- 名片解析 -->
      <template v-if="radioValue === 'card'">
        <UploadImgs
          v-model="cardImgUrl"
          :limit="cardUploadLimit"
          :autoUpload="false"
          @handle-change="cardUploadChange"
          height="150px" width="150px" style="margin: 20px auto; text-align: center;"
        >
          <template #tip>{{ cardUploadRow?.length ? `${cardUploadRow.length}/${cardUploadLimit}` : `请上传名片（最多可上传${cardUploadLimit}张）` }}</template>
        </UploadImgs>
      </template>
      <!-- 杂项 -->
      <template v-if="radioValue === 'picture'">
        <div class="flex align-center">
          <UploadImg
            v-model="cardImgUrl"
            :autoUpload="false"
            @handle-change="val => cardUploadChange(val, '杂项')"
            height="150px" width="150px" style="margin: 20px auto; text-align: center;"
          >
            <template #tip>{{ cardImgUrl ? '' : '请上传图片' }}</template>
          </UploadImg>
        </div>
      </template>
      <!-- 网页解析 -->
      <template v-if="radioValue === 'web'">
        <webAnalysis
          @analysis="handleWebAnalysis"
          @reset="webOriginList = []"
        />
      </template>
      <!-- 门墩儿招聘 -->
      <template v-if="radioValue === 'menduner'">
        <Search ref="SearchRef" @submit="handleSubmit" />
      </template>
    </div>
    <template #footer>
      <el-button v-if="radioValue !== 'menduner'" @click="handleSubmit" type="success" :disabled="analysisLoading" :loading="analysisLoading">提 交</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </template>
  </Dialog>

  <TaskDetail ref="TaskDetailRef" @analysis="val => handleAnalysis(val, true)" />
</template>

<script setup>
defineOptions({ name: 'TalentMapStoreIndex' })
import { dateFormatter } from '@/utils/formatTime'
import Search from './components/search.vue'
import webAnalysis from './components/webAnalysis.vue'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import Info from '@/views/menduner/system/person/details/components/info.vue'
import expExtend from '@/views/menduner/system/person/details/components/expExtend.vue'
import Attachment from '@/views/menduner/system/person/details/components/attachment.vue'
import { ElLoading } from 'element-plus'
import { talentGatherApi } from '@/api/menduner/system/talentMap/gather'
import TaskDetail from './components/detail.vue'

const { uploadUrl, httpRequest } = useUpload()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const cardUploadLimit = 5
const fileUploadLimit = 3
const fileUploadType = '.pdf'
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  page: 1,
  per_page: 10,
  task_type: undefined, // 任务类型
  task_status: undefined // 任务状态
})
const queryFormRef = ref() // 搜索的表单
const dialog_upload = ref(false)
const taskType = [
  { label: '名片', value: '名片' },
  { label: '简历', value: '简历' },
  { label: '门墩儿新任命', value: '新任命' },
  { label: '门墩儿招聘', value: '招聘' },
  { label: '杂项', value: '杂项' }
]
const statusObj = {
  '待解析': 'primary',
  '部分解析成功': 'warning',
  '解析成功': 'success',
  '解析失败': 'danger'
}
const itemData = ref({})

const SearchRef = ref(null)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    list.value = []
    const data = await talentGatherApi.getTaskList(queryParams)
    list.value = data.tasks ?? []
    total.value = data.pagination.total ?? 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 网页解析-信息提取
const webOriginList = ref([])
const handleWebAnalysis = (list) => {
  webOriginList.value = list ?? []
}

// 任务详情
const TaskDetailRef = ref(null)
const handleDetail = (row) => {
  TaskDetailRef.value.open(row)
}

// 任务解析
const handleAnalysis = async (row, noTip = false) => {
  if (!noTip) await message.confirm('是否确认解析当前任务？')

  const loading = ElLoading.service({
    lock: true,
    text: '任务解析中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    await talentGatherApi.taskAnalysis({ data: row })
    message.success('解析成功')
  } finally {
    loading.close()
    handleQuery()
  }
}

// 关闭上传弹窗
const handleCancel = () => {
  dialog_upload.value = false
  analysisLoading.value = false
  cardUploadRow.value = []
  fileList.value = []
}

// 创建任务
const handleCreateTask = async (query) => {
  try {
    await talentGatherApi.createTask(query)
    message.success('任务创建成功')
    handleQuery()
  } finally {
    analysisLoading.value = false
    webOriginList.value = []
    handleCancel()
  }
}

// 新任命
const handleCreateWebTask = async () => {
  if (!webOriginList.value || !webOriginList.value?.length) return message.warning('请输入新任命链接抓取网页信息后再进行提交')

  analysisLoading.value = true

  const formData = new FormData()
  formData.append('task_type', '新任命')
  webOriginList.value.forEach(e => {
    formData.append('files', e.file)
    formData.append('publish_time', e.publish_time)
  })

  handleCreateTask(formData)
}

// 任务创建
const analysisLoading = ref(false)
const handleSubmit = async () => {
  const type = radioValue.value
  // 新任命
  if (type === 'web') return handleCreateWebTask()

  // 杂项、名片、简历
  if (['card', 'file', 'picture'].includes(type)) {
    const currentList = type === 'file' ? fileList.value : cardUploadRow.value
    if (!currentList || !currentList?.length) {
      message.warning(`请上传${type === 'file' ? '简历' : type === 'card' ? '名片' : '杂项'}`)
      return
    }
    analysisLoading.value = true

    const formData = new FormData()
    formData.append('task_type', type === 'file' ? '简历' : type === 'card' ? '名片' : '杂项')
    currentList.forEach(e => {
      formData.append('files', e.raw)
    })
    handleCreateTask(formData)
  }
  
  // 门墩儿招聘
  if (type === 'menduner') {
    const formData = new FormData()
    const list = SearchRef.value?.addList?.length ? SearchRef.value.addList : null
    if (!list) return message.warning('请先选择人员 ！')

    formData.append('task_type', '招聘')
    formData.append('data', JSON.stringify(list))
    handleCreateTask(formData)
  }
}

// 简历解析
const uploadRef = ref()
const fileList = ref([])
const fileData = ref({ path: '' })
// 文件上传
const handleChange = async (file) => {
  fileData.value.path = file.name
  // unref(uploadRef)?.submit()
}

const beforeUpload = (file) => {
  let fileExtension = ''
  if (file.name.lastIndexOf('.') > -1) {
    fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
  }
  const isImg = [fileUploadType.split('.')[1]].some((type) => {
    if (file.type.indexOf(type) > -1) return true
    return !!(fileExtension && fileExtension.indexOf(type) > -1)
  })
  if (!isImg) {
    message.error(`文件格式不正确, 请上传${fileUploadType}格式!`)
    return false
  }
}
const submitFormError = () => {
  message.error('上传失败，请您重新上传！')
}
const handleExceed = () => {
  message.error(`最多只能上传${fileUploadLimit}个文件！`)
}

// 名片解析 
const cardUploadRow = ref([])
const cardImgUrl = ref(null)
const cardUploadChange = (file, type) => {
  cardUploadRow.value = type ? [{ raw: file }] : file
}

// 选择解析方式
const DialogWidth = ref('500')
const handleSelect = () => {
  openSelect.value = false
  itemData.value = {}
  DialogWidth.value = '500'
  
	const type = radioValue.value
  if (['card', 'web'].includes(type)) {
    DialogWidth.value = '800'
  }
  if (type === 'menduner') {
    DialogWidth.value = '1200'
  }
  dialog_upload.value = true
}

const openSelect = ref(false)
const radioObject = { card: '名片', file: '简历', web: '门墩儿新任命', menduner: '门墩儿招聘', picture: '杂项' }
const radioList = ref(Object.keys(radioObject).map(key => ({ value: key, label: radioObject[key]}) ))
const defaultValue = radioList.value[0].value // 默认选中
const radioValue = ref(defaultValue)
// 新增解析
const handleAdd = () => {
  webOriginList.value = []
  cardUploadRow.value = []
  cardImgUrl.value = null
  analysisLoading.value = false
  radioValue.value = defaultValue // 重置解析类型
  openSelect.value = true
}

/** 初始化 **/
onMounted(() => {
  getList()
})

</script>

<style lang="scss" scoped>
.radioBox {
	margin: 40px 0;
}
:deep {
  .el-tag__content {
    display: flex;
    align-items: center;
  }
}
</style>