<template>
  <div class="layout-no-cols">
    <!--工具栏-->
    <el-toolbar align="right">
      <!--搜索栏-->
      <div class="dropdown-search-box-r search-bar-algin-toolbar search-box-workflowview">
        <el-input v-model="filter.keyword" placeholder="请输入标题" size="medium" @keyup.enter.native="queryHandler">
          <el-select @change="queryHandler" style="width:150px" clearable slot="prepend" v-model="filter.type">
            <el-option label="所有流转中的文档" value="ALL"></el-option>
            <el-option label="待我处理的文档" value="TOME"></el-option>
            <el-option label="我处理过的文档" value="HANDLED"></el-option>
          </el-select>
        </el-input>
        <span class="search-icon">
          <i class="fa fa-search" @click="queryHandler" title="查询"></i>
        </span>
      </div>

    </el-toolbar>

    <div v-loading="dataLoading">

      <!-- 表格数据 -->
      <el-table ref="multipleTable" :data-read-url="getWorkflowlistURL" :page-size="20" tooltip-effect="dark" style="width: 100%"
        @select="selectclickHandler" @selection-change="selectionChangeHandler">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="catalogIDName" label="所属栏目" show-overflow-tooltip width="80"></el-table-column>
        <el-table-column label="标题" show-overflow-tooltip>
          <template slot-scope="scope">
            <i :class="scope.row.state !=='Unread' ? 'fa fa-envelope-open-o' : 'fa fa-envelope'"></i>
            <a href="javascript:void(0);" @click="openClickHandler(scope.row)">{{scope.row.title}}</a>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="statusName" label="文档状态" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="actionName" label="上次动作" show-overflow-tooltip width="100"></el-table-column>
        <el-table-column prop="stepName" label="当前步骤" show-overflow-tooltip width="80"></el-table-column>
        <!-- <el-table-column prop="stateName" label="标志" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="操作" align="right" width="140">
          <template slot-scope="scope">
            <el-button @click.stop="openClickHandler(scope.row)" type="text" title="打开" :priv="'com.zving.cms.Catalog.Content.'+catalogId">
              <i class="fa fa-edit f16"></i>
            </el-button>
            <el-button @click.stop="deleteClickHandler(scope.row.ID)" type="text" title="删除" :priv="'com.zving.cms.Catalog.Content.Delete.'+catalogId">
              <i class="fa fa-times f16"></i>
            </el-button>
            <el-button @click.stop="previewClickHandler(scope.row.ID)" type="text" title="预览" :priv="'com.zving.cms.Catalog.Content.'+catalogId">
              <i class="fa fa-eye f16"></i>
            </el-button>
            <el-dropdown @command="handleCommand" class="fr">
              <el-button type="text">
                <i class="fa fa-ellipsis-h f16" aria-hidden="true"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{fun:'applicationHandler',param:[scope.row]}" plain>
                  <i class="fa fa-chain"></i>申请处理</el-dropdown-item>
                <el-dropdown-item :command="{fun:'publish',param:scope.row.ID}" plain :priv="'com.zving.cms.Catalog.Content.Publish.'+catalogId">
                  <i class="fa fa-paper-plane"></i>发布</el-dropdown-item>
                <el-dropdown-item :command="{fun:'operateHistoryHandler',param:scope.row.ID}" plain  :priv="'com.zving.cms.Catalog.Content.'+catalogId">
                  <i class="fa fa-list-alt"></i>操作记录</el-dropdown-item>
                <el-dropdown-item :command="{fun:'forceEndingHandler',param:scope.row}" plain v-if="userName === 'admin'">
                  <i class="fa fa-ban"></i>强行结束流程</el-dropdown-item>
                <el-dropdown-item :command="{fun:'viewProcessClickHandler',param:scope.row}" plain priv="Admin.Workflow" >
                  <i class="fa fa-sitemap"></i>查看流程</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--操作记录-->
    <el-dialog title="操作记录" :visible.sync="historyDialogVisible" width="75%">
      <el-row v-loading="logDataLoading">
        <el-col :span="8">
          <span class="demonstration">起始时间</span>
          <el-date-picker id="wv-date-picker1" v-model="startTimeValue" @change="formatStartTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" align="right"
            type="date" placeholder="选择日期" :picker-options="pickerOptions">
          </el-date-picker>
        </el-col>
        <el-col :span="8">
          <span class="demonstration">结束时间</span>
          <el-date-picker id="wv-date-picker2" v-model="endTimeValue" @change="formatEndTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" align="right"
            type="date" placeholder="选择日期" :picker-options="pickerOptions">
          </el-date-picker>
        </el-col>
        <el-col :span="8">
          <span class="demonstration">操作人</span>
          <el-input v-model="filter.author" placeholder="" prop="value" style="width: auto;"></el-input>
          <el-button type="primary" @click="search">搜索</el-button>
        </el-col>
      </el-row>
      <el-table :data="historyData" tooltip-effect="dark" style="width: 100%">
        <el-table-column type="index" label="序号" width="65"></el-table-column>
        <el-table-column prop="actionName" label="操作" show-overflow-tooltip></el-table-column>
        <el-table-column prop="actionDetail" label="操作明细" show-overflow-tooltip></el-table-column>
        <el-table-column prop="addUser" label="操作人" show-overflow-tooltip></el-table-column>
        <el-table-column prop="addTime" label="操作时间" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.addTime | fixDateTime}}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import util from '@src/common/util.js'

export default {
  filters: {
    fixDateTime: function(val) {
      if (!val) {
        return ''
      }
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      userName: localStorage.userName,
      workFlowID: 0,
      workflowlist: [], // 表格当前页数据
      selectedRows: [], // 已选择项数组
      currentPage: 1, // 当前页数
      pageSizes: [5, 10, 15, 20, 30, 40, 50], // 每页显示个数选择器的选项设置
      pageSize: 5, // 每页显示条目个数
      total: 0, // 分页总条目数
      dataLoading: false, // 是否加载
      logDataLoading: false,
      filter: {
        keyword: '', // 查询框的关键字内容
        type: 'ALL', // 查询框的查询字段
        author: '' // 操作记录查询框的关键字内容
      },
      historyDialogVisible: false, // 操作记录，页面是否可见

      historyData: [], // 操作记录数据
      pickerOptions: {
        // 带快捷选项日期选择
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      startTimeValue: '', // 起始时间值
      endTimeValue: '' // 结束时间值
    }
  },
  methods: {
    handleCommand(obj) {
      if (obj) {
        var fun = obj.fun
        var param = obj.param
        typeof this[fun] === 'function' && this[fun](param)
      } else {
        console.warn(`未找到改菜单对应的方法:${fun}`)
      }
    },

    formatStartTime(val) {
      this.startTimeValue = val
    },

    formatEndTime(val) {
      this.endTimeValue = val
    },

    selectclickHandler(selection, row) {
      // console.log(row.ID)
    },

    // 打开
    openClickHandler(row) {
      let path = `/contentEditor/${row.ID}?type=${row.contentType}&cid=${row.catalogID}`
      window.open('contentEditor.html#' + path)
    },

    getWorkflowlistURL() {
      return [
        '/ui/workflowlist',
        {
          params: {
            pageIndex: this.currentPage - 1,
            pageSize: this.pageSize,
            keyword: encodeURIComponent(this.filter.keyword),
            type: this.filter.type,
            catalogID: this.catalogId
          }
        }
      ]
    },

    // 申请处理
    async applicationHandler(selectedRows) {
      let count = 0
      selectedRows.forEach(row => {
        if (row.state === 'Underway') {
          count++
        }
      })
      if (count === selectedRows.length) {
        util.showResponseMessage({message: '选中的记录中没有处于待申请状态的!', status: 0})
        return
      }
      // 提取选中行的文档状态
      let workflows = { data: selectedRows }
      let res = await axios.put(`/ui/workflowlist/applystep`, workflows)
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.$refs.multipleTable.getData()
      }
    },
    // 删除选中行
    async deleteClickHandler(ID) {
      try {
        await this.$confirm('确定删除吗？删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      // 提取选中行的id
      let resp = await axios.delete(`/ui/contentcore/contents/${ID}`, {params: {catalogID: this.catalogId}})
      util.showResponseMessage(resp.data)
      this.$refs.multipleTable.getData()
    },

    // 发布
    async publish(ID) {
      let res = await axios.put(`/ui/contentcore/contentpublish/${ID}/pub`, {catalogID: this.catalogId})
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.$refs.multipleTable.getData()
      }
    },

    // 预览
    previewClickHandler(ID) {
      window.open(`preview.html?id=${ID}&type=content`)
    },

    // 操作记录
    operateHistoryHandler(ID) {
      this.historyDialogVisible = true
      this.workFlowID = ID
      this.logDataLoading = true
      this.getWorkflowlistHistory()
    },
    // 操作记录搜索
    search(val) {
      this.logDataLoading = true
      this.getWorkflowlistHistory()
    },

    // 强行结束流程
    async forceEndingHandler(row) {
      if (row.status !== 10) {
        this.$alert('非流转中的文档不能直接结束', '提示', {
          type: 'warning'
        })
        return
      }
      // 提取选中行的文档状态
      let workflows = { data: [row] }
      let res = await axios.put(`/ui/workflowlist/forceend`, workflows)
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.$refs.multipleTable.getData()
      }
    },

    // 查看流程
    viewProcessClickHandler(row) {
      let workflowID = row.workflowConfigID
      if (workflowID) {
        window.open(`./workflowEditor.html?ID=${workflowID}`)
      } else {
        this.$message.error('获取不到工作流')
      }
    },

    // 多选响应
    selectionChangeHandler(selection) {
      this.selectedRows = selection
    },

    // 查询
    queryHandler() {
      this.dataLoading = true
      this.$refs.multipleTable.getData()
      this.dataLoading = false
    },

    async getWorkflowlistHistory() {
      let resp = await axios.get(`/ui/workflowlist/${this.workFlowID}`, {
        params: {
          startDate: this.startTimeValue,
          endDate: this.endTimeValue,
          userName: encodeURI(this.filter.author)
        }
      })
      this.historyData = resp.data.data
      this.logDataLoading = false
    }
  },

  props: {
    catalogId: {
      type: [Number, String]
    }
  },
  watch: {
    catalogId() {
      this.filter.type = 'ALL'
      this.$refs.multipleTable.getData()
    }
  }
}
</script>

<style scoped>
.el-form {
  float: right;
}

.el-form-item {
  margin: 0;
}

.page-wrap .page {
  float: right;
}

.el-dialog .el-form {
  float: left;
  padding-top: 0;
}

.demonstration {
  padding-right: 10px;
  font-weight: bold;
}

.errorNum {
  display: block;
  font-weight: bold;
}

.errorMessage {
  display: block;
}
.search-box-workflowview .search-icon{top:8px;}
</style>
