<template>
  <div>
    <div class="resource" :style="{ height: innerHeight - 50 + 'px' }">
      <div class="resource-content">
        <div class="resource-header">
          <div class="resource-header-title">
            <span class="container-title">资源管理</span>
          </div>
          <div class="resource-header-btn">
            <el-button type="primary" @click="createComment(false)" v-hasPermi="['zh:create:firm']">创建企业</el-button>
            <!-- <el-button type="primary" @click="openDialog">添加资源</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: 30px">
            <NewWaterFall :data="data_list" ref="waterFall">
              <template #item="{ item }">
                <div class="mask">
                  <el-button type="primary" round @click="toEdit(item)">编辑</el-button>
                </div>
              </template>
            </NewWaterFall>
          </div>
        </el-scrollbar>
        <div></div>
      </div>
    </div>
    <el-dialog v-model="createDialog" append-to-body>
      <el-form :model="createform">
        <el-form-item label="企业名称" :label-width="formLabelWidth">
          <el-input v-model="createform.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="createComment(true)">确 定</el-button>
          <el-button @click="createDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { getZhiHuiSign, createPersonCompany, updateUserInfo, listApolloByTeam, getGroupMraw, getGroupFront, getTemplate } from '@/api/zhihui/index.js';
import ZhihuiEditor from 'zhihui-editor-sdk';
import TypesNav from '@/components/TypesNav/index.vue';
import UploaderBtn from '@/components/UploaderBtn/index.vue';
import { getZHOption } from '@/utils/index';
import NewWaterFall from '@/components/NewWaterFall/index.vue';
import useUserStore from '@/store/modules/user';
import ClassNav from '@/components/ClassNav/index.vue';
import { ElLoading } from 'element-plus';

const { proxy } = getCurrentInstance();
const select_type = ref('template'); //选中类型
const original_list = ref([]); //原始数据
const font_list = ref([]);
const item_ids = ref([]);
const createDialog = ref(false);
const upLoadDialog = ref(false);
const pushDialog = ref(false);
const createform = ref({
  name: '',
});
const params = ref({
  filter: {}, //过滤条件
  page: 0,
  limit: 20,
  teamId: '',
  type: 'company',
});

const innerHeight = ref(0);
const isLast = ref(false);
const isLoading = ref(false);
innerHeight.value = window.innerHeight;
const data_list = ref([]);
const cla_id = ref('');
let loading = null;

const belong = ref(useUserStore().zhFirmId);
const userName = ref(useUserStore().name);
const waterFall = ref(null);
const cla_list = ref([]);
const uploader_type = ref('template'); //上传类型
const push_files = ref([]); //待推送文件
const total = ref(0);

function claSelect(cla) {
  cla_id.value = cla;
  resetFrom();
  getList();
}
function resetFrom() {
  let zhFirmId = useUserStore().zhFirmId;
  belong.value = zhFirmId;
  data_list.value = [];
  params.value = {
    filter: {}, //过滤条件
    page: 0,
    limit: 20,
    teamId: zhFirmId,
    type: 'company',
  };
  if (cla_id.value != '') {
    params.value.filter = { categoryIds: [cla_id.value] };
  }
  isLast.value = false;
  isLoading.value = false;
}
async function init() {
  resetFrom();
  getCla();
  getList(); //获取模板
}

function openDialog() {
  upLoadDialog.value = true;
}
//创建企业
async function createComment(isSubmit = false) {
  if (!isSubmit) return (createDialog.value = true);
  let option = {
    appid: import.meta.env.VITE_APP_ZHI_HUI_APPID,
    name: createform.value.name,
  };
  let data = await getZhiHuiSign(option);
  if (data.code == 200) {
    let sign = data.data;
    // let result = await createCompany({
    //   appid: import.meta.env.VITE_APP_ZHI_HUI_APPID,
    //   name: createform.value.name,
    //   sig: sign,
    // });
    let result = await createPersonCompany({
      name: createform.value.name,
    });
    // let result = {
    //   statusCode: 200,
    //   data: {
    //     _id: '658934914462c599098d602d',
    //     name: '测试',
    //     project: '627377d2be80280afe5e8d3f',
    //     teams: ['658934914462c599098d6031'],
    //     manages: [],
    //     createdAt: '2023-12-25T07:51:45.412Z',
    //     updatedAt: '2023-12-25T07:51:45.434Z',
    //     __v: 0,
    //   },
    // };
    if (result.statusCode == 200) {
      let update_result = await updateUserInfo({ userId: useUserStore().id, zhFirmId: result.data._id, zhGroupIds: result.data?.teams?.join(',') });
      if (update_result.code == 200) {
        proxy.$modal.msgSuccess('创建成功');
        useUserStore().updateZHInfo(result.data._id, result.data?.teams?.join(','));
        createDialog.value = false;
      }
    } else {
      proxy.$modal.msgError('创建失败-' + result.data.name + result.message);
    }
  }
  init();
}
function typesSelect(value) {
  select_type.value = value;
  init();
}
init();

async function getCla() {
  let zhFirmId = useUserStore().zhFirmId;
  let option = {
    teamId: zhFirmId,
    type: 'template',
  };
  let data = await listApolloByTeam(option);
  if (data.statusCode == 200) {
    cla_list.value = data.data;
  }
}

/**获取模板 */
async function getList(filterTermArr = '') {
  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 });
      }
    });
    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;
  }
}
/**编辑模板 */
function toEdit(item) {
  let option = getZHOption(item.id, useUserStore().id);
  let zhihuiEditor = new ZhihuiEditor(option);
  zhihuiEditor.openIframe();
}
</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;
  .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);
    }
  }
}
.mask {
  position: absolute;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.2);
  z-index: 2;
  border-radius: 20px;
  display: none;
  justify-content: center;
  align-items: center;
}
</style>
