<template>
  <view>
    <!-- v-if="autoList.length > 0 && autoList.includes('审批列表') && !isHidden" -->
    <view
      class="header_box"
      v-if="autoList.length > 0 && autoList.includes('审批列表') && !isHidden"
    >
      <view class="header_bg">
        <headers :showBack="false" :themeType="'white'">
          <view class="headerName"> 个人中心 </view>
        </headers>
        <view class="search">
          <uni-search-bar
            v-model="searchValue"
            bgColor="#EEEEEE"
            radius="5"
            placeholder="搜索流程"
            clearButton="auto"
            cancelButton="none"
          ></uni-search-bar>
        </view>
        <!-- <uni-notice-bar show-icon show-close scrollable text="欢迎体验 wflow-pro工作流 移动端" /> -->
        <view class="process-count">
          <view class="count-item todo-item" @click="to(0)">
            <view class="item-text">
              <view>待我处理</view>
              <view>{{ counter.todo }}</view>
            </view>
            <image mode="aspectFit" src="/static/image/pending1.png"></image>
          </view>
          <view>
            <view class="count-item" @click="to(2)">
              <view class="item-text">
                <view>我发起的</view>
                <view>{{ counter.mySubmited }}</view>
              </view>
              <image mode="aspectFit" src="/static/image/submit1.png"></image>
            </view>
            <view class="count-item" @click="to(3)">
              <view class="item-text">
                <view>抄送我的</view>
                <view>{{ counter.cc }}</view>
              </view>
              <image mode="aspectFit" src="/static/image/cc1.png"></image>
            </view>
          </view>
        </view>
      </view>
      <view class="w-app-items">
        <uni-collapse>
          <uni-collapse-item
            class="w-group"
            :open="true"
            v-for="(group, index) in dataList"
            :key="'group_' + index + group.items.length"
            :border="false"
            title-border="none"
          >
            <template #title>
              <text class="w-group-title">{{ group.name }}</text>
              <text>({{ group.items.length }})</text>
            </template>
            <view class="w-form-items">
              <view
                class="w-form-item"
                v-for="(item, i) in group.items"
                :key="'item_' + index"
                @click="toSubmit(item)"
              >
                <view
                  class="w-form-icon"
                  :style="'background-color: ' + item.logo.background"
                >
                  <l-icon
                    class="w-form-icon-ico"
                    color="#FFFFFF"
                    size="64rpx"
                    :name="item.logo.icon"
                  />
                </view>
                <view class="w-form-name">{{ item.formName }} </view>
              </view>
              <!-- 用来占位的 -->
              <view
                class="w-form-item"
                style="height: 0"
                v-for="(item, i) in 2"
                :key="'item_' + index"
              >
              </view>
            </view>
          </uni-collapse-item>
        </uni-collapse>
      </view>
    </view>
    <!-- <view v-else>
			<view v-if="!loading" class="nullText">您无权限查看</view>
		</view> -->
  </view>
</template>

<script setup>
import headers from "@/components/headers/headers.vue";
import { computed, onMounted, ref, watch } from "vue";
import {
  getGroupModelsByUser,
  getProcessCountData,
  getModuleAndMenuList,
} from "@/api/model.js";
import { onPullDownRefresh } from "@dcloudio/uni-app";
import { debounce } from "@/utils/tool.js";
const isHidden = ref(false);
const searchValue = ref(null);
const searchResult = ref([]);
const appList = ref([]);
const recentlyUsed = ref([]);
const counter = ref({
  cc: 0,
  mySubmited: 0,
  todo: 0,
});
const autoList = ref([]);
const loading = ref(true);

onMounted(() => {
  getPageData();
  recentlyUsed.value = uni.getStorageSync("recentlyUsed") || [];
  getAuto();
  // uni.showToast({
  // 	title: '暂未开发，敬请期待',
  // 	icon: 'none'
  // })
});

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

const searchDebounce = debounce(() => doSearch(), 800);

function getAuto() {
  // 获取工作台显示权限
  let loginUser = JSON.parse(uni.getStorageSync("loginUser"));
  getModuleAndMenuList({
    projectSn: loginUser.sn,
    moduleType: 7,
    userId: loginUser.userId,
  }).then((res) => {
    console.log(JSON.stringify(res), 777888);
    let list = res.data.result.menuList;
    console.log("我的数据啊啊啊", JSON.stringify(list));
    autoList.value = list.map((item) => item.name);
    loading.value = false;
  });
}

async function filterRecentlyUsed(collect) {
  recentlyUsed.value = recentlyUsed.value.filter((v) => collect.has(v.formId));
  recentlyUsedStore();
}

const dataList = computed(() => {
  if ((searchValue.value || "").trim() === "") {
    if (recentlyUsed.value.length > 0) {
      return [
        {
          id: 0,
          name: "最近使用",
          items: recentlyUsed.value,
        },
        ...appList.value,
      ];
    }
    return appList.value;
  }
  return [
    {
      id: 0,
      name: "搜索结果",
      items: searchResult.value,
    },
  ];
});

function doSearch() {
  searchResult.value.length = 0;
  appList.value.forEach((group) => {
    group.items.forEach((item) => {
      if (item.formName.indexOf(searchValue.value) > -1) {
        searchResult.value.push(item);
      }
    });
  });
}

function getPageData() {
  const idSet = new Set();
  getGroupModelsByUser(
    {},
    {
      TenantId: JSON.parse(uni.getStorageSync("loginUser")).sn,
    }
  )
    .then((rsp) => {
      appList.value = rsp.data
        .filter((v) => v.items.length > 0 && v.id !== 0)
        .map((group) => {
          group.items.forEach((item) => {
            idSet.add(item.formId);
            item.logo = JSON.parse(item.logo || "{}");
          });
          return group;
        });
      filterRecentlyUsed(idSet);
      uni.stopPullDownRefresh();
    })
    .catch(() => {
      recentlyUsed.value.length = 0;
      isHidden.value = true;
      uni.stopPullDownRefresh();
      uni.showToast({
        title: "暂未开发，敬请期待",
        icon: "none",
      });
    });

  getProcessCountData()
    .then((rsp) => {
      counter.value = rsp.data;
      uni.stopPullDownRefresh();
    })
    .catch(() => {
      uni.stopPullDownRefresh();
      isHidden.value = true;
      uni.showToast({
        title: "暂未开发，敬请期待",
        icon: "none",
      });
    });
}

function to() {
  // uni.switchTab({
  // 	url: '/pages/workspace/workspace'
  // })
  // console.log(JSON.stringify(webUni));
  // webUni.webView.postMessage({
  // 	data: {
  // 		typee: "topage",
  // 		url: "/pages/workspace/workspace"
  // 	}
  // })
  // setTimeout(() => {
  // 	uni.$emit('to:workspace', v)
  // }, 200)
}

function toSubmit(item) {
  if (!item.processDefId) {
    uni.showToast({
      icon: "none",
      title: "该流程还未发布😢",
    });
    return;
  }
  const i = recentlyUsed.value.findIndex((v) => item.formId === v.formId);
  if (i > -1) {
    recentlyUsed.value.splice(i, 1);
  }
  if (recentlyUsed.value.length > 10) {
    recentlyUsed.value.splice(recentlyUsed.value.length - 1, 1);
  }
  recentlyUsed.value.unshift(item);
  recentlyUsedStore();
  uni.navigateTo({
    url: `/pages/submit/InitiateProcess?code=${item.formId}`,
  });
}

function recentlyUsedStore() {
  uni.setStorageSync("recentlyUsed", recentlyUsed.value);
}

// watch(searchValue, async () => {
// 	searchDebounce()
// })
</script>

<style>
page {
  background-color: #f4f5f7 !important;
}
</style>

<style lang="less" scoped>
.header_box {
  position: relative;

  .header_bg {
    width: 100vw;
    min-height: 330rpx;
    background-image: url(/static/image/main_bg1.png);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    // background: linear-gradient(180deg, #2B8DF3 0%, #F4F5FD 100%);
    // position: absolute;
    // top: 0;
    position: relative;
  }
}
.nullText {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 28rpx;
}

.w-group {
  padding: 38rpx 0;
  width: auto;
  background-color: white;
  margin: 6rpx 0;
  border-radius: 10rpx;
}

.w-group-title {
  font-weight: 600;
  font-size: 35rpx;
  margin-left: 32rpx;
}

.search {
	.uni-searchbar {
		padding: 20rpx 28rpx;
	}
	/deep/ .uni-searchbar__box {
		background-color: white !important;
	}
//   background-color: white;
}

.w-app-items {
  padding: 0 16rpx;

  :deep(.uni-collapse) {
    background: none;
  }
}

.process-count {
  display: flex;
  padding: 28rpx;

  & > view:first-child {
    width: 40%;
  }

  & > view:last-child {
    width: 60%;
  }

  .todo-item {
    image {
      width: 96rpx;
      height: 96rpx;
    }

    .item-text {
      display: block;
      height: 100%;

      & > view:first-child {
        margin-bottom: 38rpx;
      }

      & > view:last-child {
        color: #ec8151 !important;
        font-weight: bold;
        font-size: 58rpx !important;
      }
    }
  }

  .count-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 6rpx;
    background-color: #ffffff;
    border-radius: 10rpx;
    padding: 24rpx;

    .item-text {
      & > view:last-child {
        color: #b9b8b8;
        font-weight: bold;
        font-size: 38rpx;
      }
    }
  }

  image {
    width: 58rpx;
    height: 58rpx;
  }
}

.w-form-items {
  display: flex;
  flex-wrap: wrap;
  padding: 32rpx;
  justify-content: space-between;

  .w-form-item {
    width: 144rpx;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
  }

  .w-form-name {
    width: 128rpx;
    padding: 6rpx 0;
    overflow: hidden;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .w-form-icon {
    width: 96rpx;
    height: 96rpx;
    border-radius: 16rpx;
    background-color: burlywood;
    display: flex;
    justify-content: center;
    align-items: center;

    .w-form-icon-ico {
      color: white;
    }
  }
}
</style>
