<template>
  <div class="task-change" :class="{'ibps-fixed-toolbar':checkMode}">
    <van-nav-bar
      :title="generateTitle($route.name,$route.params.title||$route.meta.title)"
      :left-text="$t('common.button.back')"
      :right-text="rightText"
      left-arrow
      fixed
      @click-left="$router.push({ name: 'dashboard' })"
      @click-right="toCheckMode()"
    />
    <van-search
      v-model="subject"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <!-- <template #left>
        <van-icon name="bars" :class="{'ibps-active':$utils.isNotEmpty(typeId)}"  class="ibps-pr-5" @click="clickType" />
      </template> -->
      <template #action>
        <van-icon name="filter-o" :class="{'ibps-active':stateActive}" @click="clickMoreSearch" />
      </template>
    </van-search>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" @load="loadData">
        <van-cell
          v-for="(item,index) in listData"
          :key="item.id+index"
          class="ibps-p-0"
        >
          <van-swipe-cell :right-width="65">
            <van-checkbox-group v-model="checkedIds">
              <van-cell
                :title="item.taskName"
                :label="item.taskSubject"
                @click="onClick(item,index)"
              >
                <template slot="icon">
                  <van-checkbox
                    v-if="checkMode"
                    ref="checkboxes"
                    :name="item"
                    class="ibps-mr-10"
                  />
                  <ibps-avatar
                    v-else
                    :icon="_randomIcon(index)"
                    :text="item.taskName"
                    :bg-color="_randomColor(index)"
                    radius="4"
                    icon-prefix="ibps-icon"
                    class="ibps-mr-10"
                  />
                </template>
                <span>{{ item.createTime|formatRelativeTime }}</span>
                <div>
                  <!-- <van-tag :type="item.status | optionsFilter(bpmnStatusOptions,'type')">{{ item.status | optionsFilter(bpmnStatusOptions) }}</van-tag> -->
                  <van-tag
                    size="medium"
                    :color="item.status | optionsFilter(bpmnStatusOptions,'type') | optionsFilter(colorOptions,'color','type')"
                    :text-color="item.status | optionsFilter(bpmnStatusOptions,'type') | optionsFilter(colorOptions,'textColor','type')"
                  >
                    {{ item.status| optionsFilter(bpmnStatusOptions) }}</van-tag>
                </div>
              </van-cell>
            </van-checkbox-group>
            <van-button
              slot="right"
              type="danger"
              :text="$t('common.button.revoke')"
              class="ibps-swipe-button"
              @click.stop="onRevoke(item)"
            />
          </van-swipe-cell>
        </van-cell>
      </van-list>
      <ibps-list-result-page
        :result-type="resultType"
        :error-type="errorType"
        :result-message="resultMessage"
      />
    </van-pull-refresh>
    <ibps-toolbar
      v-show="checkMode"
      :actions="mainActions"
    />
    <!-- <ibps-type-tree
      v-model="typeTreePopup"
      title="流程分类"
      category-key="FLOW_TYPE"
      @node-click="clickTypeNode"
      @close="visible => typeTreePopup = visible"
    /> -->
  </div>
</template>
<script>
import { queryPageList, setStatus } from '@/api/platform/bpmn/bpmTaskChange'
import ActionUtils from '@/utils/action'

import random from '@/mixins/random'
import bpmnStatus from '@/mixins/bpmnStatus'
import i18n from '@/utils/i18n'

// import IbpsMoreSearch from '@/components/ibps-more-search'
// import IbpsTypeTree from '@/business/platform/cat/type/tree'
import IbpsAvatar from '@/components/ibps-avatar'
import IbpsListResultPage from '@/components/ibps-list-result-page'
import IbpsToolbar from '@/components/ibps-toolbar'

export default {
  components: {
    // IbpsTypeTree,
    // IbpsMoreSearch
    IbpsAvatar,
    IbpsListResultPage,
    IbpsToolbar
  },
  mixins: [random, bpmnStatus],
  data() {
    return {
      stateActive: false,
      typeTreePopup: false,
      subject: '',
      moreParams: {},

      listData: [],
      pagination: {},
      sorts: {},

      loading: false,
      finished: false,
      refreshing: false,
      resultType: 'init',
      errorType: null,
      resultMessage: null,

      checkMode: false,
      checkedIds: [],
      checkedStatuss: [],
      mainActions: [{
        'name': this.$t('common.button.revoke'),
        'type': 'danger',
        'callback': this.onRevoke
      }]
    }
  },
  computed: {
    rightText() {
      return this.checkMode ? this.$t('common.button.cancel') : this.$t('common.button.manage')
    }
  },
  methods: {
    /**
     * 加载数据
     */
    loadData() {
      this.loading = true
      queryPageList(this.getSearcFormData()).then(response => {
        // 处理数据
        ActionUtils.handleListData(this, response.data)
      }).catch((e) => {
        ActionUtils.handleErrorData(this, e)
      })
    },
    /**
     * 获取格式化参数
     */
    getSearcFormData() {
      let params = {}
      if (this.$utils.isNotEmpty(this.subject)) {
        params['Q^TASK_SUBJECT_^SL'] = this.subject
      }
      if (this.$utils.isNotEmpty(this.moreParams)) {
        params = Object.assign(params, this.moreParams)
      }

      return ActionUtils.formatParams(
        params,
        this.pagination,
        this.sorts)
    },
    /**
     * 下拉刷新
     */
    onRefresh() {
      this.refreshing = true
      this.finished = false
      this.loading = true
      this.onSearch()
    },
    /**
     * 查询
     */
    onSearch() {
      this.stateActive = false
      ActionUtils.initListData(this)
      this.loadData()
    },
    /**
     * 高级查询
     */
    onMoreSearch(params) {
      if (this.$utils.isNotEmpty(this.typeId)) {
        params['Q^type_id_^SL'] = this.typeId
      }
      this.moreParams = params
      this.onSearch()
      if (this.$utils.isNotEmpty(params)) {
        this.stateActive = true
      }
    },
    /**
     * 弹窗更多查询条件
     */
    clickMoreSearch() {
      this.moreSearchPopup = true
      this.stateActive = false
    },
    /**
     * 重置表单
     */
    resetForm() {
      this.typeId = ''
    },
    clickType() {
      this.typeTreePopup = true
    },
    clickTypeNode(data) {
      this.typeId = data.id
      this.onMoreSearch({})
    },

    onClick(item, index) {
      if (this.checkMode) {
        this.$refs.checkboxes[index].toggle()
      } else {
        this.$router.push({
          name: 'taskChangeDetail',
          params: {
            id: item.id
          }
        })
      }
    },
    toCheckMode() {
      if (this.$utils.isEmpty(this.listData)) {
        return
      }
      if (this.checkMode) {
        this.show = true
        this.checkedIds = []
      }
      this.checkMode = !this.checkMode
    },
    generateTitle(name, title) { // generateTitle by vue-i18n
      return i18n.generateTitle(name, title)
    },
    onRevoke(item) {
      let checkedIds = []
      if (this.$utils.isNotEmpty(item) && this.$utils.isNotEmpty(item.id)) {
        checkedIds = [item]
      } else {
        checkedIds = this.checkedIds
        if (this.checkedIds.length === 0) {
          this.$notify({
            type: 'warning',
            message: this.$t('common.dialog.selectedRecords')
          })
          return
        }
        if (this.checkedIds.length > 1) {
          this.$notify({
            type: 'warning',
            message: this.$t('common.dialog.multipleSelected')
          })
          return
        }
      }
      if (checkedIds[0].status !== 'running') {
        this.$notify({
          type: 'danger',
          message: '该任务不是【正在运行】的任务，不能进行该操作！'
        })
        return
      }

      setStatus({ id: checkedIds[0].id, status: 'cancel' }).then(response => {
        this.$notify({
          type: 'success',
          message: this.$t('common.operate.success')
        })
        setTimeout(() => {
          this.checkMode = false
          this.onSearch()
        }, 2000)
      }).catch((e) => {
        console.log(e)
      })
    }
  }

}
</script>
