<template>
  <card-widget :is-show-tab="true" :active-key="activeKey" isTabSlot :tab-list="flowTaskTabs" @tab-change="tabClick" :style="style">
    <template #header v-if="showHeaderFlag">
      <div class="news-header">
        <div class="news-header-left">
          <span class="text_box">{{ title }}</span>
        </div>
      </div>
    </template>

    <!-- tab 数量 -->
    <template #tab="tabItem"> {{ tabItem.name }} ({{ userNumberObj[tabItem.number] }}) </template>

    <template #body>
      <a-spin :spinning="loading" :delay="100">
        <div class="news-list" v-if="dataList.length > 0">
          <div class="flow-item" v-for="(item, index) in dataList" :key="item.id" @click="flowItemClick(item)">
            <div class="flow-item-h">
              <div class="flow-item-number">{{ index < 9 ? '0' + (index + 1) : index + 1 }}</div>
              <div class="flow-item-title">
                <a-tooltip placement="topLeft">
                  <template #title>
                    <span>{{ item.instanceTitle }}</span>
                  </template>
                  {{ item.instanceTitle }}
                </a-tooltip>
              </div>
              <div class="flow-item-status">
                <InstanceStatusTag :record="item" />
              </div>
            </div>
            <div class="flow-item-b">
              <div class="flow-item-b-user">审批：{{ getCurrentApproverListWrapper(item?.currentApproverListWrapper) }}</div>
              <div class="flow-item-b-time">到达时间：{{ item.createTime }}</div>
            </div>
          </div>
        </div>

        <a-pagination
          :current="pageNo"
          :page-size="pageSize"
          :total="total"
          size="small"
          class="pagination"
          v-if="total > 0"
          show-size-changer
          show-quick-jumper
          @change="pageSizeChange"
          @showSizeChange="showSizeChange"
          :show-total="total => `共${total}条`"
        />

        <div class="news-list-empty" v-else>
          <a-empty description="暂无数据" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
        </div>
      </a-spin>
    </template>
  </card-widget>

  <!-- 详情 -->
  <WorkflowTaskDetail
    v-model:visible="isShowEdit"
    mask
    v-if="isShowEdit"
    :data="current"
    @done="getDataList(false)"
    :taskCondition="activeKey"
  />
</template>

<script setup name="FlowTaskWidget">
import { onMounted, ref, onUnmounted, defineAsyncComponent } from 'vue';
import { FlowTaskApi } from '@/views/mid/workflow/task/list/api/FlowTaskApi';
import CardWidget from '@/views/home/components/card_widget.vue';
import { Empty } from 'ant-design-vue';

const InstanceStatusTag = defineAsyncComponent(() => import('@/views/mid/workflow/task/list/components/detail/instance-status-tag.vue'));
// 流程详情
const WorkflowTaskDetail = defineAsyncComponent(() => import('@/views/mid/workflow/task/list/components/task-detail.vue'));

const props = defineProps({
  /**
   * 是否是预览模式
   */
  preview: {
    type: Boolean,
    default: false
  },
  widget: Object,
  // 门户设计id
  designId: {
    type: String,
    default: ''
  }
});

const loading = ref(false);

// 数据列表
const dataList = ref([]);
// tab选中的key
const activeKey = ref(10);

// tabs
const flowTaskTabs = [
  { name: '待办', type: 10, key: 10, number: 'toDoTaskNumber' },
  { name: '待阅', type: 20, key: 20, number: 'toReadTaskNumber' },
  { name: '已办', type: 30, key: 30, number: 'alreadyDoneTaskNumber' },
  { name: '已阅', type: 40, key: 40, number: 'alreadyReadTaskNumber' }
];

// 定时器  定时刷新待办列表
let taskListInterval = null;

const userNumberObj = ref({
  toDoTaskNumber: 0,
  toReadTaskNumber: 0,
  alreadyDoneTaskNumber: 0,
  alreadyReadTaskNumber: 0
});

// 当前所在页数
const pageNo = ref(1);
// 当前分页条数
const pageSize = ref(10);
// 总数据
const total = ref(0);

const isShowEdit = ref(false);

const current = ref(null);

const style = ref({});

const showHeaderFlag = ref(false);

const title = ref('');

/**
 * tab点击事件
 */
const tabClick = e => {
  pageNo.value = 1;
  pageSize.value = 10;
  activeKey.value = e;
  getDataList(false);
};

/**
 * 获取数据列表
 */
const getDataList = (isNum = true) => {
  if (isNum) getUserTotalTaskNum();
  loading.value = true;
  // 获取列表数据
  FlowTaskApi.getUserTasksRuTask({
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    taskCondition: activeKey.value
  })
    .then(res => {
      dataList.value = res.data.rows;
      total.value = res.data.totalRows;
    })
    .catch(() => {
      dataList.value = [];
    })
    .finally(() => (loading.value = false));
};

// 分页的页数改变
const pageSizeChange = (page, pageSize) => {
  pageNo.value = page;
  getDataList(false);
};

// 条数改变
const showSizeChange = (current, size) => {
  pageSize.value = size;
  getDataList(false);
};

// 获取待办、待阅（抄送我的）、已办、我发起的任务数量
const getUserTotalTaskNum = async () => {
  userNumberObj.value = await FlowTaskApi.getUserTotalTaskNum();
};

/**
 * 任务点击
 * @param item
 */
const flowItemClick = async item => {
  if (props.preview) return;
  current.value = item;
  isShowEdit.value = true;
};

// 设置当前办理人
const getCurrentApproverListWrapper = list => {
  let name = '';
  if (list?.length > 0) {
    name = list.map(item => item.realName).join(';');
  }
  return name;
};

/**
 * 更新组件
 */
const updateWidget = () => {
  getDataList();
  if (props.widget?.param) {
    title.value = props.widget?.param?.elementName;
    if (props.widget?.param?.config) {
      const { showHeader, borderLeft, borderRight, borderTop, borderBottom } = props.widget?.param?.config;
      showHeaderFlag.value = showHeader;
      style.value = {
        'border-left': borderLeft,
        'border-right': borderRight,
        'border-top': borderTop,
        'border-bottom': borderBottom
      };
    }
  }

  if (!props.preview) {
    // 定时器 5秒刷新
    taskListInterval = setInterval(getDataList, 60 * 1000);
  }
};

onMounted(() => {
  updateWidget();
});

onUnmounted(() => {
  // 页面卸载 清除定时器
  if (taskListInterval) {
    clearInterval(taskListInterval);
  }
});

defineExpose({
  updateWidget
});
</script>

<style scoped lang="less">
.news-header {
  display: flex;
  position: relative;
}

.news-header-left {
  flex: 1;
}

.news-header-right {
  position: absolute;
  right: 20px;
  font-size: 14px;
  color: #808080;
  cursor: pointer;
}

.news-header-right-content {
  display: flex;
  align-items: center;
}

.news-list {
  margin: 0px 0 16px 0;
  height: calc(100% - 62px - 32px - 16px);
  overflow-y: auto;
}

.pagination {
  text-align: right;
  height: 24px;
  margin-top: 8px;
}

.news-list-empty {
  width: 100%;
  height: calc(100% - 62px);
  position: relative;
  .ant-empty {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -32px;
    margin-top: -42px;
  }
}

.flow-item {
  width: 100%;
  cursor: pointer;

  &:not(:last-child) {
    margin-bottom: 16px;
  }

  .flow-item-h {
    width: 100%;
    display: flex;
    align-items: center;

    .flow-item-number {
      display: flex;
      padding: 0px 8px;
      color: #fff;
      font-size: 12px;
      font-weight: 700;
      justify-content: center;
      align-items: center;
      border-radius: 4px;
      background: #6f9ae7;
      margin-right: 8px;
    }
    .flow-item-title {
      flex: inherit;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 16px;
      color: #43505e;
      cursor: pointer;
      &:hover {
        color: var(--primary-color);
      }
    }
    .flow-item-status {
      width: 60px;
      margin-left: 8px;
      :deep(.ant-tag) {
        padding: 1px 8px !important;
        min-width: auto;
      }
    }
  }
  .flow-item-b {
    display: flex;
    align-items: center;
    margin-top: 8px;
    color: #60666b;
    font-size: 12px;
    font-weight: 400;

    .flow-item-b-user {
      margin-left: 37.35px;
    }
    .flow-item-b-time {
      margin-left: 16px;
    }
  }
}
</style>
