<template>
  <div>
    <div class="resource" :style="{ height: innerHeight - 50 + 'px' }">
      <div class="resource-content">
        <div class="resource-header">
          <div class="resource-header-title">
            <template v-if="view_type != 'company'">
              <span class="container-title">团队资源切换</span>
              <div class="chang-btns" @click="teamsDialog = true">
                <span v-if="group_name != ''">{{ group_name }}</span>
                <el-icon style="margin-left: 5px"><Switch /></el-icon>
              </div>
            </template>
            <template v-else>
              <span class="container-title">资源管理</span>
            </template>
          </div>
          <div class="resource-header-btn">
            <div class="search-input">
              <el-input class="search-input-box" v-model="search_value" />
              <el-icon class="search-icon" @click="init"><Search /></el-icon>
            </div>
            <el-button type="primary" @click="goCecommend()" style="margin-right: 5px">推荐</el-button>
            <UploaderBtn :belong="belong" :containerType="select_type" @updateEnd="init" />
          </div>
        </div>
        <TypesNav @claSelect="typesSelect" />
        <ClassNav :datas="cla_list" @claSelect="claSelect" />
        <el-scrollbar style="margin-top: 20px" :style="{ height: innerHeight - 380 + 'px' }">
          <div v-if="select_type == 'font'">
            <el-table :data="original_list">
              <el-table-column prop="img" label="字体预览">
                <template #default="{ row }">
                  <el-image :src="row.img" style="filter: invert(0.8); height: 50px" />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="字体名称" />
              <el-table-column prop="fontFamily" label="font family" />
              <el-table-column prop="#" label="操作">
                <template #default="{ row }">
                  <el-button type="danger" round @click="handleDeleteFont(row)">删除</el-button>
                  <el-button type="primary" round @click="setCla(row)">设置分类</el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="params.page" v-model:limit="params.limit" @pagination="getList" />
          </div>

          <div v-else v-infinite-scroll="getList" :infinite-scroll-immediate="false" ref="waterfull" class="infinite-list container" infinite-scroll-distance="50" style="padding: 20px">
            <NewWaterFall :data="data_list" :ref="waterFall">
              <template #item="{ item }">
                <div class="mask">
                  <div class="mask-btn">
                    <!-- <el-button type="primary" icon="Edit" round @click="toEdit(item)"></el-button> -->
                    <div></div>
                    <div class="mask-btn-right">
                      <el-button type="primary" round>
                        <el-icon style="transform: rotate(90deg)"><MoreFilled /></el-icon>
                      </el-button>
                      <div class="popover-btn-box">
                        <div class="popover-btn" style="font-size: 14px; font-weight: 500; line-height: 16px; color: #33383e" @click="changeCla(item)">编辑分类</div>
                        <!-- <div class="popover-btn" style="font-size: 14px; font-weight: 500; line-height: 16px; color: #33383e" @click="openDialog">创建副本</div> -->
                        <div class="popover-btn" style="font-size: 14px; font-weight: 500; line-height: 16px; color: #33383e" @click="deleteTemplate(item)">删除</div>
                      </div>
                    </div>
                  </div>
                  <el-button type="primary" round @click="toEdit(item)" v-if="select_type == 'template'">立即创作</el-button>
                  <el-button type="primary" round @click="downUrl(item.thumb)" v-if="select_type == 'mraw'">下载</el-button>
                </div>
              </template>
            </NewWaterFall>
          </div>
        </el-scrollbar>
        <div></div>
      </div>
    </div>
    <el-dialog v-model="teamsDialog" title="选择您所需要切换的团队">
      <div>
        <template v-for="item in teams_list">
          <el-button type="primary" :disabled="item._id == group_id" @click="changeTeam(item)" style="margin-bottom: 10px">{{ item.name }}</el-button>
        </template>
      </div>
    </el-dialog>
    <ClaSelect
      v-model:pushDialog="pushDialog"
      :belong="belong"
      :inputIds="item_ids"
      :pushFiles="font_list"
      :name="userName"
      :type="change_cla_type"
      @dialogClose="font_list = []"
      @updateEnd="getDialogClaList"
    />
  </div>
</template>
<script setup>
import useUserStore from '@/store/modules/user';
import ClassNav from '@/components/ClassNav/index.vue';
import UploaderBtn from '@/components/UploaderBtn/index.vue';
import ClaSelect from '@/components/ClaSelect/index.vue';
import TypesNav from '@/components/TypesNav/index.vue';
import { ElLoading } from 'element-plus';
import {
  getProfile,
  getGroupInfoById,
  getTemplate,
  listApolloByTeam,
  getGroupMraw,
  getGroupFront,
  delGroupFront,
  updateGroupFront,
  updateTemplate,
  delTemplate,
  getCompany,
  getZhiHuiSign,
  updateGroupInfoApp,
} from '@/api/zhihui/index.js';
import NewWaterFall from '@/components/NewWaterFall/index.vue';
import ZhihuiEditor from 'zhihui-editor-sdk';
import { getZHOption, downUrl } from '@/utils/index';
const { proxy } = getCurrentInstance();
const view_type = ref(proxy.$route.query.type);
const innerHeight = ref(0);
innerHeight.value = window.innerHeight;
const belong = ref(useUserStore().zhFirmId);
const userName = ref(useUserStore().name);
let loading = null;
const isLast = ref(false);
const isLoading = ref(false);
const teamsDialog = ref(false); //团队弹窗

const teams_list = ref([]); //团队列表
const data_list = ref([]); //素材数据
const group_id = ref(useUserStore().zhFirmId); //当前团队
const group_name = ref(''); //当前团队名称
const waterFall = ref(null);
const search_value = ref(''); //搜索值
const cla_list = ref([]); //分类列表
const cla_id = ref(''); //选中分类

const select_type = ref('template'); //选中类型
const original_list = ref([]); //原始数据
const pushDialog = ref(false);
const font_list = ref([]);
const item_ids = ref([]);
const change_cla_type = ref('font');

const total = ref(0);
const params = ref({
  filter: {}, //过滤条件
  page: 0,
  limit: 20,
  teamId: '',
});

function goCecommend() {
  proxy.$router.push({
    path: '/zhihui/firm/recommend',
    query: { groupId: group_id.value },
  });
}

async function getTeams() {
  if (view_type.value == 'company') {
    init();
    return;
  }
  let data = await getProfile(); //获取团队列表
  if (data.statusCode == 200) {
    teams_list.value = data.data.team;
    if (data.data.team.length > 0) {
      findGroup(data.data.team[0]._id);
    }
  }
}
//查询团队详情
async function findGroup(id) {
  let result = await getGroupInfoById({ id });
  if (result.statusCode == 200) {
    group_id.value = result.data._id;
    belong.value = group_id.value;
    group_name.value = `${result.data.name}-${result.data.creator.name}`;
    init();
  }
}
//改变团队
function changeTeam(item) {
  findGroup(item._id);
  teamsDialog.value = false;
}

//重置数据
function resetForm() {
  let zhFirmId = useUserStore().zhFirmId;
  if (zhFirmId) {
    params.value = {
      filter: {}, //过滤条件
      page: 0,
      limit: 20,
      teamId: group_id.value,
    };
    let filter_option = {};
    if (search_value.value != '') {
      filter_option.name = { $options: 'i', $regex: search_value.value };
    }
    if (cla_id.value != '') {
      filter_option.categoryIds = [cla_id.value];
    }
    params.value.filter = filter_option;
    data_list.value = [];
    isLast.value = false;
    isLoading.value = false;
  }
}
async function init() {
  let zhFirmId = useUserStore().zhFirmId;
  if (zhFirmId) {
    resetForm();
    getCla();
    getList(); //获取模板
  }
}
//分类选择
function claSelect(cla) {
  cla_id.value = cla;
  resetForm();
  getList();
}

//类型切换
function typesSelect(value) {
  select_type.value = value;
  init();
}

//获取列表
async function getList() {
  if (isLast.value || isLoading.value) {
    return;
  }

  isLoading.value = true;
  loading = ElLoading.service({ lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)' });
  let data = {};
  if (select_type.value == 'template') {
    data = await getTemplate(params.value);
  }
  if (select_type.value == 'mraw') {
    data = await getGroupMraw(params.value);
  }
  if (select_type.value == 'font') {
    data = await getGroupFront(params.value);
  }
  loading.close();
  if (data?.statusCode == 200) {
    let { list } = data.data;
    let info = [];
    list?.map(item => {
      if (item.thumb) {
        info.push({ id: item._id, thumb: item.thumb, name: item.name, linkId: item.linkId, categoryIds: item.categoryIds });
      }
    });
    if (params.value.page == 0) {
      data_list.value = info;
      original_list.value = list;
    } else {
      data_list.value = data_list.value.concat(info);
      original_list.value = original_list.value.concat(list);
    }
    if (list.length < params.value.limit) {
      isLast.value = true;
    } else {
      params.value.page++;
    }
    total.value = data.data.total;
    isLoading.value = false;
    proxy.$forceUpdate();
  }
}
function toEdit(item) {
  let option = getZHOption(item.id, useUserStore().id, useUserStore().zhFirmId, group_id.value, () => {
    zhihuiEditor.closeIframe();
  });
  let zhihuiEditor = new ZhihuiEditor(option);
  zhihuiEditor.openIframe();
}

async function getCla() {
  let option = {
    teamId: group_id.value,
    type: select_type.value == 'font' ? 'font' : 'template',
  };
  let data = await listApolloByTeam(option);
  if (data.statusCode == 200) {
    cla_list.value = data.data;
  }
}
//删除字体
async function handleDeleteFont(item) {
  let data = await delGroupFront({ fontId: item._id, teamId: group_id.value });
  if (data.statusCode == 200) {
    init();
  }
}

async function getDialogClaList(ids) {
  let data = {};
  if (change_cla_type.value == 'font') {
    data = await updateGroupFront({
      categoryIds: ids,
      templateIds: [font_list.value[0].id],
      teamId: belong.value,
    });
  }
  if (change_cla_type.value == 'template') {
    data = await updateTemplate({
      categoryIds: ids,
      templateIds: [font_list.value[0].id],
      teamId: belong.value,
    });
  }
  if (data.statusCode != 200) {
    return proxy.$modal.msgError('更新失败-' + data.message);
  }
  pushDialog.value = false;
  init();
}
const deleteTemplate = async item => {
  let data = await delTemplate({ ids: [item.linkId], teamId: group_id.value });
  if (data.statusCode != 200) {
    return proxy.$modal.msgError('删除失败-' + data.message);
  }
  data_list.value = data_list.value.filter(e => e.linkId != item.linkId);
  // init();
};
const changeCla = item => {
  font_list.value = [item];
  if (item.categoryIds?.length > 0) {
    item_ids.value = item.categoryIds;
  }
  change_cla_type.value = 'template';
  pushDialog.value = true;
};

function setCla(item) {
  font_list.value = [{ thumb: item.img, name: item.name, id: item._id }];
  if (item.categoryIds.length > 0) {
    item_ids.value = item.categoryIds;
  }
  change_cla_type.value = 'font';
  pushDialog.value = true;
}
getTeams();
</script>
<style scoped lang="scss">
.resource {
  padding: 30px;
  background-color: #f7f7f7;
}
.resource-content {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 20px;
}
.resource-header {
  display: flex;
  justify-content: space-between;
  .resource-header-title {
    display: flex;
    .container-title {
      margin-bottom: 0;
      font-size: 24px;
      font-weight: 700;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        left: 0;
        bottom: 2px;
        width: 105%;
        height: 6px;
        border-radius: 3px;
        background: rgba(170, 163, 245, 0.6);
      }
    }
    .chang-btns {
      display: flex;
      margin-left: 20px;
      background-color: #3a2be0;
      border-radius: 20px;
      padding: 5px 20px;
      color: #fff;
      font-size: 15px;
      align-items: center;
      &:hover {
        cursor: pointer;
      }
    }
  }
}

.resource-header-btn {
  display: flex;
  align-items: center;
  .search-input {
    display: flex;
    align-items: center;
    margin-right: 20px;
    border-radius: 20px;
    border: solid 1px #e6e6e6;
    padding: 5px 10px;
    .search-input-box :deep(.el-input__wrapper) {
      border: unset;
      box-shadow: 0 0 0 0px;
    }
    .search-icon {
      margin-left: 10px;
      font-size: 20px;
      &:hover {
        cursor: pointer;
      }
    }
  }
}
.mask {
  position: absolute;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.2);
  z-index: 2;
  padding: 10px;
  border-radius: 20px;
  display: none;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  .mask-btn {
    display: flex;
    width: 100%;
    align-items: center;
    justify-content: space-between;
    .mask-btn-right {
      position: relative;
      .popover-btn-box {
        position: absolute;
        background-color: #fff;
        display: none;
        flex-direction: column;
        z-index: 99;
        right: 0;
      }
      &:hover {
        .popover-btn-box {
          position: absolute;
          background-color: #fff;
          display: flex;
        }
      }
    }
    .popover-btn {
      border-radius: 8px;
      width: 80px;
      padding: 8px;
      color: #33383e;
      font-weight: 400;
      font-size: 14px;
      line-height: 20px;
      cursor: pointer;
      text-align: center;
      &:hover {
        background-color: #f4f3ff;
      }
    }
  }
}
</style>
