<template>
  <div class="material-list-wrap">
    <div class="search-container">
      <BCSearch
        :filterOptions="materialSearchDict"
        placeholder="搜索标题或摘要"
        @onChange="onSearch"
        @onMaterialTypeChange="onMaterialTypeChange"
      />
    </div>
    <nav>
      <div class="tabs_header">
        <Tabs
          v-model:active="headerNavActive"
          @click="onNavChange"
          line-width="20"
        >
          <Tab name="user" title="个人库"></Tab>
          <Tab name="corp" title="企业库"></Tab>
        </Tabs>
      </div>
    </nav>
    <div class="material-title-wrap">
      <MaterialTitle
        :group_name="chosedGroupData?.group_name"
        :env_data="env_data"
        :total="materialGroupCount"
        :group_scope="headerNavActive === 'corp' ? 2 : 1"
        @onToggleGroup="onToggleGroup"
      />
    </div>
    <main>
      <WlLoadMore
        v-model="isLoading"
        :finished="isFinished"
        @load="getMaterial"
      >
        <ul class="material_wrap">
          <li
            v-for="item in materials"
            :key="item.material.id"
            @click="handleChoose(item.material)"
          >
            <MaterialCell
              :data="item"
              :disabled="onCheckedFile(item.material)"
              :sub_type_not_allow="sub_type_not_allow(item.material)"
            />
          </li>
        </ul>
      </WlLoadMore>
    </main>
    <BCGroupChoosePopup
      v-model="chooseGroupPopupVisible"
      ref="groupChoosePopupRef"
      :showAllItem="true"
      :env_data="env_data"
      :group_scope="headerNavActive === 'corp' ? 2 : 1"
      @onChange="onGetGroupData"
    />
  </div>
</template>

<script lang="ts">
export default {
  name: "BCMaterialList",
};
</script>

<script lang="ts" setup>
import Api from "./http/api";
import { Tab, Tabs } from "vant";
import Store from "@mobileUI/store";
import { ref, computed } from "vue";
import { materialSearchDict } from "./utils/dict";
import WlNotice from "@mobileUI/components/WlNotice";
import usePagination from "@mobileUI/hooks/usePagination";
import MaterialCell from "./components/MaterialCell/index.vue";
import MaterialTitle from "./components/MaterialTitle/index.vue";
import BCSearch from "@mobileUI/components/BCSearch/src/index.vue";
import WlLoadMore from "@mobileUI/components/WlLoadMore/src/index.vue";
import BCGroupChoosePopup from "@mobileUI/components/BCGroupChoosePopup/src/index.vue";
import {
  TChooseGroupList,
  TChooseGroupCount,
} from "@mobileUI/typings/BCGroupChoosePopup";

const { limit, page_count, isLoading, isFinished, judgeLoadStatus } =
  usePagination();

type Props = {
  checkedData: any[];
  env_data: TEnv.TEnvData;
  not_allow_sub_type_arr: Array<number>;
};
const props = withDefaults(defineProps<Props>(), {
  checkedData: () => [],
  env_data: () => {
    return {
      sid: "",
      domain: "",
      corp_id: "",
      node_env: "uat",
      app_id: "",
      token: "",
      card_resource: "",
    };
  },
  not_allow_sub_type_arr: () => [],
});

const emit = defineEmits<{
  (e: "onHandleChecked", val: Object);
}>();
Store.corp_id = props.env_data.corp_id;
Store.node_env = props.env_data.node_env;
Store.sid = props.env_data.sid;
Store.token = props.env_data.token;
Store.card_resource = props.env_data.card_resource;
const keyword = ref("");
const materials = ref([]);
const materialGroupCount = ref(0);
const groupChoosePopupRef = ref();
const headerNavActive = ref("corp");
const chooseGroupPopupVisible = ref(false);
const chosedGroupData = ref<TChooseGroupList>(null);
const materialTypeList = ref<string[]>(null);
const materialGroupCountDict = ref<TChooseGroupCount>({});

const onToggleGroup = () => {
  chooseGroupPopupVisible.value = true;
  groupChoosePopupRef.value.onResetData();
};

// 物料计数
const onGetGroupTotal = () => {
  const { id: group_id } = chosedGroupData.value || {};
  const { corp_count_dict, user_count_dict, user_count, corp_count } =
    materialGroupCountDict.value;
  let total = 0;
  if (headerNavActive.value === "user") {
    total = group_id ? user_count_dict[group_id] : user_count;
  } else {
    total = group_id ? corp_count_dict[group_id] : corp_count;
  }
  materialGroupCount.value = total;
};

// 检查是否已选
const onCheckedFile = (item: any) => {
  return !!props.checkedData?.find(
    (res: any) =>
      res?.link?.title == item?.material_name &&
      res?.link?.picurl == item?.material_logo,
  );
};

//检查是否sub_type不符合规范
const sub_type_not_allow = computed(
  () => (material) =>
    props.not_allow_sub_type_arr.includes(material.material_subtype),
);

//获取资料列表
const getMaterial = async () => {
  const { data } = await Api.getMaterialList(
    {
      sort_list: {
        page_count: page_count.value,
        limit: limit.value,
        sort: [],
        keyword: keyword.value,
      },
      group_id: chosedGroupData.value?.id,
      material_type: materialTypeList.value,
      only_person: headerNavActive.value === "user",
      scope: headerNavActive.value === "user" ? 1 : 2,
    },
    headerNavActive.value,
  );
  if (page_count.value == 1) {
    materials.value = [];
  }
  materials.value = [...materials.value, ...(data.materials || [])];
  judgeLoadStatus(data.materials || [], data.count);
};

// 获取分组资料数
const onGetMaterialGroupCount = async () => {
  const { data } = await Api.getMaterialGroupCount({
    ctxenv: 1,
    keyword: keyword.value,
    material_type: materialTypeList.value || "",
  });
  const {
    corp_count = 0,
    corp_count_list = [],
    person_count = 0,
    person_count_list = [],
  } = data;
  materialGroupCountDict.value = {
    corp_count,
    user_count: person_count,
    corp_count_dict: corp_count_list.reduce((acc, item) => {
      acc[item.group_id] = item.count;
      return acc;
    }, {}),
    user_count_dict: person_count_list.reduce((acc, item) => {
      acc[item.group_id] = item.count;
      return acc;
    }, {}),
  };
  onGetGroupTotal();
};

const onSearch = (val) => {
  keyword.value = val;
  onResetData();
  onGetMaterialGroupCount();
};

const onMaterialTypeChange = (val) => {
  materialTypeList.value = val.value === 0 ? [] : [val.value];
  onResetData();
};

const onNavChange = () => {
  chosedGroupData.value = {};
  onResetData();
};

const onResetData = () => {
  page_count.value = 1;
  materials.value = [];
  isLoading.value = true;
  isFinished.value = false;
  getMaterial();
  onGetMaterialGroupCount();
};

const onGetGroupData = (item: TChooseGroupList) => {
  chosedGroupData.value = item;
  onResetData();
};

//点击文件事件
const handleChoose = (item: any) => {
  //判断是否已经选择过了改文件
  if (onCheckedFile(item)) return;
  else if (sub_type_not_allow.value(item)) {
    //判断是否允许点击
    WlNotice({
      message: "因小程序限制，此链接暂不支持添加至名片",
      type: "warning",
      duration: 5,
    });
    return;
  }
  emit("onHandleChecked", { ...item });
};

onResetData();
</script>

<style lang="scss" scoped>
.material-list-wrap {
  height: 100%;
  background-color: #fff;
  @extend %flex-direction-column;

  .search-container {
    padding: j(12) j(15) 0 j(15);
  }

  .material-title-wrap {
    padding: j(10) j(15);
    background-color: var(--wl-btn-dashed-bg);
  }

  main {
    height: 100%;
    background-color: var(--wl-btn-dashed-bg);
    @extend %overflow-auto;

    .material_wrap {
      padding: 0 j(15);

      li {
        padding: j(15) j(15) j(10) j(15);
        background-color: #ffffff;
        border-radius: 12px;
        margin-bottom: 12px;
      }
    }
  }

  nav {
    position: relative;
    width: j(180);
    padding: 0 j(6);
  }
}
</style>
