<template>
  <div class="fullheight">
    <ht-table
      @load="loadData"
      :data="data"
      :pageResult="pageResult"
      :selection="true"
      :show-export="false"
      :quick-search-props="[
        {prop: 'subject', label: '流程标题'},
        {prop: 'procDefName', label: '流程名称'},
        {prop: 'ID_', label: '流程编号'}
      ]"
      ref="htTable"
      @row-click="rowClick"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:toolbar>
        <!-- <el-button-group> -->
        <el-button
          icon="el-icon-document-add"
          :disabled="isDisabled"
          @click="batchRestore"
          >恢复</el-button
        >
        <el-button icon="el-icon-document-add" @click="openDelete()"
          >删除记录</el-button
        >
        <el-button
          class="ht-delete-button"
          icon="el-icon-delete"
          @click="completelyRemove"
          :disabled="isDisabled"
          >彻底删除</el-button
        >
        <!-- </el-button-group> -->
      </template>
      <template v-slot:search>
        <ht-table-search-panel
          :divide="3"
          :label-width="100"
          display-style="block"
        >
          <ht-table-search-field label="流程编号" prop="ID_" />
          <ht-table-search-field label="流程标题" prop="subject" />
          <ht-table-search-field label="流程名称" prop="procDefName" />
          <ht-table-search-field label="发起人" prop="creator" />
          <ht-table-search-field
            type="daterange"
            label="创建时间"
            prop="createTime"
            operation="BETWEEN"
          />
        </ht-table-search-panel>
      </template>

      <template #default>
        <ht-table-column type="index" width="50" align="center" label="序号" />
        <ht-table-column
          prop="id"
          label="流程编号"
          :hiden="true"
          width="200"
          show-overflow-tooltip
          :sortable="true"
        />
        <ht-table-column
          prop="subject"
          label="流程标题"
          :show-overflow-tooltip="true"
        ></ht-table-column>
        <ht-table-column
          prop="createTime"
          label="创建时间"
          width="200"
          :sortable="true"
        />
        <ht-table-column prop="creator" label="发起人" width="120" />
        <ht-table-column
          prop="updateTime"
          label="删除时间"
          width="200"
          :sortable="true"
        />
        <ht-table-column align="left" label="操作" width="180">
          <template v-slot="{row}">
            <el-button type="text" @click="handleRestore(row.id)"
              >恢复</el-button
            >
            <el-button type="text" @click.stop="handleDelete(row)"
              >彻底删除</el-button
            >
          </template>
        </ht-table-column>
      </template>
    </ht-table>

    <el-dialog
      width="80%"
      title="流程删除记录"
      :visible="dialogVisible"
      :before-close="handleClose"
      :close-on-click-modal="true"
      custom-class="form_dialog"
    >
      <template>
        <ht-table
          @load="loadFormData"
          :data="formData"
          :pageResult="formPageResult"
          :selectable="false"
          :show-export="false"
          :show-custom-column="false"
          :default-sorter="[{direction: 'DESC', property: 'DELETE_TIME_'}]"
          quick-search-props="fullname"
          v-if="dialogVisible"
        >
          <template #search>
            <ht-table-search-panel
              :divide="3"
              :label-width="90"
              display-style="block"
            >
              <ht-table-search-field
                label="删除人"
                prop="fullname"
                operation="LIKE"
              />
              <ht-table-search-field
                label="删除时间"
                prop="DELETE_TIME_"
                type="datetimerange"
                operation="BETWEEN"
              />
            </ht-table-search-panel>
          </template>
          <template>
            <ht-table-column type="index" label="序号"></ht-table-column>
            <ht-table-column
              prop="fullname"
              label="删除人"
              width="200"
              :show-overflow-tooltip="true"
            ></ht-table-column>
            <ht-table-column prop="account" label="账号" width="120" />
            <ht-table-column
              prop="deleteTime"
              label="删除时间"
              :sortable="true"
              width="200"
            />
            <ht-table-column
              prop="instSubject"
              label="删除对象"
              show-overflow-tooltip
            />
            <ht-table-column
              prop="content"
              label="删除原因"
              show-overflow-tooltip
            />
          </template>
        </ht-table>
      </template>
    </el-dialog>
    <!-- 流程催办 -->
    <InstanceUrgent ref="instanceUrgent" />
    <!-- 彻底删除弹窗 -->
    <el-dialog
      title="彻底删除"
      :visible.sync="thoroughDialogVisible"
      :before-close="handleCloseThoroughDialog"
      custom-class="thorough-dialog"
      width="60%"
    >
      <div class="tip-message">
        该操作会删除流程实例与表单所有相关数据，且一经删除不可恢复，请谨慎操作！
      </div>
      <el-scrollbar
        class="scrollbar-fullheight"
        :wrapStyle="[{maxHeight: '550px'}]"
      >
        <h4 class="del-flow__title">彻底删除流程：</h4>
        <el-table :data="selectedList" border style="width: 100%">
          <el-table-column prop="id" label="流程编号" width="180">
          </el-table-column>
          <el-table-column prop="subject" label="流程名称"> </el-table-column>
          <el-table-column prop="address" width="200" label="操作">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleCancelDel(row)"
                >取消删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-form
          data-vv-scope="thorough-form"
          v-form="{inputsDisplay: 'block', formItemAlign: 'left'}"
        >
          <ht-form-item label="删除人">
            <span>{{ currentUser.username }}</span>
          </ht-form-item>
          <ht-form-item label="删除时间">
            <span>{{ currentDate }}</span>
          </ht-form-item>
          <ht-form-item label="删除表单数据">
            <el-checkbox v-model="isRemoveBo"></el-checkbox>
          </ht-form-item>
          <ht-form-item label="删除原因">
            <ht-input
              validate="required"
              type="textarea"
              placeholder="请输入删除原因"
              v-model="content"
              maxlength="500"
              show-word-limit
            ></ht-input>
          </ht-form-item>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseThoroughDialog">取 消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
          :loading="confirmLoading"
          >确定删除</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import flow from '@/api/flow.js'
import form from '@/api/form.js'
import req from '@/request.js'
import moment from 'moment'
const InstanceUrgent = () => import('@/views/flow/InstanceUrgent.vue')
import EipUserDialog from '@/components/dialog/EipUserDialog.vue'
import {mapState} from 'vuex'
const InstanceDetail = () => import('@/views/flow/InstanceDetail.vue')

export default {
  components: {
    EipUserDialog,
    InstanceDetail,
    InstanceUrgent
  },
  data() {
    return {
      data: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      formData: [],
      formPageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      querys: [
        {
          property: 'isDele',
          value: 1,
          operation: 'EQUAL',
          group: 'queryStr',
          relation: 'AND'
        }
      ],
      loadDataUrl: '',
      dialogVisible: false,
      statusArray: [
        {text: '运行中', value: 'running', type: 'success'},
        {text: '结束', value: 'end', type: 'info'},
        {text: '草稿', value: 'draft', type: 'info'},
        {text: '驳回', value: 'back', type: 'danger'},
        {text: '驳回到发起人', value: 'backToStart', type: 'danger'},
        {text: '撤回', value: 'revoke', type: 'warning'},
        {text: '撤回到发起人', value: 'revokeToStart', type: 'warning'},
        {text: '人工终止', value: 'manualend', type: 'info'},
        {text: '管理员结束', value: 'adminmanualend', type: 'info'}
      ],
      curInstance: '',
      isDisabled: true,
      selectedList: [],
      thoroughDialogVisible: false,
      content: '',
      confirmLoading: false,
      isRemoveBo: true,
      tableData: []
    }
  },
  computed: {
    ...mapState('login', ['currentUser']),
    isForbidden: function() {
      return [
        {text: '正常', value: 0, type: 'info'},
        {text: '挂起', value: 1, type: 'danger'}
      ]
    },
    deleteUrl: function() {
      return window.context.bpmRunTime + '/runtime/instance/v1/remove'
    },
    saveRoleUrl: function() {
      let preUrl = window.context.uc + '/api/role/v1/role'
      if (this.role.id) {
        preUrl += '/updateRole'
      } else {
        preUrl += '/addRole'
      }
      return preUrl
    },
    currentDate() {
      return moment().format('YYYY-MM-DD HH:mm:ss')
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  },
  methods: {
    rowClick(row, column, event) {
      this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
    },
    handleSelectionChange(selection) {
      this.selectedList = selection
      this.isDisabled = selection.length > 0 ? false : true
    },
    handleCloseThoroughDialog() {
      this.thoroughDialogVisible = false
    },
    handleConfirm() {
      if (!this.content) return this.$message.warning('请输入删除原因')
      const params = this.selectedList.map(item => {
        return {
          id: item.id,
          subject: `${item.subject}(${item.id})`
        }
      })
      this.confirmLoading = true
      flow
        .completelyRemove(params, this.content, this.isRemoveBo)
        .then(({data}) => {
          if (data.state) {
            this.$message.success(data.message)
            this.$refs.htTable.load()
          } else {
            this.$message.error(data.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
          this.thoroughDialogVisible = false
        })
    },
    handleDelete(row) {
      this.selectedList = []
      this.content = ''
      this.isRemoveBo = true
      this.selectedList.push(row)
      this.thoroughDialogVisible = true
    },
    deleteInstance(params) {
      if (!this.content) return this.$message.warning('请输入删除原因')
      this.confirmLoading = true
      flow
        .completelyRemove(params, this.content, this.isRemoveBo)
        .then(({data}) => {
          if (data.state) {
            this.$message.success(data.message)
            this.$refs.htTable.load()
          } else {
            this.$message.error(data.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
          this.thoroughDialogVisible = false
        })
    },
    handleCancelDel(row) {
      const currentIndex = this.selectedList.findIndex(
        item => item.id === row.id
      )
      this.selectedList.splice(currentIndex, 1)
    },
    batchRestore() {
      const ids = this.selectedList.map(item => item.id)
      this.handleRestore(ids.join(','))
    },
    openDelete() {
      this.dialogVisible = true
    },
    handleClose() {
      this.dialogVisible = false
    },
    handleCloseMenuPerm() {
      this.dialogVisibleMenuPerm = false
    },
    dialogCancle(dialogVisible) {
      this[dialogVisible] = false
    },
    loadData(param, cb) {
      if (!param.querys) {
        param.querys = this.querys
      } else {
        param.querys = [...param.querys, ...this.querys]
      }
      flow
        .getInstPage(param)
        .then(response => {
          this.data = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => cb())
    },
    loadFormData(param, cb) {
      flow
        .getInstDeleteLogPage(param)
        .then(response => {
          this.formData = response.rows
          this.formPageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => cb())
    },
    handleCommand(params) {
      switch (params.command) {
        case 'restore': //恢复
          this.restore(params.row.id)
          break
      }
    },
    //终止流程
    completelyRemove() {
      this.content = ''
      this.isRemoveBo = true
      this.thoroughDialogVisible = true
      // let this_ = this
      // if(!row){
      //   this_.$message.error("请选择一条数据或多条数据");
      //   return
      // }
      // this.$prompt(
      //   '说明:该操作会删除流程实例与表单所有相关数据，并且',
      //   '彻底删除',
      //   {
      //     inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
      //     showCancelButton: false,
      //     inputErrorMessage: '终止原因不能为空'
      //   }
      // )
      //   .then(({value}) => {
      //     this_.$http
      //       .get(
      //         '${bpmRunTime}/runtime/instance/v1/doEndProcessById?id=' +
      //           row.id +
      //           '&reason=' +
      //           value
      //       )
      //       .then(function(resp) {
      //         let data = resp.data
      //         if (data.state) {
      //           this_.$message.success('操作成功')
      //           this_.$refs.htTable.load()
      //         } else {
      //           this_.$message.error(data.mesage || '操作失败')
      //         }
      //       })
      //   })
      //   .catch(() => {})
    },
    //终止恢复流程
    renewProcess(row) {
      let this_ = this
      this.$prompt('', '请输入终止恢复原因', {
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        showCancelButton: false,
        inputErrorMessage: '终止恢复原因不能为空'
      })
        .then(({value}) => {
          this_.$http
            .get(
              '${bpmRunTime}/runtime/instance/v1/renewProcess?id=' +
                row.id +
                '&reason=' +
                value
            )
            .then(function(resp) {
              let data = resp.data
              if (data.state) {
                this_.$message.success('操作成功')
                this_.$refs.htTable.load()
              } else {
                this_.$message.error(data.mesage || '操作失败')
              }
            })
        })
        .catch(() => {})
    },
    //流程催办
    instanceUrgent(row) {
      this.$refs.instanceUrgent.handleOpen(row.id, row.procDefId, row.subject) //父组件调用子组件方法
    },
    forbiddenOrUnForbiddenInst(row) {
      let this_ = this
      flow.forbiddenOrUnForbiddenInst(row).then(response => {
        if (response.state) {
          this_.$message.success(response.message)
          row.isForbidden = row.isForbidden == '1' ? '0' : '1'
        }
      })
    },
    handleRestore(id) {
      let this_ = this
      req
        .get(
          window.context.bpmRunTime + '/runtime/instance/v1/restore?id=' + id
        )
        .then(function(response) {
          let data = response.data
          if (data.state) {
            this_.$message.success(data.message)
            this_.$refs.htTable.load(true)
          } else {
            this_.$message.fail(data.message)
          }
        })
    },
    afterDelete() {
      this.$refs.htTable.load()
    }
  }
}
</script>
<style lang="scss" scoped>
.tip-message {
  height: 40px;
  line-height: 40px;
  background: rgba(255, 174, 68, 0.1);
  border-radius: 2px;
  font-size: 14px;
  color: #ffae44;
  padding-left: 16px;
  text-align: left;
}
.del-flow__title {
  margin: 0;
  padding: 24px 0 16px 0;
  color: #888;
  font-size: 14px;
  font-weight: normal;
}
::v-deep {
  .thorough-dialog {
    .el-dialog__header {
      .el-dialog__title {
        color: #222;
        font-size: 16px;
        font-weight: bold;
      }
    }
    .el-dialog__body {
      padding: 0px 30px 20px;
      .el-form {
        padding-top: 24px;
        .el-form-item__label {
          font-size: 14px;
          color: #888;
        }
      }
    }
    .el-dialog__footer {
      .dialog-footer {
        text-align: right;
      }
    }
  }
  .form_dialog {
    .search-panel__container {
      overflow-x: unset;
    }
  }
}
/deep/ .el-textarea .el-input__count {
  height: 12px;
  line-height: 12px;
}
::v-deep{
  .scrollbar-fullheight{
    .el-scrollbar__view{
      width: calc(100% - 2px);
    }
  }
}
</style>
