<template>
  <el-select v-model="selectedTaskCode" filterable :filter-method="taskDataFilter" @click.native="eqNoClick">
    <el-option
      v-for="task in searchTasks"
      :key="task.code"
      :label="task.name"
      :value="task.code"
    />
  </el-select>
</template>

<script>
import Api from '@/js/api'
import Http from '@/js/http'
import {notify} from '@/constants'
import {mapActions} from 'vuex'

export default {
  name: 'TaskSearch',
  data: function () {
    return {
      tasks: [],
      searchTasks: [],
      selectedTaskCode: ''
    }
  },
  props: {
    firstSelectedTaskCode: {
      type: String,
      default: ''
    },
    selectedProjectCode: {
      type: String,
      default: ''
    },
    selectedCallback: {
      type: Function
    }
  },
  created () {
    this.selectedTaskCode = this.firstSelectedTaskCode
    this.setRefreshTaskListFunc(this.getSimpleTaskDatas)
  },
  watch: {
    'selectedTaskCode': {
      immediate: false,
      handler: function () {
        if (this.selectedCallback) {
          this.selectedCallback(this.selectedTaskCode)
        }
      }
    }
  },
  methods: {
    ...mapActions(['setRefreshTaskListFunc']),
    taskDataFilter (val) {
      if (val) {
        this.searchTasks = this.tasks.filter(task => {
          return task.name.includes(val)
        })
      } else {
        this.searchTasks = this.tasks
      }
    },
    eqNoClick () {
      this.searchTasks = this.tasks
    },
    getSimpleTaskDatas (projectCode) {
      Http.get(Api.TASK.GET_SIMPLE_DATAS_BY_PROJECT.replace('{projectCode}', projectCode)).then((res) => {
        this.tasks = res.data
        this.searchTasks = res.data
        this.selectedTaskData = this.searchTasks.find(task => task.code === this.selectedTaskCode)
        if (!this.selectedTaskData) {
          this.selectedTaskData = this.tasks[0]
          this.selectedTaskCode = this.selectedTaskData.code
        }
      }).catch((error) => {
        notify('error', '获取任务列表数据失败：系统异常')
      })
    }
  }
}
</script>

<style scoped>

</style>
