<template>
  <div>
    <PlacedTop :nodeId="'myRequestIndex'"></PlacedTop>
    <NavBar :is-custom="true" @go-back="handleGoBack">
      <template slot="title">我的申请</template>
    </NavBar>
    <van-search
      v-model="searchValue"
      show-action
      placeholder="请输入标题或流程编号来搜索..."
      @search="onSearchChange"
      @clear="onSearch"
    >
      <template #action>
        <div @click="onSearch" style="color: #409eff">搜索</div>
      </template>
    </van-search>
    <van-tabs
      v-model="active"
      @change="onChangeTabs"
      title-active-color="#409EFF"
      color="#409EFF"
    >
      <div class="task-content-container">
        <van-tab
          v-for="(tab, index) in categories"
          :key="tab.id"
          :title="tab.name"
        >
          <div class="roadWrapper" id="myRequestIndex" v-if="status == tab.id">
            <div class="road">
              <van-pull-refresh v-model="isDownLoading" @refresh="onRefresh()">
                <van-list
                  v-if="itemList && itemList.length > 0"
                  v-model="loading"
                  :finished="finished"
                  finished-text=""
                  @load="onLoad(1)"
                  :immediate-check="false"
                  :offset="20"
                >
                  <van-cell
                    v-for="(item, index) in itemList"
                    :key="`${item.id}${index}`"
                    class="task_list_item task_mobile"
                    :class="[
                      item.status == 'backToStart' ||
                      item.status.toLowerCase() == 'back'
                        ? 'task_isback'
                        : '',
                    ]"
                    @click="showItem(item)"
                  >
                    <MyRequestListItem
                      :item="item"
                      :extraField="extraField"
                      :searchValue="searchValue"
                      @delete="handleDelete"
                      @deleteDraft="handleDeleteDraft"
                      @termination="handleTermination"
                    ></MyRequestListItem>
                  </van-cell>
                </van-list>
              </van-pull-refresh>
              <van-collapse
              v-model="activeNames"
              v-if="finished && PCitemList && PCitemList.length > 0 "
              class="pc_process"
            >
              <van-collapse-item
                title="不可使用任务"
                name="PCProcess"
                :border="false"
                :is-link="false"
              >
                <template #title>
                  不可使用任务
                  <i class="van-icon van-icon-arrow van-cell__right-icon"></i>
                </template>
                <van-list
                  v-if="PCitemList && PCitemList.length > 0"
                  v-model="PCloading"
                  :finished="PCfinished"
                  finished-text="没有更多了"
                  @load="onLoad(0)"
                  :immediate-check="false"
                  :offset="50"
                >
                  <van-cell
                    v-for="(item, index) in PCitemList"
                    :key="`${item.id}${index}`"
                    class="task_list_item task_pc"
                    :class="[
                      item.status == 'backToStart' ||
                      item.status.toLowerCase() == 'back'
                        ? 'task_isback'
                        : '',
                    ]"
                    @click="showItem(item)"
                  >
                    <MyRequestListItem
                      :item="item"
                      :extraField="extraField"
                      :searchValue="searchValue"
                      @delete="handleDelete"
                      @deleteDraft="handleDeleteDraft"
                      @termination="handleTermination"
                    ></MyRequestListItem>
                  </van-cell>
                </van-list>
              </van-collapse-item>
            </van-collapse>
              <van-empty
                v-if="itemList.length == 0 && finished && PCitemList.length == 0 && PCfinished "
                class="custom-image"
                :image="noDataImage"
                description="暂无内容"
              />
            </div>
          </div>
        </van-tab>
      </div>
    </van-tabs>
  </div>
</template>

<script>
  const PlacedTop = () => import('@/components/PlacedTop.vue')
  import { Dialog, Notify } from 'vant'
  import { mapState } from 'vuex'
  import flow from '@/api/flow.js'
  import {
    deleteInstById,
    terminationProcess,
    getTasksByInstId,
    getUrgentStateConf,
    deleteProcessInstanceById,
  } from '@/api/process.js'
  import vanListCommon from '@/mixins/vanListCommon.js'
  import nodeAndApprover from '@/mixins/nodeAndApprover.js'
  import MyRequestListItem from './MyRequestListItem.vue'
  import tabActiveMemory from '@/mixins/tabActiveMemory'
  import callBackScroll from '@/mixins/callBackScroll.js'
  export default {
    name: 'MyRequest',
    mixins: [vanListCommon, nodeAndApprover, tabActiveMemory, callBackScroll],
    components: {
      MyRequestListItem,
      PlacedTop,
    },
    data() {
      return {
        active: 0,
        status: 'all',
        categories: [
          {
            id: 'all',
            name: '全部',
          },
          {
            id: 'running',
            name: '运行中',
          },
          {
            id: 'end',
            name: '结束',
          },
          {
            id: 'draft',
            name: '草稿',
          },
        ],
        noDataImage: require('@/assets/images/no_data_list.png'),
      }
    },
    computed: {
      ...mapState('login', ['currentUser']),
      userId() {
        return this.currentUser?.userId
      },
    },
    watch: {
      itemList(val) {
        val?.length > 0 && this.loadTaskInfo(val)
      },
    },
    methods: {
      init() {
        this.onChangeTabs()
      },
      onChangeTabs(event) {
        switch (this.active) {
          case 0:
            this.status = 'all'
            break
          case 1:
            this.status = 'running'
            break
          case 2:
            this.status = 'end'
            break
          case 3:
            this.status = 'draft'
            break
          default:
            this.status = 'all'
            break
        }
        this.searchValue = ''
        this.onRefresh()
      },
      //上拉加载
      //异步请求数据 ，我们的项目时封装好的方法，此处只是调用
      onLoad(supportMobile) {
        let params = {
          pageBean: {
            page:supportMobile==1?this.page:this.PCpage,
            pageSize: this.pageSize,
            showTotal: true,
          },
          querys: [],
        }
        if (this.status != 'all') {
          params.querys.push({
            property: 'status_',
            value: this.status == 'end' ? ['end', 'manualend'] : this.status,
            operation: this.status == 'end' ? 'IN' : 'EQUAL',
            relation: 'AND',
          })
        } else {
          params.querys = []
        }
        params.querys.push({
          property: 'support_mobile_',
          value: supportMobile,
          group: 'main',
          relation: 'AND',
          operation: 'EQUAL',
        })
        if (this.searchValue) {
          params.querys.push({
            property: 'subject_',
            value: this.searchValue,
            operation: 'LIKE',
            relation: 'OR',
            group: 'quickSearch',
          })
          params.querys.push({
            property: 'proc_def_name_',
            value: this.searchValue,
            operation: 'LIKE',
            relation: 'OR',
            group: 'quickSearch',
          })
          if (this.status != 'draft') {
            params.querys.push({
              property: 'bpm_pro_inst.id_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quickSearch',
            })
          } else {
            params.querys.push({
              property: 'id_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quickSearch',
            })
          }
        }
        let _this = this
        if (this.status == 'draft') {
          flow
            .myMobileDraft(params)
            .then((res) => {
              if(supportMobile===1){
                _this.loadData(res, _this) 
              }else{
                _this.loadPCData(res, _this)
              }     
            })
            .catch((error) => {})
            .finally(() => {
              _this.isDownLoading = false
              _this.isUpLoading = false
            })
        } else {
          flow
            .myMobileRequest(params)
            .then((res) => {
              if(supportMobile===1){
                _this.loadData(res, _this) 
              }else{
                _this.loadPCData(res, _this)
              }
            })
            .catch((error) => {})
            .finally(() => {
              _this.isDownLoading = false
              _this.isUpLoading = false
            })
        }
      },
      showItem(item) {
        if (item.supportMobile == 1) {
          if (
            item.status == 'revokeToStart' ||
            item.status == 'backToStart' ||
            (item.status == 'back' && item.backToStart == true)
          ) {
            //撤回或者驳回到发起人，点击我的请求，直接跳转到待办页面
            /*
              //获取我的请求对应实例的任务
              分两种情况：
              1、如果包含退回发起人/驳回发起人，进入我的申请，如果单据退回发起人/驳回发起人状态，直接进入待办
              2、如果情况1不满足，进入只读状态查看我的审批单，可关闭或撤回（根据按钮权限渲染）
              */
            let me_ = this
            getTasksByInstId(item.id).then((resp) => {
              console.log(me_.userId, 'me_.userId')
              if (
                resp &&
                resp.rows &&
                resp.rows.length == 1 &&
                resp.rows[0].assigneeId == me_.userId
              ) {
                me_.$router.push({
                  path: '/matter/approvalForm',
                  query: {
                    taskId: resp.rows[0].id,
                    instId: item.id,
                    isGetApprovalBtn: true,
                    myApplication: true,
                    type: 'request',
                    status: item.status,
                  },
                })
              } else {
                this.$router.push({
                  path: '/matter/approvalForm',
                  query: {
                    instId: item.id,
                    // 这个参数用于检查是否有撤回流程权限
                    type: 'request',
                    myApplication: true,
                    status: item.status,
                  },
                })
              }
            })
          } else if (item.status == 'draft') {
            this.$router.push({
              path: '/matter/startProcess',
              query: {
                defId: item.procDefId,
                instId: item.id,
                name: item.subject,
                instStatus: item.status,
                status: item.status,
              },
            })
          } else {
            this.$router.push({
              path: '/matter/approvalForm',
              query: {
                instId: item.id,
                // 这个参数用于检查是否有撤回流程权限
                type: 'request',
                myApplication: true,
                status: item.status,
              },
            })
          }
        } else {
          this.$toast.fail('此任务未绑定手机表单')
        }
      },
      handleDelete(id) {
        Dialog.confirm({
          title: '提示',
          message: '确认删除此流程?',
          beforeClose: (action, done) => {
            if (action === 'confirm') {
              deleteInstById(id).then((res) => {
                if (!res.state)
                  return Notify({ type: 'danger', message: res.message })
                Notify({ type: 'success', message: res.message })
                this.onRefresh()
                done()
              })
            } else {
              done()
            }
          },
        }).then(() => {})
      },
      handleDeleteDraft(id) {
        Dialog.confirm({
          title: '提示',
          message: '草稿一经删除则无法恢复，是否确定要删除该草稿?',
          beforeClose: (action, done) => {
            if (action === 'confirm') {
              deleteProcessInstanceById(id).then((res) => {
                if (!res.state)
                  return Notify({ type: 'danger', message: res.message })
                Notify({ type: 'success', message: res.message })
                this.onRefresh()
                done()
              })
            } else {
              done()
            }
          },
        }).then(() => {})
      },
      handleTermination(id) {
        Dialog.confirm({
          title: '提示',
          message: '确认终止此流程?',
          beforeClose: (action, done) => {
            if (action === 'confirm') {
              terminationProcess(id, (res) => {
                if (!res.state)
                  return Notify({ type: 'danger', message: res.message })
                Notify({ type: 'success', message: res.message })
                this.onRefresh()
                done()
              })
            } else {
              done()
            }
          },
        }).then(() => {})
      },
      handleGoBack() {
        const from = this.$route.query.from
        if (from === 'worker') {
          this.$router.push('/worker')
        } else {
          this.$router.push({
            path: '/home',
          })
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  .roadWrapper {
    height: calc(#{$vh} - 164px);
    overflow: scroll;
  }
  ::v-deep .van-tab {
    font-size: 16px;
  }
  .van-search {
    padding: 16px 8px 8px 16px;
    .van-search__content {
      border-radius: 8px;
    }
  }
  .task_list_item {
    margin-bottom: 16px;
    border-radius: 12px;
    padding: 16px;
    .van-cell__title {
      width: 100%;
    }
  }
  .task-content-container {
    padding: 16px 0;
    .road {
      padding: 0 16px;
    }
  }
  .pc_process ::v-deep .van-collapse-item__content {
    padding: 0;
    background: #f5f5f5;
  }
  .pc_process ::v-deep .van-collapse-item__title{
    text-align: center;
    background: #f5f5f5;
    color: #409eff;
    border: none;
    .van-icon{
      color: #409eff;
    }
  }
  .van-hairline--top-bottom::after, 
  .van-hairline-unset--top-bottom::after {
    border-width:0;
  }
</style>
