<template>
  <el-container class="list_main_content">
    <el-aside width="200px">
      <b class="top-title el-icon-menu">待办信息分类</b>
      <FlowTree
        ref="FlowTree"
        v-if="isRefresh"
        @currentTree="getCurrent"
        :loadCount="loadCount"
        :data="data"
      ></FlowTree>
    </el-aside>
    <el-container
      style="border-left:1px solid #E7EAEC;"
      class="table-container"
    >
      <el-main>
        <div class="query-box">
          <div>
            <el-button
              size="small"
              type="primary"
              @click="copyToClick"
              icon="icon-chuanyue"
              >传阅</el-button
            >
            <el-button
              size="small"
              @click="divertClick"
              icon="icon-zhuanyi"
              type="primary"
              >转移</el-button
            >
          </div>
          <div class="query-box_right">
            <el-input
              size="small"
              clearable
              placeholder="标题/编号/流程名称"
              prefix-icon="el-icon-search"
              style="width:300px;margin:0 15px;"
              v-model="tableData"
              @keyup.enter.native="searchEnterFun"
            ></el-input>
            <el-date-picker
              v-model="date"
              type="datetimerange"
              align="right"
              size="small"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
            <div style="margin-left: 15px;">
              <el-button
                size="small"
                type="primary"
                @click="search('find')"
                icon="el-icon-search"
                >搜索</el-button
              >
              <el-button size="small" @click="reset" icon="icon-my-todo-reset"
                >重置</el-button
              >
            </div>
          </div>
        </div>
        <!-- default-sort  排序 -->
        <el-table
          ref="doneTable"
          :data="rows"
          border
          style="width: 100%"
          header-cell-class-name="header-row-bg"
          row-class-name="flow-table-row"
          size="medium"
          v-loading="fullscreenLoading"
          :max-height="500"
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="id"
            width="200"
            show-overflow-tooltip
            align="center"
            label="流程编号"
          ></el-table-column>
          <el-table-column label="标题" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="流程名称"
            show-overflow-tooltip
            align="center"
            width="200" 
          >
            <template slot-scope="scope">
              <!-- <span>{{
                $t('flow.' + scope.row.procDefKey, scope.row.procDefName)
              }}</span> -->
              <span>{{scope.row.procDefName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="是否办结"
            show-overflow-tooltip
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <el-tag
                v-if="
                  scope.row.status == 'end' || scope.row.status == 'manualend'
                "
                type="danger"
                size="small"
                >已办结</el-tag
              >
              <el-tag
                v-if="
                  scope.row.status != 'end' && scope.row.status != 'manualend'
                "
                size="small"
                >未办结</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            label="发起时间"
            show-overflow-tooltip
            align="center"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.createTime | dateformat('yyyy-MM-DD HH:mm:ss')
              }}</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="50px" style="padding:10px 0">
        <el-row type="flex" justify="end">
          <el-pagination
               background
            :disabled="fullscreenLoading"
            @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="pagination.total"
          ></el-pagination>
        </el-row>
      </el-footer>
    </el-container>
    <!--传阅按钮 用户选择对话框  -->
    <ht-user-dialog
      ref="copyToClick_EipUserDialog"
      @on-confirm="eipUserDialogOk"
      append-to-body
    />

    <!--转移按钮 用户选择对话框  -->
    <ht-user-dialog
      ref="divertClick_EipUserDialog"
      @on-confirm="eipUserDialogOk"
      single
      append-to-body
    />
  </el-container>
</template>

<script>
import req from '@/request.js'
import FlowTree from '@/views/flow/permissionAdjustment/FlowTree.vue'
import utils from '@/hotent-ui-util.js'
import flow from '@/api/flow.js'
import {Message} from 'element-ui'
const eipUserDialog = () => import('@/components/dialog/EipUserDialog.vue')
let Base64 = require('js-base64').Base64
export default {
  name: 'done',
  components: {FlowTree, eipUserDialog},
  props: ['data'],
  data() {
    return {
      isRefresh: true,
      maxHeight: '500', //列表高度
      tableData: '',
      date: '',
      currentTree: '',
      fullscreenLoading: true,
      sorter: [],
      rows: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      selectInstIds: '', //选择要复制的instId
      //点击的按钮
      buttonName: '',
      selectList: []
    }
  },
  watch: {
    data: {
      handler(newValue, oldValue) {
        this.$nextTick(() => {
          this.createdSearch()
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    //传阅
    copyToClick() {
      this.buttonName = 'copyToClick'
      this.selectInstIds = ''
      let selectSelection = this.$refs.doneTable.selection
      if (selectSelection && selectSelection.length == 0) {
        this.$message.error('请选择要传阅的任务')
        return
      }
      for (let k = 0; k < selectSelection.length; k++) {
        this.selectInstIds = this.selectInstIds + selectSelection[k].id + ','
      }
      this.selectInstIds = this.selectInstIds.substring(
        0,
        this.selectInstIds.length - 1
      )
      this.$refs['copyToClick_EipUserDialog'].showDialog()
    },
    //转移
    divertClick() {
      this.buttonName = 'divertClick'
      this.selectInstIds = ''
      this.taskKeys = ''
      this.selectList = this.$refs.doneTable.selection
      if (this.selectList && this.selectList.length == 0) {
        this.$message.error('请选择要转移的已办')
        return
      }
      // for(let k = 0;k<selectSelection.length;k++){
      //     this.selectInstIds = this.selectInstIds + selectSelection[k].id+",";
      // }
      // this.selectInstIds = this.selectInstIds.substring(0,this.selectInstIds.length-1);
      this.$refs['divertClick_EipUserDialog'].showDialog()
    },
    //选择用户确认事件
    eipUserDialogOk(data) {
      if (this.buttonName == 'copyToClick') {
        if (data && data.length > 0) {
          let userId = ''
          for (let k = 0; k < data.length; k++) {
            if (data[k].id != this.data.typeValue.id) {
              userId = userId + data[k].id + ','
            }
          }
          userId = userId.substring(0, userId.length - 1)
          let map = {
            copyToType: '0',
            messageType: 'inner',
            opinion: '管理员传阅已办',
            userId: userId,
            instanceId: this.selectInstIds,
            files: ''
          }
          req
            .post(
              window.context.bpmRunTime + '/runtime/instance/v1/transToMore',
              map
            )
            .then(response => {
              if (response.data && response.data.state) {
                this.$message.success('设置传阅成功')
                this.createdSearch()
              }
            })
        }
      } else if (this.buttonName == 'divertClick') {
        if (data && data.length > 0) {
          if (this.data.typeValue.id == data[0].id) {
            this.$message.error('所选任务不能转移给自己')
            return
          }
          let map = {
            oldUserId: this.data.typeValue.id,
            oldUserName: this.data.typeValue.fullname,
            userId: data[0].id,
            userName: data[0].fullname,
            selectInst: this.selectList
          }
          req
            .post(
              window.context.bpmRunTime + '/runtime/instance/v1/divertDoneTask',
              map
            )
            .then(res => {
              if (res.data.state) {
                this.$message.success(res.data.message)
                this.createdSearch()
              }
            })
            .catch(() => {})
        }
      }
    },
    //动态计算列表高度
    // setMaxHeight(item) {
    //   const this_ = this
    //   setTimeout(() => {
    //     if (window.innerHeight) {
    //       this_.maxHeight = window.innerHeight
    //     } else if (document.body && document.body.clientHeight) {
    //       this_.maxHeight = document.body.clientHeight
    //     }
    //     this_.maxHeight = this_.maxHeight - item
    //   }, 10)
    // },
    //动态计算列表高度
    setMaxHeight(item) {
      const this_ = this
      setTimeout(() => {
        if (window.innerHeight) {
          this_.maxHeight = window.innerHeight
        } else if (document.body && document.body.clientHeight) {
          this_.maxHeight = document.body.clientHeight
        }
        this_.maxHeight = this_.maxHeight - item
      }, 10)
    },
    //Loading 加载中
    openFullScreen() {
      this.fullscreenLoading = true
    },
    handleSizeChange: function(size) {
      //每页下拉显示数据
      this.pagination.pageSize = size
      this.search()
    },
    handleCurrentChange: function(currentPage) {
      //点击第几页
      this.pagination.page = currentPage
      this.search()
    },
    //回车查询
    searchEnterFun: function(e) {
      var keyCode = window.event ? e.keyCode : e.which
      if (keyCode == 13) {
        this.search('find')
      }
    },
    // 查询
    search(str) {
      const this_ = this
      if (str == 'find') {
        this_.pagination.page = 1
      }
      let querys = [] //查询条件
      let queryFilter = {}
      let pageBean = {pageBean: this_.pagination}
      let beginDate = '' //开始时间
      let endDate = '' //结束时间
      let group = 'main' //判断条件
      if (this_.tableData) {
        querys = [
          {
            property: 'proc_def_name_',
            value: this_.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          },
          {
            property: 'subject_',
            value: this_.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          },
          {
            property: 'wfInst.id_',
            value: this_.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          }
        ]
      }
      if (this_.currentTree) {
        querys.push({
          property: 'type_id_',
          value: this.currentTree,
          group: 'typeId',
          operation: 'IN',
          relation: 'AND'
        })
      }
      if (this_.date) {
        beginDate = utils.formatDate(this_.date[0].getTime())
        endDate = utils.formatDate(this_.date[1].getTime())
        querys.push({
          property: 'wfInst.create_time_',
          value: [beginDate, endDate],
          group: 'time',
          operation: 'BETWEEN',
          relation: 'AND'
        })
      }
      queryFilter = {pageBean: this_.pagination, querys, sorter: this_.sorter}
      this_.openFullScreen()
      let account = this_.data.typeValue.account
      //初次加载默认pageBean
      req
        .post(
          window.context.bpmRunTime +
            '/runtime/instance/v1/getDoneListByAccount?account=' +
            account,
          queryFilter
        )
        .then(response => {
          if (response.data) {
            this_.rows = response.data.rows
            this_.pagination = {
              page: response.data.page,
              pageSize: response.data.pageSize,
              total: response.data.total
            }
          }
          //页面加载调用tudo.js里面的分页方法
          this_.fullscreenLoading = false
        })
        .catch(() => {
          this_.fullscreenLoading = false
        })
    },
    //重置
    reset() {
      this.tableData = ''
      this.date = ''
      this.search('find')
    },
    //子组件传值父组件(待办分类查询)
    getCurrent(data) {
      const this_ = this
      if (data.id == 6) {
        this_.currentTree = ''
        this_.openFullScreen()
        let pageBean = {pageBean: this_.pagination}
        let account = this_.data.typeValue.account
        //初次加载默认pageBean
        req
          .post(
            window.context.bpmRunTime +
              '/runtime/instance/v1/getDoneListByAccount?account=' +
              account,
            pageBean
          )
          .then(response => {
            if (response.data) {
              this_.rows = response.data.rows
              this_.pagination = {
                page: response.data.page,
                pageSize: response.data.pageSize,
                total: response.data.total
              }
            }
            //页面加载调用tudo.js里面的分页方法
            this_.fullscreenLoading = false
          })
          .catch(() => {
            this_.fullscreenLoading = false
          })
      } 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 account = this.data.typeValue.account
      return flow.getDoneCountByAccount(account)
    },
    createdSearch() {
      const this_ = this
      let querys = []
      let pageBean = {
        pageBean: {page: '1', pageSize: '10', showTotal: 'true'},
        querys: querys
      }
      let account = this_.data.typeValue.account
      //初次加载默认pageBean
      req
        .post(
          window.context.bpmRunTime +
            '/runtime/instance/v1/getDoneListByAccount?account=' +
            account,
          pageBean
        )
        .then(response => {
          if (response.data) {
            this_.rows = response.data.rows
            this_.pagination = {
              page: response.data.page,
              pageSize: response.data.pageSize,
              total: response.data.total
            }
          }
          //页面加载调用tudo.js里面的分页方法
          this_.fullscreenLoading = false
        })
        .catch(() => {
          this_.fullscreenLoading = false
        })
    }
  },
  created() {
    const this_ = this
    if (JSON.stringify(this_.data) == '{}') {
      return '请选择查询对象'
    }
    this_.setMaxHeight(300) //动态计算列表高度
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';
.el-container {
  background-color: #fff;
}
.el-row {
  margin-bottom: 20px;
}
.el-header {
  border-bottom: 1.5px solid #ededed;
}
.top-title {
  line-height: 58px;
  margin-left: 20px;
  font-size: 16px;
  color: #a2a2a2;
}
/deep/.el-tree {
  position: relative;
  cursor: default;
  background: #fff;
  color: #303133;
  font-size: 13px;
}
.query-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-bottom: 20px;
  &_right{
    display: flex;
  }
}
</style>
