/**
* @Description: 流程查询
* @author wx
* @date 2020/4/1
*/
<template>
  <div class="process-page">
    <DeeSearchLay
      :form="form"
      :quick-search="quickSearch"
      :table-colums="tableColums"
      :table-data="tableData"
      :index-row="indexRow"
      :pagination="pagination"
      :is-show="isShow"
      :preview-tabs="previewTabs"
      :detail-title="detailTitle"
      @handleSearch="handleSearch"
      @paginationCurrentChange="paginationCurrentChange"
      @handleSizeChange="handleSizeChange"
      @closeDetail="closeDetail"
      @handleOperate="handleOperate"
    />
  </div>
</template>

<script>
import { getInstanceList, getInstanceInfo, getInstancePbo, getInstanceHistory, getTemplateList } from '@/api/workflow/userSettings.js'

export default {
  name: 'Process',
  components: {},
  data() {
    return {
      dialogVisible: false,
      searchObj: {
        startedUserId: localStorage.getItem('userId')
      },
      isShow: false,
      // 不是快速查询
      isQuickSearch: false,
      itemData: null,
      // 列表
      tableColums: [
        { title: '流程名称', key: 'name', align: 'center', minWidth: 180, component: {
          render: (h, params) => {
            return h('div', [
              h('span', {
                class: 'link-style',
                on: {
                  click: () => {
                    this.itemData = params
                    this.lookDetail()
                  }
                }
              }, params.name)
            ])
          }
        }},
        { title: '流程模板', key: 'processDefName', align: 'center', formatter(row, column) {
          return row.processDef ? row.processDef.name : ''
        } },
        { title: '启动者', key: 'ownerName', align: 'center', minWidth: 140 },
        { title: '状态', key: 'status', align: 'center' },
        { title: '开始时间', key: 'gmtCreate', align: 'center', minWidth: 180 },
        { title: '完成时间', key: 'gmtFinished', align: 'center', minWidth: 180 },
        { title: '执行期限(d)', key: 'costTimeInMillis', align: 'center', formatter(row, column) {
          const costTimeInMillis = row.costTimeInMillis
          if (!costTimeInMillis) return '/'

          const costTimeInHours = costTimeInMillis / 3600 / 1000 / 24
          return costTimeInHours
        } },
        { title: '超时(d)', key: 'expireTimeInMillis', align: 'center',
          component: {
            render(h, params) {
              const expireTimeInMillis = params.expireTimeInMillis
              let str = '/'
              let color = ''
              if (expireTimeInMillis) {
                const expireTimeInHours = expireTimeInMillis / 3600 / 1000 / 24
                str = expireTimeInHours ? (expireTimeInHours > 0 ? `逾期` : `剩余`) + ` ${Math.abs(expireTimeInHours.toFixed(1))}` : '/'
                color = expireTimeInHours > 0 ? 'red' : ''
              }
              return h('span',
                { style: { color }}, str)
            }
          }}
      ],
      indexRow: {
        title: '序号',
        align: 'center',
        width: '70'
      },
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50]
      },
      // 快速查询列表条件
      quickSearch: [
        {
          name: '我发起的流程',
          num: 0
        }
      ],
      // Tab标签页点击事件
      tabHandler: {
        'tab-click': function(tab) {
          this.hanldeTab(tab)
        }
      },
      form: {
        // form表单数据
        propForm: {
          'startedUserId': localStorage.getItem('userId')
        },
        // form 表单展示方式配置
        propFormData: [{
          data: [
            {
              key: 'name',
              title: '流程名称',
              component: {
                name: 'el-input',
                clearable: true
              }
            },
            {
              key: 'processDefKey',
              title: '流程模板',
              component: {
                name: 'el-select',
                options: [],
                clearable: true,
                filterable: true,
                remote: true,
                reserveKeyword: true,
                remoteMethod: (val) => {
                  this.handleRemoteTemp(val)
                }
              }
            },
            {
              key: 'startedUserId',
              title: '流程启动者',
              component: {
                name: 'DxUserSelect'
              },
              handler: {
                getUser: (value) => {
                  this.$set(this.form.propForm, 'startedUserId', value.id)
                }
              }
            },
            {
              key: 'gmtCreateRange',
              title: '开始时间',
              component: {
                name: 'el-date-picker',
                type: 'daterange',
                clearable: true,
                format: 'yyyy-MM-dd',
                startPlaceholder: '开始时间',
                endPlaceholder: '结束时间'
              }
            },
            {
              key: 'gmtFinishRange',
              title: '完成时间',
              component: {
                name: 'el-date-picker',
                type: 'daterange',
                clearable: true,
                format: 'yyyy-MM-dd',
                startPlaceholder: '开始时间',
                endPlaceholder: '结束时间'
              }
            },
            {
              key: 'hasTimeout',
              title: '是否超时',
              component: {
                name: 'el-select',
                options: [
                  { 'label': '是', 'value': 'true' },
                  { 'label': '否', 'value': 'false' }],
                clearable: true
              }
            },
            {
              key: 'state',
              title: '状态',
              component: {
                name: 'el-select',
                options: [
                  { 'label': '进行中', 'value': 'RUNNING' },
                  { 'label': '已完成', 'value': 'FINISHED' }],
                clearable: true
              }
            }
          ]
        }]
      },
      selectionRow: [],
      // 详情标题
      detailTitle: '',
      previewTabs: [
        {
          'name': '任务信息',
          'data': [{
            'prop': { basicInfo: [] },
            'path': 'basicInfo',
            'name': '任务信息',
            'id': 1584759705994
          }]
        },
        {
          'name': '历史记录',
          'data': [{
            'prop': {
              historyColumns: [
                { title: '流程实例名称', key: 'instanceName', align: 'center', minWidth: 180, formatter(row, column) {
                  return row.processInstVO ? row.processInstVO.name : ''
                } },
                { title: '活动名称', key: 'name', align: 'center', minWidth: 160, formatter(row, column) {
                  return row.aliasName || row.name
                } },
                { title: '执行者', key: 'assigneeName', align: 'center' },
                { title: '委托人', key: 'ownerName', align: 'center' },
                { title: '处理结果', key: 'result', align: 'center' },
                { title: '备注', key: 'comments', align: 'center', formatter: function(row, column) {
                  return row.comments ? row.comments.join('\n') : ''
                } },
                { title: '开始时间', key: 'startTime', align: 'center', minWidth: 120 },
                { title: '结束时间', key: 'endTime', align: 'center', minWidth: 120 }
              ],
              historyInfo: []
            },
            'path': 'history',
            'name': '流程历史记录',
            'desc': '对象的流程历史记录',
            'id': 1584806243055
          }]
        },
        {
          'name': '流程跟踪',
          'data': [{
            'prop': { processInstanceId: '' },
            'path': 'processTracking',
            'name': '流程跟踪',
            'id': 1584759705993
          }]
        }
      ]
    }
  },
  created() {
  },
  mounted() {
    this.setOptions()
    this.getSelfList()
    this.getList()
  },
  methods: {
    hanldeTab(val) {
    },
    setOptions(query) {
      const params = {
        'page': 1,
        'size': 9999,
        'enable': true
      }
      if (query) { params.name = query }
      getTemplateList(params).then(res => {
        const tempOptions = []
        res.items.content.forEach((item) => {
          tempOptions.push({
            'label': item.name,
            'value': item.key
          })
        })
        this.form.propFormData[0].data[1].component.options = tempOptions
      })
    },
    handleSearch(obj) {
      this.searchObj = {}
      if (obj.gmtCreateRange) {
        this.searchObj.gmtCreateStart = obj.gmtCreateRange[0] + ' 00:00:00'
        this.searchObj.gmtCreateEnd = obj.gmtCreateRange[1] + ' 23:59:59'
      }
      if (obj.gmtFinishRange) {
        this.searchObj.gmtFinishStart = obj.gmtFinishRange[0] + ' 00:00:00'
        this.searchObj.gmtFinishEnd = obj.gmtFinishRange[1] + ' 23:59:59'
      }

      if (obj.name) { this.searchObj.name = obj.name }
      if (obj.processDefKey) { this.searchObj.processDefKey = obj.processDefKey }
      if (obj.startedUserId) { this.searchObj.startedUserId = !isNaN(obj.startedUserId) ? obj.startedUserId : localStorage.getItem('userId') }
      if (obj.hasTimeout) { this.searchObj.hasTimeout = obj.hasTimeout }
      if (obj.state) { this.searchObj.state = obj.state }
      this.pagination.currentPage = 1
      this.pagination.pageSize = 10
      this.getList()
      this.closeDetail()
    },
    handleOperate(obj) {
      this.isQuickSearch = true
      this.isShow = false
      this.searchObj = {}
      this.form.propForm = {
        startedUserId: localStorage.getItem('user') + '(' + localStorage.getItem('fullName') + ')'
      }
      switch (obj.type) {
        // 我发起的流程
        case 0:
          this.getSelfList()
          break
        case 1:
        // 超时流程
      }
    },
    getList() {
      const params = this.searchObj
      params.page = this.pagination.currentPage
      params.size = this.pagination.pageSize
      getInstanceList(params).then(res => {
        this.tableData = res.items.content.map(item => {
          item.show = true
          return item
        })
        this.pagination.total = res.items.totalElements
      })
    },
    // 获取我发起的流程
    getSelfList() {
      const requestData = {
        'page': this.pagination.currentPage,
        'size': this.pagination.pageSize,
        'startedUserId': localStorage.getItem('userId')
      }
      getInstanceList(requestData).then(res => {
        if (this.isQuickSearch) {
          this.tableData = res.items.content.map(item => {
            item.show = true
            return item
          })
          this.pagination.total = res.items.totalElements
        }
        this.quickSearch[0].num = res.items && res.items.totalElements ? res.items.totalElements : 0
      })
    },
    getDetail(id) {
      getInstanceInfo(id).then(res => {
        const processInst = res.items
        getInstancePbo(id).then(data => {
          const pboData = data.items
          const basicInfo = [
            { label: '实例名称', value: processInst.name },
            { label: '实例ID', value: processInst.id },
            { label: '启动者', value: processInst.ownerName },
            { label: '状态', value: processInst.status },
            { label: '开始时间', value: processInst.gmtCreate },
            { label: '完成时间', value: processInst.gmtFinished },
            { label: '引用模板', value: `${processInst.procDefName}(${processInst.procDefVersion})` },
            { label: '业务对象', value: `${pboData.subTypeName}-${pboData.id}` }]
          this.previewTabs[0].data[0].prop.basicInfo = basicInfo
        })
      })
    },
    getHistory(id) {
      getInstanceHistory(id).then(res => {
        this.previewTabs[1].data[0].prop.historyInfo = res.items.content || []
      })
    },
    // 查看详情
    lookDetail() {
      this.isShow = true
      this.detailTitle = `<div class="task-title">${this.itemData.name}<span>(${this.itemData.status})</span></div>`
      this.getDetail(this.itemData.id)
      this.getHistory(this.itemData.id)
      this.previewTabs[2].data[0].prop.processInstanceId = this.itemData.id
    },
    // 关闭详情
    closeDetail() {
      this.isShow = false
    },
    handleSizeChange(pageSize) {
      if (!this.isQuickSearch) {
        this.getList()
      } else {
        this.getSelfList()
      }
    },
    paginationCurrentChange(currentPage) {
      if (!this.isQuickSearch) {
        this.getList()
      } else {
        this.getSelfList()
      }
    },
    handleRemoteTemp(query) {
      if (query !== '') {
        this.setOptions(query)
      }
    }
  }
}
</script>

<style lang="scss">
.process-page {
  height:100%;
  .flex-s{
    display: flex;
    justify-content: space-between;
  }
  .dee-table{
    height: 100%;
    .dee-table-body {
      height: calc(100% - 110px) !important;
    }
  }
}
</style>