<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
      v-if="!$route.meta.single"
      class="navbar-collapse"
      :class="{'navbar-collapse-right': !asideShow}"
      @click="asideShow = !asideShow"
    >
      <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>
          <el-select
            class="form_status"
            v-model="form.statusData"
            @change="statusChange"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </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-col>
        </el-row>
      </div>
      <el-main class="content">
        <!-- default-sort  排序 -->
        <el-table
          :data="rows"
          style="width: 100%"
          header-cell-class-name="myRequest-header-row"
          row-class-name="myRequest-row"
          size="medium"
          v-loading="fullscreenLoading"
          :default-sort="{prop: 'status,createTime', order: 'descending'}"
        >
          <el-table-column
            type="index"
            width="50"
            align="center"
            label="序号"
          ></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="myRequest-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="150"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.procDefName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            width="150"
          >
            <template slot-scope="scope">
              <span> {{ scope.row.createTime | formatDate }} </span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="creator" label="发起人" align="center" width="180"></el-table-column> -->
          <el-table-column width="110" align="center" label="状态">
            <template slot-scope="scope">
              <span
                v-if="
                  scope.row.status == 'revoke' ||
                    scope.row.status == 'revokeToStart' ||
                    scope.row.status == 'back' ||
                    scope.row.status == 'backToStart'
                "
                style="color:#f71010"
                >{{ myRequestStatus[scope.row.status] }}</span
              >
              <span v-if="scope.row.status == 'draft'" style="color:#c2a437">{{
                myRequestStatus[scope.row.status]
              }}</span>
              <span
                v-if="scope.row.status == 'running'"
                style="color:#318409"
                >{{ myRequestStatus[scope.row.status] }}</span
              >
              <span
                v-if="
                  scope.row.status == 'end' || scope.row.status == 'manualend'
                "
                style="color:#909399"
                >{{ myRequestStatus[scope.row.status] }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="150"
            v-if="showOperation"
          >
            <template slot-scope="scope">
              <!-- <el-button
                v-if="
                  scope.row.status == 'running' ||
                    scope.row.status == 'back' ||
                    scope.row.status == 'revoke'
                "
                size="mini"
                type="danger"
                @click="handleRevoke(scope.row.id, scope.row.status)"
                >撤回</el-button
              > -->
              <el-button
                v-if="scope.row.status == 'draft'"
                size="mini"
                type="danger"
                @click="deleteDraft(scope.row.id)"
                >删除草稿</el-button
              >
              <el-button
                v-if="
                  scope.row.status == 'manualend' ||
                    scope.row.status == 'revokeToStart' ||
                    scope.row.status == 'backToStart' ||
                    (scope.row.status == 'back' &&
                      scope.row.backToStart == true)
                "
                size="mini"
                type="danger"
                @click="deleteBpm(scope.row.id)"
                >删除</el-button
              >
              <el-button
                style="margin-top: 5px;"
                v-if="
                  scope.row.status == 'revokeToStart' ||
                    scope.row.status == 'backToStart' ||
                    (scope.row.status == 'back' &&
                      scope.row.backToStart == true)
                "
                size="mini"
                type="danger"
                @click="doEndProcessById(scope.row.id)"
                >终止</el-button
              >
            </template>
          </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>
    </el-container>
    <!-- 流程图 -->
    <TaskImage
      ref="taskImage"
      :bpmnInstId="selectBpmnInstId"
      :instId="selectInstanceId"
      :defId="selectDefId"
    />
  </el-container>
</template>

<script>
import {mapState, mapActions} from 'vuex'
import FlowTree from '@/components/flow/flowTree.vue'
import utils from '@/utils.js'
import process from '@/api/process.js'
import TaskImage from '@/components/flow/task/taskImage.vue'
const MY_REQUEST_STATUS = {
  revoke: '撤回',
  revokeToStart: '撤回到发起人',
  draft: '草稿',
  running: '运行中',
  end: '结束',
  manualend: '人工结束',
  back: '驳回',
  backToStart: '驳回到发起人'
}

export default {
  name: 'myRequest',
  components: {
    FlowTree,
    TaskImage
  },
  props: {
    defKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      myRequestStatus: MY_REQUEST_STATUS,
      isAsideShow: false,
      asideShow: false,
      form: {tableData: '', date: '', statusData: ''},
      fullscreenLoading: true,
      dialogFormVisible: false,
      opinion: '',
      currentTree: '',
      id: '',
      statusData: '',
      options: [
        {
          value: '',
          label: '请选择状态'
        },
        {
          value: 'revoke',
          label: '撤回'
        },
        {
          value: 'draft',
          label: '草稿'
        },
        {
          value: 'back',
          label: '驳回'
        },
        {
          value: 'end',
          label: '结束'
        },
        {
          value: 'running',
          label: '运行中'
        }
      ],
      showOperation: false,
      selectInstanceId: '',
      selectDefId: '',
      selectBpmnInstId: ''
    }
  },
  computed: {
    ...mapState('storeProcess', ['rows', 'pagination', 'total']),
    currentSwitchValue() {
      return (
        localStorage.myRequestAsideShow === 'true' ||
        localStorage.myRequestAsideShow === true
      )
    }
  },
  methods: {
    //将当前展开或者收起的值存在localStorage中
    handleSwitch(val) {
      localStorage.myRequestAsideShow = val
    },
    //选择状态查询
    statusChange(value) {
      this.form.statusData = value
      this.search('find')
    },
    handleClose(done) {
      this.dialogFormVisible = true
    },
    //逻辑删除流程实例
    deleteBpm(id) {
      this.$confirm('确认删除此流程?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        this.$store.dispatch('storeProcess/restore', id).then(() => {
          this.search('find')
        })
      })
    },
    //终止流程
    doEndProcessById(id) {
      this.$confirm('确认终止此流程?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        this.$store.dispatch('storeProcess/doEndProcessById', id).then(() => {
          this.search('find')
        })
      })
    },
    //删除草稿
    deleteDraft(id) {
      this.$store.dispatch('storeProcess/removeDraftById', id).then(() => {
        this.search('find')
      })
    },
    //撤回到发起人
    handleRevoke(id, status) {
      if (status == 'revokeToStart') {
        this.$message.warning('已撤回，不能再撤回')
        return false
      }
      this.dialogFormVisible = true
      this.id = id
    },
    saveRevoke() {
      if (this.opinion == '') {
        this.$message.warning('请填写撤回意见')
        return false
      }
      let data = {
        instanceId: this.id,
        isHandRevoke: false,
        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 == '' &&
        this.form.statusData == '' &&
        (this.form.date == '' || this.form.date == null)
      ) {
        if (this.currentTree != '') {
          querys = [
            {
              property: 'type_id_',
              value: this.currentTree,
              group: 'typeId',
              operation: 'IN',
              relation: 'AND'
            }
          ]
        }
      } else {
        if (
          this.form.tableData != '' &&
          this.form.statusData != '' &&
          this.form.date != '' &&
          this.form.date != null
        ) {
          group = 'time'
        }
        if (this.form.date != null && this.form.date != '') {
          beginDate = utils.formatDate(this.form.date[0].getTime())
          endDate = utils.formatDate(this.form.date[1].getTime())
        }
        if (this.form.tableData) {
          querys.push({
            property: 'proc_def_name_',
            value: this.form.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          })
          querys.push({
            property: 'subject_',
            value: this.form.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          })
          querys.push({
            property: 'bpm_pro_inst.id_',
            value: this.form.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          })
        }
        if (beginDate && endDate) {
          querys.push({
            property: 'create_time_',
            value: [beginDate, endDate],
            group: group,
            operation: 'BETWEEN',
            relation: 'AND'
          })
        }

        if (this.form.statusData) {
          querys.push({
            property: 'status_',
            value: this.form.statusData,
            group: 'status',
            operation: 'LIKE',
            relation: 'AND'
          })
        }

        if (this.currentTree) {
          querys.push({
            property: 'type_id_',
            value: this.currentTree,
            group: 'typeId',
            operation: 'IN',
            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/getMyRequestByPagination', queryFilter)
        .then(() => {
          this.fullscreenLoading = false
        })
    },
    //重置
    reset() {
      this.form = {tableData: '', date: '', statusData: ''}
      this.search('find')
    },
    handleRowClick(row, newWin) {
      if (this.defKey) {
        this.handleOpenUrl(
          '/sysModuleInst/' + row.id + '/request/' + this.defKey,
          newWin
        )
      }
      if (row.status == 'draft') {
        this.handleOpenUrl('/start/' + row.procDefId + '/' + row.id, newWin)
      } else if (row.status == 'end' || row.status == 'manualend') {
        this.handleOpenUrl('/instRead/' + row.id + '/myRequest', newWin)
      } else {
        this.handleOpenUrl('/inst/' + row.id + '/request', 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.openFullScreen()
        this.currentTree = ''
        let pageBean = {pageBean: this.pagination}
        this.$store
          .dispatch('storeProcess/getMyRequestByPagination', pageBean)
          .then(() => {
            //页面加载调用myRequest.js里面的分页方法
            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 pageBean = {}
      return process.getMyRequestCount(pageBean)
    },
    checkOperationShow(data) {
      //draft manualend revokeToStart backToStart back revokeToStart backToStart back(&&backToStart==true)
      //是否显示操作列
      if (!data || data.length == 0) {
        this.showOperation = false
        return
      }
      let arr = [
        'draft',
        'manualend',
        'revokeToStart',
        'backToStart',
        'revokeToStart'
      ]
      for (let i = 0; i < data.length; i++) {
        let row = data[i]
        if (
          (row.status == 'back' && row.backToStart == true) ||
          arr.includes(row.status)
        ) {
          this.showOperation = true
          return
        }
      }
      this.showOperation = false
    },
    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/getMyRequestByPagination', pageBean)
      .then(() => {
        //页面加载调用myRequest.js里面的分页方法
        this.fullscreenLoading = false
      })
  },
  watch: {
    rows(newValue, oldValue) {
      this.checkOperationShow(newValue)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.el-table ::v-deep th.myRequest-header-row {
  background-color: #fafafa;
  font-size: 13px;
}

.el-table ::v-deep tr.myRequest-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;
}

.myRequest-subject {
  cursor: pointer;
}

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

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

::v-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;

    ::v-deep .el-input__prefix,
    ::v-deep .el-input__suffix {
      height: 32px;
    }
    .form_input {
      margin-right: 10px;
    }
    .form_date_picker {
      margin-right: 10px;
      min-width: 300px;
    }
    .form_status {
      margin-right: 10px;
      min-width: 200px;
    }
  }
}
</style>
