<template>
  <el-container class="list_main_content fullheight">
    <el-aside width="200px" v-if="!$route.meta.single" v-show="asideShow" class="aside-tree__wrap">
      <p class="flow_tree_top_title">已办事项分类</p>
      <FlowTree ref="FlowTree" @currentTree="getCurrent" :loadCount="loadCount" @switch-change="handleSwitch"
        :isAsideShow="isAsideShow"></FlowTree>
    </el-aside>
    <div class="navbar-collapse" :class="{'navbar-collapse-right': !asideShow}" @click="asideShow = !asideShow" v-if="!$route.meta.single">
      <div class="navbar-collapse-bg">
        <i class="navbar-collapse-arrow" :class="{'el-icon-arrow-left': asideShow, 'el-icon-arrow-right': !asideShow}"></i>
      </div>
    </div>
    <el-container style="border-left:1px solid #E7EAEC">
      <h3 class="flow_table_title">已办事项列表</h3>
      <div class="content_top_wrap">
        <el-form ref="form" v-form data-vv-scope="form" class="content_top_wrap_form">
          <el-input
            class="form_input"
            size="small"
            clearable
            placeholder="标题/编号/流程名称"
            prefix-icon="el-icon-search"
            v-model="form.tableData"
            @keyup.enter.native="searchEnterFun"
          ></el-input>
          <el-date-picker
            class="form_date_picker"
            v-model="form.date"
            type="datetimerange"
            size="small"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
          <div>
            <eip-org-selector
              class="form_org_selector"
              style="display:inline-block;"
              placeholder="发起人组织"
              :single="true"
              v-model="form.orgName"
              :config="{id: 'form.orgId'}"
            />
          </div>
        </el-form>
        <el-row>
          <el-col :span="24">
            <el-button size="small" type="primary" @click="search('find')">查询</el-button>
            <el-button size="small" @click="reset">重置</el-button>
            <el-button size="small" @click="taskToCopyTo()">传阅</el-button>
          </el-col>
        </el-row>
      </div>
      <el-main class="content">
        <!-- default-sort  排序 -->
        <el-table
          :data="rows"
          ref="htTable"
          @row-click="rowClick"
          style="width: 100%"
          header-cell-class-name="done-header-row"
          row-class-name="done-row"
          size="medium"
          v-loading="fullscreenLoading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center"></el-table-column>
          <el-table-column label="流程图" width="70" align="center">
            <template slot-scope="scope">
              <el-button
                @click="handleShowTaskImage(scope.row)"
                icon="icon-flow1"
                size="mini"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column prop="id" width="160" show-overflow-tooltip align="center" label="流程编号"></el-table-column>
          <el-table-column label="标题" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="done-subject" @click="handleRowClick(scope.row)" @contextmenu.prevent="handleRowClick(scope.row,true)"> {{ scope.row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column label="流程名称" show-overflow-tooltip align="center" width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.procDefName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否办结" show-overflow-tooltip align="center" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 'end' || scope.row.status == 'manualend'" class="blue-color">已办结</span>
              <span v-if="scope.row.status != 'end' && scope.row.status != 'manualend'" class="red-color">未办结</span>
            </template>
          </el-table-column>
          <el-table-column label="发起时间" show-overflow-tooltip align="center" width="160">
            <template slot-scope="scope">
              <span> {{ scope.row.createTime | formatDate }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="发起人" width="100" align="center"></el-table-column>
        </el-table>
      </el-main>
      <el-footer height="52px">
        <el-row type="flex" justify="end">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-row>
      </el-footer>
      <el-dialog title="撤回" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
        <el-input type="textarea" :autosize="{minRows: 4, maxRows: 4}" placeholder="请输入撤回意见" v-model="opinion"></el-input>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveRevoke" size="small">确 定</el-button>
          <el-button @click="exitRevoke" size="small">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 流程传阅-->
      <TaskToCopyTo ref="taskToCopyTo" :instId="ids" />
      <!-- 流程图 -->
      <TaskImage
        ref="taskImage"
        :bpmnInstId="selectBpmnInstId"
        :instId="selectInstanceId"
        :defId="selectDefId"
      />
    </el-container>
  </el-container>
</template>

<script>
import {mapState, mapActions} from 'vuex'
import process from '@/api/process'
import FlowTree from '@/components/flow/flowTree.vue'
import utils from '@/utils.js'
import TaskToCopyTo from '@/components/flow/task/taskToCopyTo.vue'
import eipOrgSelector from '@/components/eipControl/selector/EipOrgSelector.vue'
import TaskImage from "@/components/flow/task/taskImage.vue";
export default {
  name: 'doneRead',
  components: {
    FlowTree,
    TaskToCopyTo,
    eipOrgSelector,
    TaskImage
  },
  props: {
    defKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isAsideShow:false,
      asideShow:false,
      form: {tableData: '', date: '', orgName: '', orgId: ''},
      currentTree: '',
      fullscreenLoading: true,
      dialogFormVisible: false,
      opinion: '',
      id: '',
      ids: '', //已办实例id集合,
      selectInstanceId:"",
      selectDefId:"",
      selectBpmnInstId:""

    }
  },
  watch: {
    'form.orgId': {
      handler(newName, oldName) {
        this.search('find')
      },
      immediate: true
    }
  },
   computed: {
    ...mapState('storeProcess',['rows','pagination','total']),
    currentSwitchValue(){
      return localStorage.doneAsideShow === 'true' || localStorage.doneAsideShow === true
    }
  },
  methods: {
    //将当前展开或者收起的值存在localStorage中
    handleSwitch(val){
      localStorage.doneAsideShow = val
    },
    rowClick(row, column, event) {
      this.$refs.htTable.toggleRowSelection(row)
    },
    //流程传阅
    taskToCopyTo() {
      if (this.ids == '') {
        this.$message.warning('请选择要传阅的流程')
        return
      }
      this.$refs.taskToCopyTo.handleClose() //父组件调用子组件方法
    },
    //批量勾选待办流程获取
    handleSelectionChange(val) {
      this.ids = ''
      if (val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          this.ids = this.ids + val[i].id + ','
        }
        this.ids = this.ids.substring(0, this.ids.length - 1)
      }
    },
    formatDate(value) {
      return utils.formatDate(value.createTime)
    },
    handleClose(done) {
      this.dialogFormVisible = true
    },
    //撤回到上一个节点
    handleRevoke(id) {
      this.dialogFormVisible = true
      this.id = id
    },
    saveRevoke() {
      if (this.opinion == '') {
        this.$message.warning('请填写撤回意见')
        return false
      }
      let data = {
        instanceId: this.id,
        isHandRevoke: true,
        cause: this.opinion
      }
      this.$store.dispatch('storeProcess/revokeInstance', data).then(() => {
        this.dialogFormVisible = false
        this.opinion = ''
        this.search()
      })
    },
    exitRevoke() {
      this.dialogFormVisible = false
      this.opinion = ''
    },
    //Loading 加载中
    openFullScreen() {
      this.fullscreenLoading = true
    },
    handleSizeChange: function(size) {
      //每页下拉显示数据
      this.$store.dispatch('storeProcess/setPaginationSize', size)
      this.search()
    },
    handleCurrentChange: function(currentPage) {
      //点击第几页
      this.$store.dispatch('storeProcess/setPaginationPageNum', currentPage)
      this.search()
    },
    //回车查询
    searchEnterFun: function(e) {
      var keyCode = window.event ? e.keyCode : e.which
      if (keyCode == 13) {
        this.search('find')
      }
    },
    // 查询
    search(str) {
      this.openFullScreen()
      if (str == 'find') {
        this.$store.dispatch('storeProcess/setPaginationPageNum', 1)
      }
      let querys = [] //查询条件
      let queryFilter = {}
      let pageBean = {pageBean: this.pagination}
      let beginDate = '' //开始时间
      let endDate = '' //结束时间
      let group = 'main' //判断条件

      if (this.form.tableData) {
        querys = [
          {
            property: 'proc_def_name_',
            value: this.form.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          },
          {
            property: 'subject_',
            value: this.form.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          },
          {
            property: 'wfInst.id_',
            value: this.form.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          }
        ]
      }
      if (this.form.orgId) {
        querys.push({
          property: 'wfInst.CREATE_ORG_PATH_',
          value: this.form.orgId,
          group: 'orgId',
          operation: 'LIKE',
          relation: 'AND'
        })
      }
      if (this.currentTree) {
        querys.push({
          property: 'type_id_',
          value: this.currentTree,
          group: 'typeId',
          operation: 'IN',
          relation: 'AND'
        })
      }
      if (this.form.date) {
        beginDate = utils.formatDate(this.form.date[0].getTime())
        endDate = utils.formatDate(this.form.date[1].getTime())
        querys.push({
          property: 'wfInst.create_time_',
          value: [beginDate, endDate],
          group: 'time',
          operation: 'BETWEEN',
          relation: 'AND'
        })
      }

      if (this.defKey) {
        querys.push({
          property: 'proc_def_key_',
          value: this.defKey,
          operation: 'EQUAL',
          relation: 'AND'
        })
      }
      queryFilter = {pageBean: this.pagination, querys}
      this.$store.dispatch('storeProcess/getDoneByPagination', queryFilter).then(() => {
        this.fullscreenLoading = false
      })
    },
    //重置
    reset() {
      this.form = {tableData: '', date: '', orgName: '', orgId: ''}
      this.search('find')
    },
    handleRowClick(row,newWin) {
      //判断是否显示撤回按钮
      let type="";
      if (!(row.status != 'running' || row.opinionStatus != 'agree') || row.opinionStatus == 'inqu') {
        type="done";
      } else {
        type="doneList";
      }
      if (this.defKey) {
        this.handleOpenUrl('/sysModuleInst/' + row.id + '/'+type+'/'+this.defKey,newWin);
      }else{
        this.handleOpenUrl('/inst/' + row.id + '/'+type,newWin)
      }
    },
    handleOpenUrl(url,newWin){
      if(!newWin){
        this.$router.push(url);
        return;
      }
      if(!url){
        return ;
      }
      let token = this.$store.state.login.currentUser.token;
      if(!url.toLowerCase().startsWith("http")){
        url = window.context.front + url;
      }
      if(url.indexOf('?') == -1){
        url = url + "?token=" + token;
      }else{
        url = url + "&token=" + token;
      }
      window.open(url,"_blank");
    },
    //子组件传值父组件(已办分类查询)
    getCurrent(data) {
      if (data.id == 6) {
        this.currentTree = ''
      } else {
        let ids = []
        this.getFlowTrees(data, ids)
        this.currentTree = ids.join(',')
      }
      this.search('find')
    },
    getFlowTrees(data, ids) {
      ids.push(data.id)
      let arr = data.children
      for (var i = 0; i < arr.length; i++) {
        this.getFlowTrees(arr[i], ids)
      }
    },
    loadCount() {
      let pageBean = {}
      return process.getDoneInstCount(pageBean)
    },
    async handleShowTaskImage(row) {
      await this.changeSeletion(row);
      this.$refs.taskImage.handleOpen();
    },
    changeSeletion(row) {
      this.selectInstanceId = row.id;
      this.selectBpmnInstId = row.bpmnInstId;
    },
  },
  created() {
    this.asideShow = this.currentSwitchValue
    this.isAsideShow = this.currentSwitchValue
    let querys = []
    if (this.defKey) {
      querys.push({
        property: 'proc_def_key_',
        value: this.defKey,
        operation: 'EQUAL',
        relation: 'AND'
      })
    }
    let pageBean = {
      pageBean: {page: '1', pageSize: '10', showTotal: 'true'},
      querys
    } //初次加载默认pageBean
    this.$store.dispatch('storeProcess/getDoneByPagination', pageBean).then(() => {
      //页面加载调用done.js里面的分页方法
      this.fullscreenLoading = false
    })
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';
.el-table /deep/ th.done-header-row {
  background-color: #fafafa;
  font-size: 13px;
}

.el-table /deep/ tr.done-row {
  font-size: 13px;
  color: $--color-text-regular;
}

.el-container {
  background-color: #fff;
}

.el-row {
  margin-bottom: 20px;
}

.el-header {
  border-bottom: 1.5px solid #ededed;
}

.done-subject {
  cursor: pointer;
}

.done-subject {
  color: $--theme-color;
}

.top-title {
  line-height: 58px;
  margin-left: 20px;
  font-size: 16px;
  color: #a2a2a2;
}

/deep/.el-tree {
  position: relative;
  cursor: default;
  background: #fff;
  color: $--color-text-primary;
  font-size: 13px;
}
.content{
  padding-top: 0;
}
.content_top_wrap {
  display: flex;
  flex-direction: row;
  margin: 10px 0 0 20px;
  flex-wrap: wrap;
  // height: 32px;
  &_form {
    display: flex;
    flex-direction: row;
    margin-bottom: 10px;
    /deep/ .el-input__prefix,
    /deep/.el-input__suffix {
      height: 32px;
    }
    .form_input {
      margin-right: 10px;
    }
    .form_date_picker,
    .form_org_selector {
      margin-right: 10px;
      min-width: 300px;
    }
  }
}
</style>
