<template>
  <!-- autoList.length > 0 -->
  <view class="content header_bg" v-if="autoList.length > 0">
    <headers :showBack="false" :themeType="'white'">
      <view class="headerName"> 个人中心 </view>
    </headers>
    <view class="nav-type">
      <movable-area style="width: 100%; height: 100%; overflow: hidden">
        <movable-view
          direction="horizontal"
          style="min-width: 100%; width: 100%; height: 100%"
        >
          <uni-segmented-control
            :current="current"
            :values="tabs"
            @clickItem="switchItem"
            styleType="text"
            activeColor="#ffffff"
          ></uni-segmented-control>
        </movable-view>
      </movable-area>
      <!-- <uni-segmented-control :current="current" :values="tabs" @clickItem="switchItem" styleType="text"
				activeColor="#4C87F3"></uni-segmented-control> -->
    </view>
    <swiper
      :current="current"
      :duration="300"
      @change="tabChange"
      :style="{ height: contentHeight + 'px' }"
    >
      <swiper-item class="datas" v-for="(data, i) in pageData" :key="i">
        <scroll-view
          v-if="data.length > 0"
          class="scrool-more"
          :refresher-threshold="0"
          @scrolltolower="toNextPage"
          :scroll-top="scrollTo.current"
          @scroll="scroll"
          enablePullDownRefresh
          @scrolltoupper="() => {}"
          :show-scrollbar="true"
          :style="{ height: contentHeight + 'px' }"
          scroll-y="true"
          scroll-with-animation="true"
        >
          <view
            class="process-item"
            v-for="(item, i) in data"
            :key="item.instanceId + i"
            @click="showInstance(item)"
          >
            <view>
              <text
                >{{ (item.owner || item.staterUser || {}).name }}提交的
                {{ item.processDefName }}</text
              >
              <uni-tag
                class="process-item-status"
                circle="true"
                :text="getStatus(item).text"
                :type="getStatus(item).type"
                inverted
              ></uni-tag>
            </view>
            <view class="form-content">
              <view
                v-for="fd in item.formAbstracts || []"
                :key="fd.id"
                class="form-content-it"
              >
                <text style="color: #b5b5b5">{{ fd.name }}: </text>
                <text class="over-tip">{{ getFormValText(fd) }}</text>
              </view>
            </view>
            <view class="process-item-footer">
              <avatar
                :name="(item.owner || item.staterUser).name"
                :src="getRes((item.owner || item.staterUser).avatar)"
                :size="30"
              ></avatar>
              <text>在 {{ item.createTime || item.startTime }} 提交 </text>
            </view>
          </view>
          <uni-load-more
            :status="status"
            mode="scaleToFill"
            :showIcon="false"
          ></uni-load-more>
        </scroll-view>
        <image
          v-else
          class="nodata"
          src="/static/image/noData.png"
          mode="widthFix"
        ></image>
      </swiper-item>
    </swiper>
  </view>
  <!-- <view v-else>
		<view v-if="!loading" class="nullText">您无权限查看</view>
	</view> -->
</template>

<script setup>
import headers from "@/components/headers/headers.vue";
import Avatar from "@/components/Avatar.vue";
import { computed, nextTick, ref } from "vue";
import taskApi from "@/api/task";
import {
  getModuleAndMenuList,
  getGroupModelsByUser,
  getProcessCountData,
} from "@/api/model.js";
import { getFormValText, getRes } from "@/utils/tool.js";
import {
  onLoad,
  onUnload,
  onPullDownRefresh,
  onReachBottom,
} from "@dcloudio/uni-app";
import { getTaskResult, getProcTag } from "@/utils/ProcessUtil.js";
const tabs = computed(() => {
  const navs = ["待我处理", "已处理的", "我发起的", "抄送我的"];
  let arr = JSON.parse(JSON.stringify(autoList.value));
  arr = arr.filter((item) => navs.includes(item));
  // pageData.value = arr.map(() => []);
  arr[current.value] =
    (arr[current.value] || "") + `-${datas.value.total || 0}`;
  return arr;
});

const contentHeight = computed(() => {
  return uni.getSystemInfoSync().windowHeight - 40;
});

const scrollTo = ref({
  current: 0,
  old: 0,
});
const current = ref(0);
const status = ref("more");
const params = ref({
  pageSize: 10,
  pageNo: 1,
  code: "",
});

//定义四组页面数据
const pageData = ref([[], [], [], []]);

const datas = ref({
  pages: 1,
  size: 10,
  total: 0,
  records: [],
});

let autoList = ref([]);
let loading = ref(true);
const isHidden = ref(false);
// onMounted(() => {
// 	getPageData()
// })
// 临时效果-为了隐藏内容
function getPageData() {
  const idSet = new Set();
  getGroupModelsByUser(
    {},
    {
      TenantId: JSON.parse(uni.getStorageSync("loginUser")).sn,
    }
  )
    .then((rsp) => {})
    .catch(() => {
      isHidden.value = true;
    });

  getProcessCountData()
    .then((rsp) => {})
    .catch(() => {
      isHidden.value = true;
    });
}

function getStatus(item) {
  let navs = tabs.value[current.value];
  if (navs.indexOf("-") >= 0) {
    navs = navs.split("-")[0];
  }
  switch (navs) {
    case "待我处理":
      return {
        text: "待处理",
        type: "warning",
      };
    case "已处理的":
      return getTaskResult(item);
    case "我发起的":
    case "抄送我的":
      return getProcTag(item.result);
  }
  // case 0:
  // 	return {
  // 		text: '待处理', type: 'warning'
  // 	};
  // case 1:
  // 	return getTaskResult(item);
  // case 2:
  // case 3:
  // 	return getProcTag(item.result);
}

function getAuto() {
  // 获取工作台显示权限
  let loginUser = JSON.parse(uni.getStorageSync("loginUser"));
  getModuleAndMenuList({
    projectSn: loginUser.sn,
    moduleType: 7,
    userId: loginUser.userId,
  }).then((res) => {
    // let list = [];
    let list = res.data.result.menuList;
    autoList.value = list.map((item) => item.name);
    let arr = JSON.parse(JSON.stringify(autoList.value));
    const navs = ["待我处理", "已处理的", "我发起的", "抄送我的"];
    arr = arr.filter((item) => navs.includes(item));
    autoList.value = arr;
    pageData.value.length = arr.length;
    loading.value = false;
    console.log(autoList.value);
    getDataList();
  });
}

function switchItem(v) {
  current.value = v.currentIndex;
  params.value.pageNo = 1;
  getDataList();
  scrollToTop();
}

function scroll(e) {
  scrollTo.value.old = e.detail.scrollTop;
}

function scrollToTop() {
  scrollTo.value.current = scrollTo.value.old;
  nextTick(() => {
    scrollTo.value.current = 0;
  });
}

function tabChange(e) {
  let index = e.target.current || e.detail.current;
  switchItem({
    currentIndex: index,
  });
}

function getDataRequest() {
  let navs = tabs.value[current.value];
  console.log(tabs.value, current.value);
  if (navs.indexOf("-") >= 0) {
    navs = navs.split("-")[0];
  }
  switch (navs) {
    case "待我处理":
      return taskApi.getUserTodoList(params.value);
    case "已处理的":
      return taskApi.getIdoList(params.value);
    case "我发起的":
      return taskApi.getUserSubmittedList(params.value);
    case "抄送我的":
      return taskApi.getCcMeList(params.value);
  }
}

function getDataList() {
  status.value = "loading";
  try {
    getDataRequest()
      .then((rsp) => {
        uni.stopPullDownRefresh();
        console.log(JSON.stringify(rsp.data), 888999);
        datas.value.total = rsp.data.total;
        if (params.value.pageNo === 1) {
          //datas.value.records.length = 0
          pageData.value[current.value].length = 0;
        }
        pageData.value[current.value].push(...rsp.data.records);
        //datas.value.records.push(...rsp.data.records)
        status.value =
          params.value.pageNo * params.value.pageSize < datas.value.total
            ? "more"
            : "noMore";
      })
      .catch((err) => {
        uni.stopPullDownRefresh();
      });
  } catch (e) {
    //TODO handle the exception
    console.log(e);
  }
}

function showInstance(item) {
  uni.navigateTo({
    url: `/pages/instance/instancePreview?instanceId=${
      item.instanceId
    }&nodeId=${current.value === 0 ? item.nodeId : null}`,
  });
}

onLoad((v) => {
  uni.hideTabBar();
  getDataList();
  getAuto();
  // uni.showToast({
  // 	title: '暂未开发，敬请期待',
  // 	icon: 'none'
  // })
});

// 监听事件，快速跳转到对应项
uni.$on("to:workspace", (v) => {
  switchItem({
    currentIndex: v,
  });
});

onUnload(() => uni.$off("to:workspace"));

onPullDownRefresh(() => {
  getDataList();
});

function toNextPage() {
  params.value.pageNo++;
  getDataList();
}
</script>

<style lang="less" scoped>
.header_bg {
  width: 100vw;
  min-height: 330rpx;
  background-image: url(/static/image/main_bg1.png);
  background-repeat: no-repeat;
  background-size: 100%;
  // background: linear-gradient(180deg, #2B8DF3 0%, #F4F5FD 100%);
  // position: absolute;
  // top: 0;
  position: relative;
}
page {
  background-color: #f4f5f7;
}

.nullText {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 28rpx;
}

.nav-type {
  // position: fixed;
  // top: 0;
  width: 100%;
  height: 72rpx;

  // z-index: 999;
  // overflow-x: scroll;
  //   background-color: white;
  :deep(.segmented-control) {
    width: 100%;
    padding: 0 28rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .segmented-control__item {
      width: max-content;
      flex: none;
    }
    .segmented-control__item:not(:last-child) {
      margin-right: 50rpx;
    }
    .segmented-control__text {
      color: rgba(255, 255, 255, 0.7) !important;
    }
    .segmented-control__item--text {
      border-bottom: none;
      color: white !important;
    }
  }
}

.datas {
  position: relative;

  .nodata {
    width: 100%;
    height: auto;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .process-item {
    margin: 32rpx;
    border-radius: 13rpx;
    background-color: white;
    padding: 26rpx 32rpx;
    position: relative;

    .uni-tag {
      font-weight: 400;
    }

    .process-item-status {
      position: absolute;
      right: 32rpx;
    }

    .form-content {
      font-size: 26rpx;
      color: #8b8b8b;
      margin: 16rpx 16rpx;

      .form-content-it {
        overflow-x: hidden;
        display: flex;
        flex-wrap: wrap;

        .over-tip {
          margin-left: 5px;
        }
      }
    }

    .process-item-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;

      & > text:last-child {
        font-size: 22rpx;
        color: #8b8b8b;
      }
    }
  }
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>
