<template>
  <div>
    <PlacedTop :nodeId="'myTaskIndex'"></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"
        :style="{
          paddingTop:
            status == 'leaderWait' || status == 'delegate' ? '16px' : '0',
        }"
      >
        <van-tab
          v-for="(tab, index) in categories"
          :key="tab.name"
          :title="tab.label"
          :name="tab.IndexName"
          :badge="
            (tab.name == 'wait' && (waitTasksTotal !== 0||waitTasksMobileTotal!==0)
              ? waitTasksTotal + waitTasksMobileTotal
              : '') ||
            (tab.name == 'leaderWait' && (LeaderTotal !== 0 || LeaderMobileTotal!==0)? LeaderTotal+LeaderMobileTotal : '')
          "
        >
          <div
            class="filter"
            v-if="tab.name !== 'leaderWait' && tab.name !== 'delegate'"
          >
            <van-radio-group
              class="filter-custom-radio-group"
              v-model="checkCategories"
            >
              <van-radio
                v-for="(item, index) in statusArr.slice(0, 3)"
                :name="item.name"
                :key="item.label"
              >
                {{ item.label }}
              </van-radio>
            </van-radio-group>
            <div
              class="filter-icon"
              :class="activeStatus ? 'active-status-class' : ''"
              @click="showPopup"
            >
              {{ status == 'wait' ? '其他类型' : '其他状态' }}
              <i class="icon-shaixuan"></i>
            </div>
          </div>
          <div
            class="roadWrapper"
            :style="{
              '--outHeight':
                tab.name == 'leaderWait' || tab.name == 'delegate'
                  ? '180px'
                  : '205px',
            }"
            id="myTaskIndex"
            v-if="status == tab.name"
          >
            <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="[
                      rowClassName(item),
                    ]"
                    @click="showItem(item)"
                  >
                    <DelegateListItem
                      v-if="status == 'delegate'"
                      :item="item"
                      :searchValue="searchValue"
                      @delBpmTask="delBpmTaskMyDelegateById"
                    ></DelegateListItem>
                    <TaskListItem
                      v-else
                      :item="item"
                      :extraField="extraField"
                      :searchValue="searchValue"
                      :currentActiveTab="status"
                    ></TaskListItem>
                  </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="[
                      rowClassName(item),
                    ]"
                    @click="showItem(item)"
                  >
                    <DelegateListItem
                      v-if="status == 'delegate'"
                      :item="item"
                      :searchValue="searchValue"
                      @delBpmTask="delBpmTaskMyDelegateById"
                    ></DelegateListItem>
                    <TaskListItem
                      v-else
                      :item="item"
                      :extraField="extraField"
                      :searchValue="searchValue"
                      :currentActiveTab="status"
                    ></TaskListItem>
                  </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>
            <van-loading size="24px" v-if="itemLoading" vertical>加载中...</van-loading>
          </div>
        </van-tab>
      </div>
    </van-tabs>
    <van-popup
      v-model="showCategories"
      position="bottom"
      round
      :style="{
        height: '320px',
        width: '100vw',
      }"
    >
      <div class="pop-header">
        <span class="cancel" @click="showCategories = false">关闭</span>
        <span class="title">
          {{ status == 'wait' ? '其他类型' : '其他状态' }}
        </span>
        <span></span>
      </div>
      <div style="font-size: 14px; color: #262626; margin: 16px 0 0 16px">
        {{ status == 'wait' ? '任务类型' : '任务状态' }}
      </div>
      <van-radio-group class="custom-radio-group" v-model="checkCategories">
        <van-radio
          v-for="(item, index) in statusArr.slice(3, statusArr.length)"
          :name="item.name"
          :key="item.label"
        >
          {{ item.label }}
        </van-radio>
      </van-radio-group>
    </van-popup>
  </div>
</template>

<script>
  const PlacedTop = () => import('@/components/PlacedTop.vue')
  import {
    TAB_LIST,
    TODO_TASK_STATUS_LIST,
    DONE_TASK_STATUS_LIST,
  } from './const'
  import TaskListItem from './TaskListItem.vue'
  import DelegateListItem from './DelegateListItem.vue'
  import flow from '@/api/flow.js'
  import { Dialog, Notify } from 'vant'
  import {
    getLeaderTodoList,
    checkHasSecretary,
    takeBackTask,
  } from '@/api/process'
  import vanListCommon from '@/mixins/vanListCommon.js'
  import tabActiveMemory from '@/mixins/tabActiveMemory'
  import nodeAndApprover from '@/mixins/nodeAndApprover.js'
  import callBackScroll from '@/mixins/callBackScroll.js'

  export default {
    name: 'MyTask',
    mixins: [vanListCommon, tabActiveMemory, nodeAndApprover, callBackScroll],
    components: {
      TaskListItem,
      DelegateListItem,
      PlacedTop,
    },
    props: {
      activeNumber: {
        type: String | Number,
        default: 0,
      },
    },
    data() {
      return {
        status: 'wait',
        active: 0,
        categories: TAB_LIST.filter((item) => {
          return item.name != 'leaderWait'
        }),
        noDataImage: require('@/assets/images/no_data_list.png'),
        waitTasksTotal: 0,
        waitTasksMobileTotal: 0,
        LeaderTotal: 0,
        LeaderMobileTotal:0,
        showCategories: false,
        checkCategories: 'all',
        random: new Date().valueOf(),
        itemLoading:true,
      }
    },
    computed: {
      statusArr() {
        if (this.status == 'wait') {
          return TODO_TASK_STATUS_LIST
        } else if (this.status == 'down') {
          return DONE_TASK_STATUS_LIST
        } else if (this.status == 'leaderWait' || this.status == 'delegate') {
          return []
        }
      },
      activeStatus() {
        return this.statusArr
          .slice(3, this.statusArr.length)
          .find((item) => item.name == this.checkCategories)
      },
    },
    created() {
      this.active = Number(this.activeNumber)
    },
    watch: {
      activeNumber: {
        handler(val) {
          switch (val) {
            case 0:
              this.status = 'wait'
              break
            case 1:
              this.status = 'leaderWait'
              break
            case 2:
              this.status = 'down'
              break
            case 3:
              this.status = 'delegate'
              break
            default:
              this.status = 'wait'
              break
          }
        },
        immediate: true,
      },
      itemList(val) {
        val?.length > 0 && this.loadTaskInfo(val)
      },
      checkCategories: {
        handler(newval, oldval) {
          if (newval !== oldval) {
            this.random = new Date().valueOf()
            this.itemLoading =true
            this.onRefresh()
          }
          this.showCategories = false
        },
        immediate: true,
      },
    },
    methods: {
      async init() {
        await this.checkHasSecretary()
        this.onChangeTabs()
      },
      checkHasSecretary() {
        return checkHasSecretary().then((res) => {
          if (!res.value) {
            this.categories = TAB_LIST.filter((item) => {
              return item.name != 'leaderWait'
            })
          } else {
            this.categories = TAB_LIST
            this.LeaderTotalMet()
          }
        })
      },
      LeaderTotalMet() {
        getLeaderTodoList({}).then((response) => {
          this.LeaderTotal = response.total
        })
      },
      onChangeTabs(event) {
        switch (this.active) {
          case 0:
            this.status = 'wait'
            break
          case 1:
            this.status = 'leaderWait'
            break
          case 2:
            this.status = 'down'
            break
          case 3:
            this.status = 'delegate'
            break
          default:
            this.status = 'wait'
            break
        }
        this.searchValue = ''
        this.checkCategories = 'all'
        this.random = new Date().valueOf()
        this.itemLoading = true
        this.onRefresh()
      },
      //上拉加载
      //异步请求数据 ，我们的项目时封装好的方法，此处只是调用
      onLoad(supportMobile) {
        let params = {
          pageBean: {
            page:supportMobile==1?this.page:this.PCpage,
            pageSize: this.pageSize,
            showTotal: true,
          },
          querys: [{
          property: this.status == 'wait'?'bt.support_mobile_':'support_mobile_',
          value: supportMobile,
          group: 'main',
          relation: 'AND',
          operation: 'EQUAL',
          }],
        }
        let _self = this
        const random = this.random
        if (this.status == 'wait') {
          if (this.checkCategories != 'all') {
            params.querys.push({
              group: 'filter',
              operation: 'EQUAL',
              property: 'bt.status_',
              relation: 'AND',
              value: this.checkCategories,
            })
          }
          if (this.searchValue) {
            params.querys.push({
              property: 'bt.subject_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quickSearch',
            })
            params.querys.push({
              property: 'bt.proc_def_name_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quickSearch',
            })
            params.querys.push({
              property: 'bt.proc_inst_id_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quickSearch',
            })
          }
          flow
            .getMobileTodoList(params)
            .then((response) => {
              if(supportMobile===1){
                _self.waitTasksTotal = response.total
                _self.loadData(response, _self,random) 
              }else{
                _self.waitTasksMobileTotal = response.total
                _self.loadPCData(response, _self,random)
              }
            })
            .catch((error) => {})
            .finally(() => {
              _self.itemLoading =false
              _self.isDownLoading = false
              _self.isUpLoading = false
              
            })
        } else if (this.status == 'leaderWait') {
          if (this.checkCategories != 'all') {
            params.querys.push({
              group: 'filter',
              operation: 'EQUAL',
              property: 'bt.status_',
              relation: 'AND',
              value: this.checkCategories,
            })
          }
          if (this.searchValue) {
            params.querys.push({
              property: 'subject_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quick',
            })
            params.querys.push({
              property: 'proc_def_name_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quick',
            })
            params.querys.push({
              property: 'proc_inst_id_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quick',
            })
            params.querys.push({
              property: 'name_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quick',
            })
          }
          getLeaderTodoList(params)
            .then((response) => {     
              if(supportMobile===1){
                this.LeaderTotal = response.total
                _self.loadData(response, _self,random) 
              }else{
                this.LeaderMobileTotal = response.total
                _self.loadPCData(response, _self,random)
              }
            })
            .catch((error) => {})
            .finally(() => {
              _self.itemLoading =false
              _self.isDownLoading = false
              _self.isUpLoading = false
            })
        } else if (this.status == 'delegate') {
          if (this.searchValue) {
            params.querys.push({
              property: 'subject_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quickSearch',
            })
            params.querys.push({
              property: 'proc_inst_id_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quickSearch',
            })
          }
          flow
            .getMobileDelegate(params)
            .then((response) => {
              this.LeaderTotal = response.total
              if(supportMobile===1){
                _self.loadData(response, _self,random) 
              }else{
                _self.loadPCData(response, _self,random)
              }
            })
            .catch((error) => {})
            .finally(() => {
              _self.itemLoading =false
              _self.isDownLoading = false
              _self.isUpLoading = false
            })
        } else {
          if (this.checkCategories != 'all') {
            params.querys.push({
              group: 'filter',
              operation: 'EQUAL',
              property: 'wfInst.status_',
              relation: 'AND',
              value: this.checkCategories,
            })
          }
          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',
            })
            params.querys.push({
              property: 'wfInst.id_',
              value: this.searchValue,
              operation: 'LIKE',
              relation: 'OR',
              group: 'quickSearch',
            })
          }
          flow
            .getMobileDoneList(params)
            .then((response) => {
              if(supportMobile===1){
                _self.loadData(response, _self,random) 
              }else{
                _self.loadPCData(response, _self,random)
              }
            })
            .catch((error) => {})
            .finally(() => {
              _self.itemLoading =false
              _self.isDownLoading = false
              _self.isUpLoading = false
            })
        }
      },
      //进入审批页面
      showItem(row) {
        if (this.status == 'wait') {
          if (row.supportMobile != 1) {
            this.$toast.fail('此待办未绑定手机表单')
            return
          }

          /*与产品确认移动端不选择领导代为审批 3/27 */
          /*   if (row.status == 'SHARE' || row.status == 'BACKSHARE') {
                     if (row.identityList && row.identityList.length == 1) {
                    this.$router.push({
                      path: '/matter/approvalForm',
                      query: {
                        taskId: row.taskId || row.id,
                        instId: row.procInstId,
                        isGetApprovalBtn: true,
                        type: 'fromTodoList',
                        status: row.status,
                      },
                    }) } else {
                      let html =
                        '<select ref=' +
                        Math.random() +
                        ' id="approvalLeaderSelect" style="width: 200px;height: 30px;border-radius: 4px;margin: 20px 70px;" ><option value="">请选择</option>'
                      row.identityList.forEach((identity) => {
                        html +=
                          '<option value="' +
                          identity.id +
                          '">' +
                          identity.name +
                          '</option>'
                      })
                      html += '</select>'
                      let this_ = this
                      this.$alert(html, '请选择一个领导代为审批', {
                        dangerouslyUseHTMLString: true,
                        beforeClose: function (action, instance, done) {
                          if (action == 'confirm') {
                            let se = document.getElementById('approvalLeaderSelect')
                            if (se.selectedIndex == 0) {
                              Notify({
                                type: 'warning',
                                message: '请选择代为审批的领导',
                              })
                            } else {
                              instance.close()
                              this_.$router.push(
                                '/task/' + row.id + '/' + se[se.selectedIndex].value
                              )
                            }
                          } else {
                            instance.close()
                          }
                        },
                      })
                    } */
          /*  } else {}*/
          this.$router.push({
            path: '/matter/approvalForm',
            query: {
              taskId: row.taskId || row.id,
              instId: row.procInstId,
              isGetApprovalBtn: true,
              type: 'fromTodoList',
              status: row.status,
            },
          })
        } else if (this.status == 'down') {
          if (row.supportMobile != 1) {
            this.$toast.fail('此已办未绑定手机表单')
            return
          }
          //判断是否显示撤回按钮
          this.$router.push({
            path: '/matter/approvalForm',
            query: {
              instId: row.id,
              isReadonly: true,
              type: 'done',
              doneTaskId: row.taskId,
              nodeId: row.nodeId,
              status: row.status,
            },
          })
        } else if (this.status == 'leaderWait') {
          if (row.supportMobile != 1) {
            this.$toast.fail('此待办未绑定手机表单')
            return
          }

          this.$router.push({
            path: '/matter/approvalForm',
            query: {
              taskId: row.id,
              instId: row.procInstId,
              isGetApprovalBtn: true,
              type: 'fromTodoList',
              status: row.status,
              leaderId: row.leaderIds,
            },
          })
        } else if (this.status == 'delegate') {
          this.$router.push({
            path: '/matter/approvalForm',
            query: {
              instId: row.procInstId,
              from: 'delegate',
              nodeId: row.nodeId,
              status: row.status,
            },
          })
        }
      },
      handleGoBack() {
        const from = this.$route.query.from
        if (from === 'worker') {
          this.$router.push('/worker')
        } else {
          this.$router.push({
            path: '/home',
          })
        }
      },
      rowClassName(row) {
        let className = ''
        const statusList = ['back', 'backToStart', 'BACK', 'BACKSHARE']
        if (
          statusList.includes(row.instStatus) ||
          statusList.includes(row.status)
        ) {
          className = 'task_isback'
        }
        return className
      },
      showPopup() {
        this.showCategories = true
      },
      //根据任务ID收回转办任务
      delBpmTaskMyDelegateById(row) {
        Dialog.confirm({
          title: '提示',
          message: '确认收回此流程?',
          beforeClose: (action, done) => {
            if (action === 'confirm') {
              takeBackTask(row.taskId).then((res) => {
                done()
                if (!res.state)
                  return Notify({ type: 'danger', message: res.message })
                Notify({ type: 'success', message: res.message })
                this.onRefresh()
              })
            } else {
              done()
            }
          },
        }).then(() => {})
      },
    },
  }
</script>
<style lang="scss" scoped>
  .roadWrapper {
    height: calc(#{$vh} - var(--outHeight));
    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-bottom: 16px;
    .road {
      padding: 0 16px;
    }
  }
  .pop-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    width: calc(100vw - 32px);

    .cancel {
      font-size: 14px;
      color: #8c8c8c;
    }

    .title {
      font-size: 17px;
      color: #1a1a1a;
      font-weight: bold;
    }
  }
  ::v-deep .custom-radio-group,
  .custom-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    width: calc(100% - 32px);
    padding: 16px;
    // 单选框，复选框文字样式
    .van-radio__label,
    .van-checkbox__label {
      text-align: center;
      margin-left: 0;
      height: 44px;
      width: 106px;
      line-height: 44px;
      font-size: 14px;
      margin-bottom: 16px;
      background-color: #f9f9f9;
      border-radius: 8px;
      flex: 1;
    }

    .van-radio,
    .van-checkbox {
      position: relative;
      border-radius: 4px;
      overflow: hidden;
    }

    // 去掉原本的勾选样式
    .van-radio__icon .van-icon,
    .van-checkbox__icon .van-icon {
      border: 0;
      display: none;
    }
    // 选中之后的文字颜色和背景色设置
    .van-radio__icon--checked + .van-radio__label,
    .van-checkbox__icon--checked + .van-checkbox__label {
      color: #fff;
      background-color: #409eff;
    }
  }
  .custom-radio-group::after {
    // 使用伪类元素占据单位，不影响页面
    content: '';
    height: 0;
    width: 32%;
  }
  .status-tab {
    ::v-deep .van-tabs__wrap {
      width: 70vw;
      display: inline-block;
    }
  }
  .filter {
    position: relative;
    padding: 2px 0 12px;
  }
  .filter-icon {
    position: absolute;
    right: 12px;
    font-size: 14px;
    top: 11px;
    color: #8c8c8c;
  }
  ::v-deep .filter-custom-radio-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    width: calc(75% - 18px);
    height: 40px;
    // 单选框，复选框文字样式
    .van-radio__label {
      text-align: center;
      margin-left: 0;
      width: 30%;
      font-size: 14px;
      color: #8c8c8c;
      flex: 1;
    }

    .van-radio {
      position: relative;
      overflow: hidden;
    }

    // 去掉原本的勾选样式
    .van-radio__icon .van-icon {
      border: 0;
      display: none;
    }
    // 选中之后的文字颜色和背景色设置
    .van-radio__icon--checked + .van-radio__label {
      color: #409eff;
    }
    .van-radio__icon--checked {
      position: relative;
      text-align: center;
      &::after {
        content: '';
        position: absolute;
        bottom: -10px;
        width: 40px;
        height: 3px;
        background-color: #409eff;
      }
    }
  }
  .active-status-class {
    color: #409eff;
  }
  .icon-shaixuan{
    font-size: 18px;
  }
  .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>
