<template>
  <div :class="{'ibps-fixed-toolbar':checkMode}">
    <van-sticky>
      <van-nav-bar :title="generateTitle($route.name,$route.params.title||$route.meta.title)"
        :left-text="$t('common.button.back')" :right-text="$utils.isNotEmpty(listData)?rightText:''" left-arrow
        @click-left="$router.push({ name: 'dashboard' })" @click-right="toCheckMode()" />
      <!-- <van-tabs v-model="tabActive" @click="onSearch">
        <van-tab
          v-for="data in tabDatas"
          :key="data.name"
          :name="data.name"
          :title="data.title"
        />
      </van-tabs> -->
      <van-search v-model="subject" show-action 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-checkbox-group v-model="checkedIds">
          <van-cell v-for="(item,index) in listData" :key="item.id+index" :title="item.procDefName"
            :label="getTaskDesc(item.subject)" @click="onClick(item,index)">
            <template slot="icon">
              <van-checkbox v-if="checkMode" ref="checkboxes" :name="item.taskId" class="ibps-mr-10" />
              <ibps-avatar v-else :icon="_randomIcon(index)" :text="item.procDefName" :bg-color="_randomColor(index)"
                radius="4" icon-prefix="ibps-icon" class="ibps-mr-10" />
            </template>
            <span>{{ item.createTime|formatRelativeTime }}</span>
            <div v-if="item.remindTimes>0">
              <!-- <van-tag plain :type="item.remindTimes|remindTimesTypeFilter">催办{{ item.remindTimes }}次</van-tag> -->
              <van-tag size="medium"
                :color="item.remindTimes|remindTimesTypeFilter | optionsFilter(colorOptions,'color','type')"
                :text-color="item.remindTimes|remindTimesTypeFilter | optionsFilter(colorOptions,'textColor','type')">
                催办{{ item.remindTimes }}次</van-tag>
            </div>
          </van-cell>
        </van-checkbox-group>
      </van-list>
      <ibps-list-result-page :result-type="resultType" :error-type="errorType" :result-message="resultMessage" />
    </van-pull-refresh>
    <ibps-toolbar v-show="checkMode" :actions="actions" />

    <approve-popup :visible="batchOpinionPopup" :task-id="selectedIds" :action="actionName"
      @close="(visible)=>{batchOpinionPopup =visible}" @callback="onRefreshPage" />
    <!--高级查询-->
    <ibps-more-search :show="moreSearchPopup" :search-forms="searchForms" @callback="onMoreSearch"
      @close="callback => moreSearchPopup = callback" @reset-form="resetForm">
      <template v-slot:definition>
        <ibps-bpmn-definition v-model="defKey" value-key="defKey" input-align="left" class="van-hairline--bottom" />
      </template>
    </ibps-more-search>

    <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" :task-id="taskId"
      @close="visible => formrenderVisible = visible" @callback="onRefreshPage" />
  </div>
</template>
<script>
  import { pending4User, pending4Org, pending4OrgManager, pending4Role, pending4Position, pending4Group } from '@/api/platform/office/bpmReceived'
  import { batchSuspendProcess, batchRecoverProcess } from '@/api/platform/bpmn/bpmTask'

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

  import ApprovePopup from '@/business/platform/bpmn/form-ext/approve'

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

  import IbpsBpmnFormrenderDialog from '@/business/platform/bpmn/form/dialog'

  export default {
    components: {
      IbpsMoreSearch,
      IbpsAvatar,
      IbpsListResultPage,
      IbpsTypeTree,
      IbpsBpmnDefinition,
      IbpsToolbar,
      ApprovePopup,
      IbpsBpmnFormrenderDialog
    },
    mixins: [random, bpmnStatus],
    data() {
      return {
        // tabActive: 'userType',
        tabActive: 'user',
        tabDatas: [{
          name: 'user',
          title: '用户'
        }, {
          name: 'org',
          title: '组织'
        }, {
          name: 'orgManager',
          title: '组织负责人'
        }, {
          name: 'role',
          title: '角色'
        }, {
          name: 'position',
          title: '岗位'
        }, {
          name: 'group',
          title: '用户组'
        }],
        moreSearchPopup: false,
        stateActive: false,
        searchForms: {
          forms: [
            { prop: 'Q^subject_^SL', label: '事物名称' },
            { prop: 'Q^procDefName^SL', label: '事物说明', fieldType: 'slot', slotName: 'definition' },
            { prop: ['Q^create_time_^DL', 'Q^create_time_^DG'], label: '创建时间', fieldType: 'dateRange', options: { datefmt: 'yyyy-MM-dd' } }
          ]
        },
        subject: '',
        typeId: '',
        defKey: '',
        moreParams: {},

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

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

        checkMode: false,
        checkedIds: [],
        show: false,
        actions: [
          {
            name: this.$t('common.button.agree'),
            type: 'primary',
            callback: this.openAgreeDialog
          }, {
            name: this.$t('common.button.stop'),
            type: 'danger',
            callback: this.openStopDialog
          }, {
            name: this.$t('common.button.suspend'),
            type: 'warning',
            callback: this.suspend
          }, {
            name: this.$t('common.button.recover'),
            type: 'info',
            callback: this.recover
          }
        ],
        batchOpinionPopup: false,
        actionName: 'agree',

        typeTreePopup: false,

        taskId: '',
        formrenderVisible: false,
        formrenderTitle: ''
      }
    },
    computed: {
      rightText() {
        return this.checkMode ? this.$t('common.button.cancel') : this.$t('common.button.manage')
      },
      selectedIds() {
        return this.checkedIds.join(',')
      }
    },
    methods: {
      generateTitle(name, title) { // generateTitle by vue-i18n
        return i18n.generateTitle(name, title)
      },
      /**
       * 加载数据
       */
      loadData() {
        this.loading = true
        let requestMethod
        switch (this.tabActive) {
          case 'user':
            requestMethod = pending4User
            break
          case 'org':
            requestMethod = pending4Org
            break
          case 'orgManager':
            requestMethod = pending4OrgManager

            break
          case 'role':
            requestMethod = pending4Role
            break
          case 'position':
            requestMethod = pending4Position
            break
          case 'group':
            requestMethod = pending4Group
            break
          default:
            break
        }

        requestMethod(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^temp.subject_^SL'] = this.subject
        }
        if (this.$utils.isNotEmpty(this.typeId)) {
          params['Q^temp.TYPE_ID_^S'] = this.typeId
        }
        if (this.$utils.isNotEmpty(this.defKey)) {
          params['Q^temp.proc_def_key_^S'] = this.defKey
        }
        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) {
        this.moreParams = params
        this.onSearch()
        if (this.$utils.isNotEmpty(params)) {
          this.stateActive = true
        }
      },
      /**
       * 弹窗更多查询条件
       */
      clickMoreSearch() {
        this.moreSearchPopup = true
        this.stateActive = false
      },
      /**
       * 重置表单
       */
      resetForm() {
        this.typeId = ''
        this.defKey = ''
      },

      onRefreshPage() {
        this.checkedIds = []
        this.checkMode = false
        this.onRefresh()
      },

      onClick(item, index) {
        if (this.checkMode) {
          this.$refs.checkboxes[index].toggle()
        } else {
          this.taskId = item.id
          this.formrenderTitle = item.procDefName
          this.formrenderVisible = true
        }
      },
      clickType() {
        this.typeTreePopup = true
      },
      clickTypeNode(data) {
        this.typeId = data.id
        this.onMoreSearch({})
      },
      toCheckMode() {
        if (this.$utils.isEmpty(this.listData)) {
          return
        }
        if (this.checkMode) {
          this.show = true
          this.checkedIds = []
        }
        this.checkMode = !this.checkMode
      },
      openAgreeDialog() {
        if (this.checkedIds.length === 0) {
          this.$notify({
            type: 'warning',
            message: this.$t('common.dialog.selectedRecords')
          })
          return
        }
        this.batchOpinionPopup = true
        this.actionName = 'agree'
      },
      openStopDialog() {
        if (this.checkedIds.length === 0) {
          this.$notify({
            type: 'warning',
            message: this.$t('common.dialog.selectedRecords')
          })
          return
        }
        this.batchOpinionPopup = true
        this.actionName = 'stop'
      },

      suspend() {
        if (this.checkedIds.length === 0) {
          this.$notify({
            type: 'warning',
            message: this.$t('common.dialog.selectedRecords')
          })
          return
        }

        this.$dialog.confirm({
          title: this.$t('common.dialog.warn'),
          message: this.$t('common.operate.makeSure')
        }).then(() => {
          batchSuspendProcess({ 'taskIds': this.selectedIds }).then(response => {
            this.$notify({
              type: 'success',
              message: '批量挂起流程成功！'
            })
            this.onRefreshPage()
          }).catch((e) => {
            console.error(e)
          })
        })
      },
      getTaskDesc(v) {
        if (!v.includes('#')) {
          return ''
        }
        return v.split('#')[1] || ''
      },
      recover() {
        if (this.checkedIds.length === 0) {
          this.$notify({
            type: 'warning',
            message: this.$t('common.dialog.selectedRecords')
          })
          return
        }
        this.$dialog.confirm({
          title: this.$t('common.dialog.warn'),
          message: this.$t('common.operate.makeSure')
        }).then(() => {
          batchRecoverProcess({ 'taskIds': this.selectedIds }).then(response => {
            this.$notify({
              type: 'success',
              message: '批量恢复流程成功！'
            })
            this.onRefreshPage()
          }).catch((e) => {
            console.error(e)
          })
        })
      }
    }

  }
</script>
<style lang="scss" scoped>
  ::v-deep .van-cell__title {
    width: 65%;

    .van-cell__label {
      overflow-wrap: break-word;
    }
  }
</style>