<template>
  <div class="new-process">
    <van-sticky>
      <van-nav-bar
        :title="generateTitle($route.name,$route.params.title||$route.meta.title)"
        :left-text="$t('common.button.back')"
        left-arrow
        @click-left="$router.push({ name: 'dashboard' })"
      />

      <van-tabs v-model="tabActive" color="#3396FB" @click="onClickTab">
        <van-tab
          v-for="data in tabDatas"
          :key="data.name"
          :name="data.name"
          :title="data.title"
        />
      </van-tabs>
      <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-sticky>

    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        @load="loadData"
      >
        <van-swipe-cell
          v-for="(item,index) in listData"
          :key="item.id+index"
          :right-width="65"
        >
          <van-cell
            :key="item.id+index"
            :title="item.name"
            :value="item.createTime|formatRelativeTime"
            :label="item.desc"
            @click="onClick(item,index)"
          >
            <template slot="icon">
              <ibps-avatar
                :icon="_randomIcon(index)"
                :text="item.name"
                :bg-color="_randomColor(index)"
                width="24"
                height="24"
                radius="8"
                icon-prefix="new-process_size ibps-icon"
                class="ibps-mr-10"
              />
            </template>
            <div v-if="tabActive===1">
              <div>{{ item.createTime|formatRelativeTime }}</div>
              <!-- <van-tag plain :type="item.favorites | optionsFilter(bpmnStatusOptions,'type')">{{ item.favorites | optionsFilter(bpmnStatusOptions) }}</van-tag> -->
              <van-tag
                size="medium"
                :color="item.favorites | optionsFilter(bpmnStatusOptions,'type') | optionsFilter(colorOptions,'color','type')"
                :text-color="item.favorites | optionsFilter(bpmnStatusOptions,'type') | optionsFilter(colorOptions,'textColor','type')"
              >
                {{ item.favorites| optionsFilter(bpmnStatusOptions) }}</van-tag>
            </div>
          </van-cell>

          <van-button
            slot="right"
            :name="item.favorites?'star-o':'star'"
            :type="item.favorites?'danger':'info'"
            :text="item.favorites?'取消':'收藏'"
            class="ibps-swipe-button"
            @click="onFavorites(item.defId,item.favorites)"
          />

        </van-swipe-cell>
        <ibps-list-result-page
          :result-type="resultType"
          :error-type="errorType"
          :result-message="resultMessage"
        />
      </van-list>
    </van-pull-refresh>

    <!-- <ibps-more-search
      :show="moreSearchPopup"
      :search-forms="searchForms"
      @callback="onMoreSearch"
      @close="callback => moreSearchPopup = callback"
      @reset-form="resetForm"
    /> -->

    <ibps-type-tree
      v-model="typeTreePopup"
      title="流程分类"
      category-key="FLOW_TYPE"
      @node-click="clickTypeNode"
      @close="visible => typeTreePopup = visible"
    />
    <ibps-bpmn-formrender-dialog
      :visible="formrenderVisible"
      :title="formrenderTitle"
      :def-id="defId"
      @close="visible => formrenderVisible = visible"
    />
  </div>
</template>
<script>
import { newProcess, favorited, saveFavorites, removeFavorites } from '@/api/platform/office/bpmInitiated'

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

// import IbpsMoreSearch from '@/components/ibps-more-search'
import IbpsAvatar from '@/components/ibps-avatar'
import IbpsListResultPage from '@/components/ibps-list-result-page'
import IbpsTypeTree from '@/business/platform/cat/type/tree'
import IbpsBpmnFormrenderDialog from '@/business/platform/bpmn/form/dialog'

export default {
  name: 'new-process',
  components: {
    // IbpsMoreSearch,
    IbpsTypeTree,
    IbpsAvatar,
    IbpsListResultPage,
    IbpsBpmnFormrenderDialog
  },
  mixins: [random, bpmnStatus],
  data() {
    return {
      tabActive: 0,
      tabDatas: [{
        name: 0,
        title: '收藏的流程'
      }, {
        name: 1,
        title: '发布的流程'
      }],
      stateActive: false,
      moreSearchPopup: false,
      typeTreePopup: false,
      searchForms: {
        forms: [
          { prop: 'Q^name_^SL', label: '流程名称', fieldType: 'text' }
        ]
      },
      subject: '',
      typeId: '',
      moreParams: {},

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

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

      defId: '',
      formrenderVisible: false,
      formrenderTitle: ''
    }
  },

  created() {
    this.loadData()
  },
  methods: {
    generateTitle(name, title) { // generateTitle by vue-i18n
      return i18n.generateTitle(name, title)
    },
    onClickTab(index) {
      // 清空查询条件
      this.subject = ''
      this.typeId = ''
      this.moreParams = {}

      this.onSearch()
    },
    loadData() {
      this.loading = true
      if (this.tabActive === 0) {
        this.loadFavoritesListData()
      } else {
        this.loadDefineListData()
      }
    },
    loadFavoritesListData() {
      favorited(this.getSearcFormData()).then(response => {
        ActionUtils.handleListData(this, response.data)
      }).catch((e) => {
        ActionUtils.handleErrorData(this, e)
      })
    },
    loadDefineListData() {
      newProcess(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^name_^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.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({})
    },
    onFavorites(defId, type) {
      if (type === true) {
        removeFavorites({ defIds: defId }).then(response => {
          this.$notify({
            type: 'success',
            message: '取消收藏成功！'
          })
          this.onSearch()
        })
      } else {
        saveFavorites({ defIds: defId }).then(response => {
          this.$notify({
            type: 'success',
            message: '收藏成功！'
          })
          this.onSearch()
        })
      }
    },
    // 启动流程
    onClick(item) {
      this.defId = item.id
      this.formrenderTitle = item.name
      this.formrenderVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
  .new-process_size{
    font-size: 14px!important;
  }
  ::v-deep .van-cell__title{
    width: 65%;
    .van-cell__label{
      overflow-wrap: break-word;
    }
  }
</style>
