<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="项目名称"
            prefix-icon="el-icon-search"
            v-model="form.tableData"
            @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-item label="状态">
          <el-select
            size="small"
            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-item>
      </el-form>
      <div class="container-btn">
        <el-button size="small" type="danger" @click="search('find')"
          >查询</el-button
        >
        <el-button size="small" @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"
            style="width: 100%; height:100%"
            border
            stripe
            fit
            size="mini"
            ref="multipleSelection"
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
            :cell-style="{'text-align': 'center'}"
            :header-cell-style="{'text-align': 'center'}"
            v-loading="fullscreenLoading"
          >
            <el-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            ></el-table-column>

            <el-table-column
              prop="id"
              width="160"
              show-overflow-tooltip
              align="center"
              label="流程编号"
            ></el-table-column>
            <el-table-column
              prop="orgName"
              width="160"
              show-overflow-tooltip
              align="center"
              label="发起企业"
            ></el-table-column>
            <el-table-column
              prop="bizNoticeName"
              width="160"
              show-overflow-tooltip
              align="center"
              label="项目名称"
            ></el-table-column>
            <el-table-column label="标题" prop="subject" show-overflow-tooltip>
            </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 label="流程图" width="70" align="center">
              <template slot-scope="scope">
                <el-button
                  @click="handleShowTaskImage(scope.row)"
                  icon="el-icon-connection"
                  size="mini"
                ></el-button>
              </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-else-if="
                    scope.row.status == 'end' &&
                      scope.row.typeId == 1590187623949930496
                  "
                  style="color:#318409"
                  >提现成功</span
                >
                <span
                  v-else-if="
                    scope.row.status == 'manualend' &&
                      scope.row.typeId == 1590187623949930496
                  "
                  style="color:#f71010"
                  >提现失败</span
                >
                <span
                  v-else-if="
                    (scope.row.status == 'end' &&
                      scope.row.typeId !== 1590187623949930496) ||
                      (scope.row.status == 'manualend' &&
                        scope.row.typeId !== 1590187623949930496)
                  "
                  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 == 'draft'"
                  size="mini"
                  type="primary"
                  plain
                  @click="deleteDraft(scope.row.id)"
                  >删除草稿</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="handleRowClick(scope.row, false)"
                  icon="el-icon-view"
                >
                  详情
                </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="primary"
                  plain
                  @click="deleteBpm(scope.row.id)"
                  >删除</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, 50, 100]"
            :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 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: {
    rowClick() {},
    handleSelectionChange() {},
    //将当前展开或者收起的值存在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: 'bizNoticeName',
            value: this.form.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          })
        }
        if (beginDate && endDate) {
          querys.push({
            property: 'createTime',
            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')
    },
    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)
    },
    handleDbClick(row) {
      console.log(row)
      this.handleRowClick(row)
    },
    handleRowClick(row, newWin) {
      //判断是否显示撤回按钮
      console.log(row)
      let type = 'request'
      // 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')
    },
    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: '50', 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>
.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>
