
<template>
  <div class="handlecenter_box">
    <van-tabs v-model:active="searchData['status']" :sticky="true" @click-tab="tabClickHandle">
        <div class="search_box">
          <div class="search_input">
            <van-search
              v-model="searchData['searchVal']"
              background="transparent"
              placeholder="搜索标题、申请编号、申请内容"
              @search="searchHandler"
            />
          </div>
          <div class="search_icon">
            <van-button type="primary" icon="replay" size="small" @click="resetHandler"></van-button>
            <van-icon name="filter-o" size="24" color="#51555A" @click="modelShow = true" style="margin-left: 6px;"/>
          </div>
        </div>
        <van-tab :title="'待办('+handlerCaseStatis['normal']+')'" name="1">
          <div class="handlecenter_card_box">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
              <van-list
                v-model:loading="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
              >
                <div class="handlecenter_card" v-for="(item,index) in handleLists" :key="index">
                  <div class="header">
                    <p class="title">
                      <span>业务编号：</span>
                      <span>{{item['CODE']}}</span>
                    </p>
                    <p class="status">
                       <span v-html="item['statusVal']"></span>
                    </p>
                  </div>
                  <div class="content" @click="clickHandler(item, false)">
                    <div class="titleBox">
                      <p class="title">{{item['NAME']}}</p>
                      <p class="desc">办理环节：<span>{{item['ACTIVITYNAME']}}</span></p>
                    </div>
                    <div class="desc">{{item['DESCRIBTION']??'暂无流程描述'}}</div>
                  </div>
                  <div class="tip">
                    <div class="one">
                      <van-icon name="clock-o" />
                      <span>{{formatDateTime(new Date(item['STARTTIME']))}}</span>
                    </div>
                    <div class="two" @click="processLogHandle(item)">
                      <van-button type="primary" icon="todo-list-o" size="mini">流程日志</van-button>
                    </div>
                  </div>
                </div>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
        <van-tab :title="'已完成('+handlerCaseStatis['finish']+')'" name="90">
          <div class="handlecenter_card_box">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
              <van-list
                v-model:loading="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
              >
                <div class="handlecenter_card" v-for="(item,index) in handleLists" :key="index">
                  <div class="header">
                    <p class="title">
                      <span>业务编号：</span>
                      <span>{{item['CODE']}}</span>
                    </p>
                    <p class="status">
                      <!-- <span>{{ item['IS_END'] === 1 ? '归档' : '完成' }}</span> -->
                       <span v-html="item['statusVal']"></span>
                    </p>
                  </div>
                  <div class="content" @click="clickHandler(item, true)">
                    <div class="titleBox">
                      <p class="title">{{item['NAME']}}</p>
                      <p class="desc">完成环节：<span>{{item['ACTIVITYNAME']}}</span></p>
                    </div>
                    <div class="desc">{{item['DESCRIBTION']??'暂无流程描述'}}</div>
                  </div>
                  <div class="tip">
                    <div class="one">
                      <van-icon name="clock-o" />
                      <span>{{formatDateTime(new Date(item['STARTTIME']))}}</span>
                    </div>
                    <div class="two" @click="processLogHandle(item)">
                      <van-button type="primary" icon="todo-list-o" size="mini">流程日志</van-button>
                    </div>
                  </div>
                </div>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
        <van-tab :title="'已归档('+handlerCaseStatis['archive']+')'" name="99">
          <div class="handlecenter_card_box">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
              <van-list
                v-model:loading="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
              >
                <div class="handlecenter_card" v-for="(item,index) in handleLists" :key="index">
                  <div class="header">
                    <p class="title">
                      <span>业务编号：</span>
                      <span>{{item['CODE']}}</span>
                    </p>
                    <p class="status">
                       <span v-html="item['statusVal']"></span>
                    </p>
                  </div>
                  <div class="content" @click="clickHandler(item, true)">
                    <div class="titleBox">
                      <p class="title">{{item['NAME']}}</p>
                    </div>
                    <div class="desc">{{item['DESCRIBTION']??'暂无流程描述'}}</div>
                  </div>
                  <div class="tip">
                    <div class="one">
                      <van-icon name="clock-o" />
                      <span>{{formatDateTime(new Date(item['STARTTIME']))}}</span>
                    </div>
                    <div class="two" @click="processLogHandle(item)">
                      <van-button type="primary" icon="todo-list-o" size="mini">流程日志</van-button>
                    </div>
                  </div>
                </div>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
    </van-tabs>
    <van-dialog :show-cancel-button="true" v-model:show="modelShow" title="流程目录" @confirm="confirmHandle">
      <van-tree-select
          v-model:active-id="activeIds"
          v-model:main-active-index="activeIndex"
          :items="items"
        />
    </van-dialog>
    <van-dialog v-model:show="processLogShow" title="流程日志" confirmButtonText="关闭">
      <div class="processLogBox">
        <ul>
          <li v-for="(item,index) in processLogs" :key="index">
            <p :class="'status color'+item['handleMethod']">{{ filterStatus(item['handleMethod']) }}</p>
            <p class="header">{{ item['activityName'] }}</p>
            <p>{{ item['handleMethod'] === 0 ? '退回人' : '办理人' }}：{{ item['handler'] }}</p>
            <p>转件时间：{{item['receiveTime']}}</p>
            <p>办理时限：{{ item['shouldFinishTime'] ? item['shouldFinishTime'] : '无时限' }}</p>
            <p v-if="item['transferActivityName']">转至》{{ item['transferActivityName'] ? `[${item['transferActivityName']}]` : ''}}<span style="display: inline-block;margin-left: 5px;"></span></p>
            <p v-if="item['transferActivityName']">可办理人：{{ item['canHandler'] }}</p>
          </li>
        </ul>
      </div>
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { showToast } from "vant";
import { getHandlerCaseCenterList, getHandlerCaseCenterCount,getRecordList, getFlowTemplateTreeDataByUser, saveAndGetMobileUrl } from '@/service/flow';
import { listToTree } from '@/utils/tree';
import PubsubService from "@/utils/PubsubService";
import { formatDateTime, getQueryParamsByUrl } from '@/utils/common';
import { useCommonStoreWithOut } from '@/stores/modules/common';

defineOptions({
  name: 'HandleCenter'
})

const items = ref([]);
const loading = ref(false);
const finished = ref(false);
const modelShow = ref(false);
const refreshing = ref(false);
const activeIds = ref<string[]>([]);
const activeIndex = ref<number>(0);
const onRefresh = () => {
  queryHandlerCaseCenterCount();
  queryHandlerCaseCenterList(true);
};

const onLoad = () => {
  loading.value = true;
  pageData.value.page = pageData.value.page + 1
  queryHandlerCaseCenterList();
};
const searchHandler = () => {
  queryHandlerCaseCenterCount();
  queryHandlerCaseCenterList(true);
}
const pageData = ref<{
  page: number
  rows: number
  records?: number
}>({
  page: 0,
  rows: 10,
  records: 0
})
const searchData = ref<{
  status: string
  searchVal: string
}>({
  status: '1',
  searchVal: ''
})
const handlerCaseStatis = ref<{
  normal: number
  finish: number
  archive: number
}>({
  normal: 0,
  finish: 0,
  archive: 0
})
const queryHandlerCaseCenterCount = () => {
  const sendData = {
    isMobile: true,
    toSystemId: '',
    flowTemIds: JSON.stringify(activeIds.value),
    ...searchData.value
  }
  getHandlerCaseCenterCount(sendData).then((result:any) => {
    if (result) {
      handlerCaseStatis.value.normal = result.NORMAL
      handlerCaseStatis.value.finish = result.FINISH
      handlerCaseStatis.value.archive = result.ARCHIVE
    }
  })
}
queryHandlerCaseCenterCount()
const handleLists = ref<any[]>([]);
const queryHandlerCaseCenterList = (isPull = false) => {
  if (isPull) {
    pageData.value.page = 1
    refreshing.value = true;
    finished.value = false;
  }
  const sendData = {
    IEnd: 0,
    isMobile: true,
    toSystemId: '',
    flowTemIds: JSON.stringify(activeIds.value),
    ...pageData.value,
    ...searchData.value
  }
  getHandlerCaseCenterList(sendData).then((result: any) => { 
    if (result.error_code) {
      finished.value = true;
      return;
    }
    if (result && result.rows) {
      isPull ? handleLists.value = result.rows : handleLists.value?.push(...result.rows) 
    }
    if (isPull) {
      refreshing.value = false
    }
    /** 用来解决tab切换时，容器高度发生变化自动触发loading事件 */
    const time = setTimeout(() => {
      loading.value = false;
      clearTimeout(time);
    }, 800);
    if (result.records === handleLists.value.length) { 
      finished.value = true;
    }
  });
}
const tabClickHandle = () => {
  loading.value = true;
  queryHandlerCaseCenterList(true);
}
const sendData = {
  isRight: 0,
  officeStatus: 1,
  excludedSystemId: '',
  toSystemId: '',
};
getFlowTemplateTreeDataByUser(sendData).then((result: any) => { 
  result.forEach((item: any) => {
    item['text'] = item['name']
  })
  if (result && result.length > 0) { 
    items.value = listToTree(result)[0]['children']; 
  }
});
const resetHandler = () => {
  loading.value = true;
  searchData.value.searchVal = ''
  activeIds.value = []
  queryHandlerCaseCenterCount();
  queryHandlerCaseCenterList(true);
}
const confirmHandle = () => {
  loading.value = true;
  queryHandlerCaseCenterCount();
  queryHandlerCaseCenterList(true);
}
/**
 * 流程办理或查看
 */
const CommonStore = useCommonStoreWithOut();
const router = useRouter();
const toPageHandle = (path: string, params: any) => {
  if (path) {
    //@ts-ignore
    const arr = path.split(window?.locationBaseUrl)
    if (arr.length > 1) {
      const {url, query} = getQueryParamsByUrl(arr[1])
      Object.assign(query, params);
      router.push({
        path: url,
        query
      })
    }
  }
};
const clickHandler = (item: any, isView: boolean) => {
  let btnArrJson: any[] = []
  if (item && item['btnArrJson']) {
    btnArrJson = JSON.parse(item['btnArrJson'])
  }
  const sendData = {
    "activityInsId": item['ACTIVITYINSID'],
    "flowInsId": item['FLOWINSID'],
    "participantId": item['PARTICIPANTID'],
    "isView": isView,
    "status": ''
  }
  CommonStore.setCFlowItemData({
    FLOWINSID: item['FLOWINSID'],
    CODE: item['CODE'],
    DESCRIBTION: item['DESCRIBTION'],
    ACTIVITYNAME:  item['ACTIVITYINSID']
  })
  const operationMap = filterToCalBackBtn(btnArrJson);
  saveAndGetMobileUrl(sendData).then((result) => { 
    if (typeof (result) === 'string') {
      toPageHandle(result, {
        '_isCalBack': operationMap['isCalback'],
        '_isObsolete': operationMap['isObsolete']
      })
    }
  });
}
type OperationType = {
  isCalback: string
  isObsolete: string
}
const filterToCalBackBtn = (lists: any[]): OperationType => {
  const map: OperationType = {
    isCalback: '0',
    isObsolete: '0'
  }
  for (let i: number = 0; i < lists.length; i++){
    if (lists[i]['name'] === "calBackBtn") {
      map['isCalback'] = lists[i]['iEnable'] ? '1' : '0'
      continue;
    }
    if (lists[i]['name'] === "obsoleteBtn") {
      map['isObsolete'] = lists[i]['iEnable'] ? '1' : '0'
      continue;
    }
  }
  return map;
}
/**
 * 流程日志
 */
const filterStatus = (status: number) => {
  let msg = '';
  switch (status) {
    case 0:
      msg = '退件'
      break
    case 1:
      msg = '转件'
      break
    default:
      msg = '办理'
      break
  }
  return msg;
}
const processLogShow = ref<boolean>(false)
const processLogs = ref<any[]>([])
const processLogHandle = (item) => {
  getRecordList({
    flowInstanceId: item['FLOWINSID'],
    _search: false,
    sord: 'asc'
  }).then((result: any) => {
    if (result && result.length > 0) {
      processLogs.value = result
      processLogShow.value = true;
    }else{
      showToast({
        message: "暂无流程日志！",
        position: "top",
      });
    }
  })
}
PubsubService.subscribe('HandleCenterEvent', () => {
    searchHandler();
})
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>