<template>
  <div class="my-request">
    <ht-table
      ref="htTable"
      :data="tableData"
      :page-result="pageResult"
      :selectable="false"
      :quick-search-props="quickSearchProps"
      :quick-search-width="300"
      :show-export="false"
      :row-class-name="rowClassName"
      :header-cell-class-name="headerCellClassName"
      pagination-justify="end"
      :show-custom-column="false"
      :page-sizes="pageSizes"
      @load="loadData"
    >
      <template #search>
        <ht-table-search-panel
          :divide="3"
          :label-width="80"
          display-style="block"
        >
          <ht-table-search-field
            :label="$t('myRequest.SerialNumber')"
            prop="bpm_pro_inst.id_"
            operation="LIKE"
          />
          <ht-table-search-field
            :label="$t('myRequest.flowSubject')"
            prop="subject_"
            operation="LIKE"
          />
          <ht-table-search-field
            :label="$t('myRequest.flowProcDefName')"
            prop="proc_def_name_"
            operation="LIKE"
          />
          <ht-table-search-field
            :label="$t('myRequest.flowCreateTime')"
            prop="create_time_"
            type="daterange"
            operation="BETWEEN"
          />
          <!-- <ht-table-search-field
            label="状态"
            prop="status_"
            type="select"
            :options="statusOptions"
          /> -->
        </ht-table-search-panel>
      </template>
      <template #default>
        <ht-table-column
          type="index"
          width="50"
          align="center"
          :label="$t('myRequest.index')"
          fixed="left"
        />
        <ht-table-column
          prop="id"
          align="left"
          :label="$t('myRequest.SerialNumber')"
          width="180"
          show-overflow-tooltip
          fixed="left"
        >
          <template #default="{ row }">
            <div class="instance-id_wrap">
              {{ row.id }}
              <span
                class="copy-icon"
                @click="(event) => clipboard(row.id, event)"
              >
                <i class="icon-copy"></i>
              </span>
            </div>
          </template>
        </ht-table-column>
        <ht-table-column
          :label="$t('myRequest.flowChart')"
          width="70"
          align="center"
          fixed="left"
        >
          <template #default="{ row }">
            <div class="process-box">
              <ht-icon
                name="process"
                class="process-icon"
                @click="handleShowFlowChart(row)"
              ></ht-icon>
            </div>
          </template>
        </ht-table-column>
        <ht-table-column
          :label="$t('myRequest.flowSubject')"
          align="left"
          min-width="300"
          show-overflow-tooltip
          fixed="left"
        >
          <template #default="{ row }">
            <span class="subject" @click="handleClick(row)">
              {{ row.subject }}
            </span>
          </template>
        </ht-table-column>
        <ht-table-column
          :label="$t('myRequest.flowNodeName')"
          show-overflow-tooltip
          align="left"
          width="120"
        >
          <template #default="{ row }">
            <span v-if="extraField[row.id] && extraField[row.id].nodeName">
              <span
                v-for="(name, index) in extraField[row.id].nodeName"
                :key="`node-name_${row.id}_${index}`"
                class="flowlist-node-name"
              >
                {{ name }}
              </span>
            </span>
          </template>
        </ht-table-column>
        <ht-table-column
          align="left"
          prop="procDefName"
          :label="$t('myRequest.flowProcDefName')"
          width="160"
          show-overflow-tooltip
        />
        <ht-table-column
          align="left"
          prop="createTime"
          :label="$t('myRequest.flowCreateTime')"
          width="160"
          show-overflow-tooltip
        ></ht-table-column>
        <ht-table-column
          align="left"
          :label="$t('myRequest.flowStatus')"
          width="160"
          prop="status_"
          show-overflow-tooltip
          :render-header="renderHeaderMethod"
          :filters="statusArr"
        >
          <template #default="{ row }">
            <span
              :class="{
                'grey-color': ['end', 'manualend'].includes(row.status),
              }"
            >
              <ht-icon
                name="dot"
                :class="statusDotClassName[row.status]"
              ></ht-icon>
              {{ requestStatus[row.status] }}
            </span>
          </template>
        </ht-table-column>
        <ht-table-column
          v-if="isShowOperation"
          :label="$t('myRequest.operation')"
          align="center"
          width="100"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              v-if="isTerminationBtn(row)"
              size="mini"
              type="text"
              @click="handleTermination(row.id)"
            >
              终止
            </el-button>
            <el-button
              v-if="isShowDelBtn(row)"
              size="mini"
              type="text"
              class="red-color"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </ht-table-column>
      </template>
    </ht-table>
    <ht-flow-chart
      ref="flowChart"
      :inst-id="instanceId"
      :bpmn-inst-id="bpmnInstId"
    />
        <processForecast
      ref="processForecast"
      :inst-id="instanceId"
      :def-id="defId"
      :node-id="nodeId"
      :bpmn-inst-id="bpmnInstId"
    ></processForecast>
  </div>
</template>

<script>
  import matter from '@/mixins/matter'
  import tableHeight from '@/mixins/tableHeight'
  import nodeAndApprover from '@/mixins/nodeAndApprover'
  import tableHeaderFilter from '@/mixins/tableHeaderFilter'
 import processForecast from '@/views/matter/processForecast/processForecast.vue'

  import {
    getMyRequestList,
    deleteInstById,
    terminationProcess,
    getMyRequestTask,
  } from '@/api/process'

  import {
    MY_REQUEST_STATUS,
    REQUEST_DEFAULT_QUERY,
    STATUS_OPTION,
    STATUS_DOT_CLASS_NAME,
  } from './const'

  export default {
    name: 'MyRequest',
    components: {processForecast},
    mixins: [matter, tableHeight, nodeAndApprover, tableHeaderFilter],
    data() {
      return {
        tableData: [],
        isShowOperation: false,
        requestStatus: MY_REQUEST_STATUS,
        quickSearchProps: REQUEST_DEFAULT_QUERY,
        // statusOptions: STATUS_OPTION,
        statusDotClassName: STATUS_DOT_CLASS_NAME,
      }
    },
    computed: {
      isShowDelBtn() {
        return (row) => {
          const { status, backToStart } = row
          const hasStatus = [
            'revokeToStart',
            'manualend',
            'backToStart',
          ].includes(status)
          return hasStatus || (status === 'back' && backToStart)
        }
      },
      isTerminationBtn() {
        return (row) => {
          const { status, backToStart } = row
          const hasStatus = ['revokeToStart', 'backToStart'].includes(status)
          return hasStatus || (status === 'back' && backToStart)
        }
      },
      defaultQueryList() {
        const statusList = ['revoke', 'back', 'running', 'end']
        const list = statusList.map((item) => {
          return {
            property: 'status_',
            value: item,
            group: 'status',
            operation: 'LIKE',
            relation: 'OR',
          }
        })
        if (this.$route.query && this.$route.query.flowKey) {
          list.push({
            property: 'proc_def_key_',
            value: this.$route.query.flowKey,
            operation: 'EQUAL',
            group: 'main',
            relation: 'AND',
          })
        }
        return list
      },
      statusArr() {
        return Object.keys(this.requestStatus)
          .filter((status) => status != 'draft')
          .map((item) => {
            return {
              text: this.requestStatus[item],
              value: item,
            }
          })
      },
    },
    watch: {
      tableData(val) {
        val?.length > 0 && this.loadTaskInfo(val)
      },
    },
    activated() {
      this.$refs.htTable.load(true)
    },
    methods: {
      loadData(param, cb) {
        const data = {
          pageBean: this.pageResult,
          ...param,
          querys: [
            ...this.defaultQueryList,
            ...this.getCurrentQuery(param, 'type_id_'),
          ],
        }
        getMyRequestList(data)
          .then((res) => {
            if (!res) return
            const { rows, page, pageSize, total } = res
            this.tableData = rows || []
            this.handleIsShowOperate(this.tableData)
            this.pageResult = {
              page,
              pageSize,
              total,
            }
            this.$nextTick(() => {
              this.$refs.htTable && this.$refs.htTable.$refs.htTable.doLayout()
            })
          })
          .finally(() => cb?.())
      },
      handleIsShowOperate(data) {
        const statusList = [
          'draft',
          'manualend',
          'revokeToStart',
          'backToStart',
          'revokeToStart',
        ]
        data?.map((item) => {
          if (
            (item.status === 'back' && item.backToStart) ||
            statusList.includes(item.status)
          ) {
            this.isShowOperation = true
          }
        })
      },
      handleClick(row) {
        /*
        //获取我的请求对应实例的任务
        分两种情况：
        1、如果包含退回发起人/驳回发起人，进入我的申请，如果单据退回发起人/驳回发起人状态，直接进入待办
        2、如果情况1不满足，进入只读状态查看我的审批单，可关闭或撤回（根据按钮权限渲染）
        */
        getMyRequestTask(row.id).then((res) => {
          let task = res.value
          if (task && task.id) {
            this.$router.push({
              path: '/matter/approvalForm',
              query: {
                taskId: task.id,
                instId: row.id,
                isGetApprovalBtn: true,
                myApplication: true,
                type: 'request',
              },
            })
          } else {
            this.$router.push({
              path: '/matter/approvalForm',
              query: {
                instId: row.id,
                // 这个参数用于检查是否有撤回流程权限
                type: 'request',
                myApplication: true,
                // TODO：taskId
                // taskId:
                // __isFull__: false,
              },
            })
          }
        })
      },
      handleDelete(id) {
        this.$confirm('确认删除此流程?', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning',
          closeOnClickModal: false,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              deleteInstById(id).then((res) => {
                if (!res.state) return this.$message.error(res.message)
                instance.confirmButtonLoading = false
                this.$message.success(res.message)
                this.$refs.htTable.load()
                done()
              })
            } else {
              done()
              instance.confirmButtonLoading = false
            }
          },
        }).then(() => {})
      },
      handleTermination(id) {
        this.$confirm('确认终止此流程?', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning',
          closeOnClickModal: false,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              terminationProcess(id, (res) => {
                if (!res.state) return this.$message.error(res.message)
                instance.confirmButtonLoading = false
                this.$message.success(res.message)
                this.$refs.htTable.load()
                done()
              })
            } else {
              done()
              instance.confirmButtonLoading = false
            }
          },
        }).then(() => {})
      },
    },
  }
</script>

<style lang="scss" scoped>
  .my-request {
    height: 100%;
    .subject,
    .process-icon {
      cursor: pointer;
      color: var(--themeColor);
    }
    .red-color {
      color: $base-color-red;
    }
  }
</style>
