<template>
  <div class="common-page-content">
    <div class="common-search-container">
      <el-form
        ref="form"
        v-form
        data-vv-scope="form"
        label-width="auto"
        label-position="right "
        :inline="true"
      >
        <el-form-item label="项目名称">
          <el-input
            size="small"
            clearable
            placeholder="项目名称"
            v-model="form.tableData"
            @keyup.enter.native="searchEnterFun"
          ></el-input>
        </el-form-item>
        <el-form-item label="发起企业">
          <el-input
            size="small"
            clearable
            placeholder="发起企业"
            v-model="form['org.name_']"
            @keyup.enter.native="searchEnterFun"
          ></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            size="small"
            v-model="form.date"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div class="container-btn">
        <el-button
          size="small"
          type="danger"
          icon="el-icon-search"
          @click="search('find')"
          >搜索</el-button
        >
        <el-button size="small" icon="el-icon-refresh" @click="reset"
          >重置</el-button
        >
      </div>
    </div>
    <el-row class="common-table-container flex searchPanel">
      <el-col :span="24" class="common-table-wrapper">
        <div class="common-table-content btn-pagenation" ref="contentPanel">
          <!-- default-sort  排序 -->
          <el-table
            :data="rows"
            border
            stripe
            fit
            size="mini"
            ref="htTable"
            @row-click="rowClick"
            @row-dblclick="handleDbClick"
            style="width: 100%;height:100%"
            header-cell-class-name="done-header-row"
            row-class-name="done-row"
            v-loading="fullscreenLoading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              label="标题"
              show-overflow-tooltip
              align="center"
              prop="subject"
            >
            </el-table-column>
            <el-table-column
              prop="orgName"
              width="160"
              show-overflow-tooltip
              align="center"
              label="发起企业"
            ></el-table-column>
            <el-table-column
              label="项目名称"
              show-overflow-tooltip
              align="center"
              width="160"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.bizNoticeName }}</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
              v-if="show"
              align="center"
              width="160"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.amount }}</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'
                  "
                  class="blue-color"
                  type="success"
                  >已办结</el-tag
                >
                <el-tag
                  v-if="
                    scope.row.status != 'end' && scope.row.status != 'manualend'
                  "
                  class="red-color"
                  type="danger"
                  >未办结</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 | formatDate }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="creator"
              label="发起人"
              width="100"
              align="center"
            ></el-table-column>
            <el-table-column label="流程图" width="70" align="center">
              <template slot-scope="scope">
                <el-button
                  @click="handleShowTaskImage(scope.row)"
                  icon="el-icon-connection"
                  plain
                  size="mini"
                ></el-button>
              </template>
            </el-table-column>
            <el-table-column width="150" label="操作" align="center">
              <template v-slot="{row}">
                <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="handleRowClick(row, false)"
                  icon="el-icon-view"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="common-pagenation">
          <el-pagination
            background
            class="bbsl-pagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.page"
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>

    <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>
    <!-- 流程图 -->
    <TaskImage
      ref="taskImage"
      :bpmnInstId="selectBpmnInstId"
      :instId="selectInstanceId"
      :defId="selectDefId"
    />
  </div>
</template>

<script>
import {mapState, mapActions} from 'vuex'
import process from '@/api/process'
import utils from '@/utils.js'
import TaskImage from '@/components/flow/task/taskImage.vue'
export default {
  name: 'doneRead',
  components: {
    TaskImage
  },
  props: {
    defKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isAsideShow: false,
      asideShow: false,
      form: {tableData: '', date: '', orgName: '', orgId: ''},
      currentTree: '',
      fullscreenLoading: true,
      dialogFormVisible: false,
      show: 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: {
    handleDbClick(row) {
      console.log(row)
      this.handleRowClick(row)
    },
    //将当前展开或者收起的值存在localStorage中
    handleSwitch(val) {
      localStorage.doneAsideShow = val
    },
    rowClick(row, column, event) {
      this.$refs.htTable.toggleRowSelection(row)
    },
    //批量勾选待办流程获取
    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'
          // },
          {
            property: 'bizNoticeName',
            value: this.form.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'AND'
          }
        ]
      }
      if (this.form['org.name_']) {
        querys.push({
          property: 'org.name_',
          value: this.form['org.name_'],
          group: 'main',
          operation: 'LIKE',
          relation: 'AND'
        })
      }
      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: '', orgName: ''}
      this.search('find')
    },
    handleRowClick(row, newWin) {
      //判断是否显示撤回按钮
      console.log(row)
      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',
    //     })
    // }
    if (this.currentTree) {
      querys.push({
        property: 'type_id_',
        value: this.currentTree,
        group: 'typeId',
        operation: 'IN',
        relation: 'AND'
      })
    }
    let pageBean = {
      pageBean: {page: '1', pageSize: '50', showTotal: 'true'},
      querys
    } //初次加载默认pageBean
    this.$store
      .dispatch('storeProcess/getDoneByPagination', pageBean)
      .then(() => {
        this.rows.forEach(item => {
          if (item.procDefKey == 'yetx') {
            this.show = true
          } else {
            this.show = false
          }
        })
        //页面加载调用done.js里面的分页方法
        this.fullscreenLoading = false
      })
  }
}
</script>

<style lang="scss" scoped>
.common-table-container {
  height: calc(100% - 10px);
}
.common-table-content.btn-pagenation {
  height: calc(100% - 60px);
}
.cloumn-btn {
  border: 1px solid #2761ff;
  padding: 3px 10px;
  border-radius: 5px;
  &:nth-child(1) {
    margin-right: 5px;
  }
  &:nth-child(2) {
    margin-right: 5px;
  }
  &:nth-child(1):hover {
    background-color: #2761ff;
    color: #fff;
  }
  &:nth-child(2):hover {
    background-color: #2761ff;
    color: #fff;
  }
  /deep/ i,
  span {
    font-size: 16px;
  }
}

/deep/ .el-tree-node__content {
  padding: 5px 0;
}
/deep/ .el-table thead tr th {
  background-color: #eee !important;
  border-right: 1px solid #dfe2e8 !important;
}
/deep/ .el-table {
  border-collapse: collapse !important;
}
</style>
