<template>
  <PageWrapper dense fixed-height contentFullHeight>
    <PageLayout
      :title="t('桌面设计')"
      :searchConfig="searchConfig"
      @search="search"
      @scroll-height="scrollHeight"
      @refresh="getList"
    >
      <template #search> </template>
      <template #operation>
        <div class="button-box">
          <a-button @click.stop="handleAdd" type="primary" v-auth="'desktop:add'">{{
            t('新增')
          }}</a-button>
        </div>
      </template>
      <template #right>
        <div v-if="data.dataSource.length > 0" class="deskconbox">
          <div class="list-box" :style="{ overflowY: 'auto' }" :key="data.renderKey">
            <div class="item" v-for="(item, index) in data.dataSource" :key="index">
              <div class="image"
                ><a-image
                  width="100%"
                  height="100%"
                  :src="item.backgroundUrl"
                  :preview="false"
                  fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2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oFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
              /></div>
              <div class="edit" @click.stop="handleEdit(item.id)">{{ t('设计') }}</div>
              <div class="mark"> </div>
              <div class="main">
                <span class="name">{{ item.name }}</span>
                <div class="flex">
                  <div class="menu-list">
                    <a-tooltip placement="bottom" @click="handleFirst(item.id)">
                      <template #title>
                        <span>{{ t(item.isFirst === 1 ? '默认首页' : '设为默认首页') }}</span>
                      </template>
                      <Icon
                        icon="jam:home-f"
                        :color="item.isFirst === 1 ? primaryColor : '#C3C8CF'"
                        class="menu-item"
                      />
                    </a-tooltip>
                    <a-popconfirm :title="t('确定删除吗?')" @confirm="handleDelete(item.id)">
                      <a-tooltip placement="bottom">
                        <template #title>
                          <span>{{ t('删除') }}</span>
                        </template>
                        <Icon icon="ant-design:delete-filled" color="#C3C8CF" class="menu-item" />
                      </a-tooltip>
                    </a-popconfirm>

                    <a-tooltip placement="bottom" @click="handlePreview(item.id)">
                      <template #title>
                        <span>{{ t('查看') }}</span>
                      </template>
                      <Icon icon="ant-design:eye-filled" color="#C3C8CF" class="menu-item" />
                    </a-tooltip>
                    <a-tooltip placement="bottom" @click="copy(item.id)">
                      <template #title>
                        <span>{{ t('复制') }}</span>
                      </template>
                      <Icon icon="ant-design:copy-filled" color="#C3C8CF" class="menu-item" />
                    </a-tooltip>
                    <a-tooltip placement="bottom" @click="handleDownByData(item)">
                      <template #title>
                        <span>{{ t('导出') }}</span>
                      </template>
                      <Icon icon="ic:round-cloud-download" color="#C3C8CF" class="menu-item" />
                    </a-tooltip>
                    <a-tooltip placement="bottom" @click="showHistory(item.id)">
                      <template #title>
                        <span>{{ t('历史') }}</span>
                      </template>
                      <Icon icon="mingcute:time-fill" color="#C3C8CF" class="menu-item" />
                    </a-tooltip>
                  </div>
                  <a-switch
                    v-model:checked="item.enabledMark"
                    :checkedValue="1"
                    :unCheckedValue="0"
                    :disabled="item.isFirst === 1"
                    size="small"
                    @change="changeEnabledMark(item)"
                  />
                </div>
              </div>
            </div>
          </div>

          <a-pagination
            v-model:current="data.pagination.current"
            v-model:pageSize="data.pagination.pageSize"
            :total="data.pagination.total"
            show-less-items
            @change="getList"
            :show-total="(total) => t(`共 ${total} 条数据`)"
            show-size-changer
            show-quick-jumper
            :page-size-options="['10', '20', '50', '80', '100']"
          />
        </div>
        <div v-else>
          <EmptyBox />
        </div>
        <DesktopDesign
          v-if="data.desktopDesignVisible"
          :editId="data.editId"
          @close="handleClose"
        />
        <DesktopPreview
          v-if="data.previewVisible"
          ref="previewRef"
          :list="data.list"
          @close="data.previewVisible = false"
        />
        <a-drawer
          size="large"
          v-model:visible="data.historyVisible"
          :title="t('历史记录')"
          placement="right"
        >
          <DesktopHistory v-if="data.historyVisible" :id="data.historyId" />
        </a-drawer>
      </template>
    </PageLayout>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, defineAsyncComponent } from 'vue';
  import { Icon } from '/@/components/Icon/index';
  import DesktopHistory from './components/DesktopHistory.vue';
  import { DesktopPageModel } from '/@/api/desktop/model';
  import { PageLayout, EmptyBox } from '/@/components/ModalPanel';
  import userTableScrollHeight from '/@/hooks/setting/userTableScrollHeight';
  import { LoadingBox } from '/@/components/ModalPanel';
  import { notification } from 'ant-design-vue';
  import {
    copyDesktop,
    deleteDesktop,
    exportDesktop,
    getDesktopInfo,
    getPageList,
    setFirstHome,
    setEnabled,
  } from '/@/api/desktop';
  import { DesktopInfoItem } from '/@/model/desktop/designer';
  import DesktopPreview from './components/DesktopPreview.vue';
  import { downloadByData } from '/@/utils/file/download';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { PageWrapper } from '/@/components/Page';
  import { primaryColor } from '../../../../build/config/themeConfig';

  const { t } = useI18n();
  const DesktopDesign = defineAsyncComponent({
    loader: () => import('./components/DesktopDesign.vue'),
    loadingComponent: LoadingBox,
  });
  const searchConfig = [
    {
      field: 'keyword',
      label: '',
      type: 'input',
    },
  ];
  const { scrollHeight } = userTableScrollHeight();
  let data: {
    dataSource: Array<DesktopPageModel>;
    renderKey: number;
    keyword: string;
    pagination: {
      current: number;
      total: number;
      pageSize: number;
    };
    desktopDesignVisible: boolean;
    editId: string;
    list: Array<DesktopInfoItem>;
    previewVisible: boolean;
    historyVisible: boolean;
    historyId: string;
  } = reactive({
    dataSource: [],
    renderKey: 0,
    pagination: { current: 1, total: 0, pageSize: 20 },
    keyword: '',
    desktopDesignVisible: false,
    editId: '',
    list: [],
    previewVisible: false,
    historyVisible: false,
    historyId: '',
  });
  onMounted(() => {
    data.dataSource = [];
    getList();
  });
  async function getList() {
    let params = {
      limit: data.pagination.current,
      size: data.pagination.pageSize,
      keyword: data.keyword,
    };
    let res = await getPageList(params);
    data.dataSource = res.list;
    data.pagination.total = res.total;
    data.renderKey++;
  }
  function search(params?: any) {
    data.keyword = params.keyword;
    data.pagination.current = 1;
    data.dataSource = [];
    getList();
  }
  function handleAdd() {
    data.desktopDesignVisible = true;
  }
  async function handlePreview(id: string) {
    let { jsonContent } = await getDesktopInfo(id);
    data.list = JSON.parse(jsonContent);
    data.previewVisible = true;
  }
  function handleEdit(id: string) {
    data.editId = id;
    data.desktopDesignVisible = true;
  }
  async function handleDelete(id: string) {
    try {
      let res = await deleteDesktop(id);
      if (res) {
        notification.open({
          type: 'success',
          message: t('删除'),
          description: t('成功'),
        });
        getList();
      }
    } catch (error) {}
  }
  function handleClose() {
    data.editId = '';
    data.list = [];
    data.desktopDesignVisible = false;
    getList();
  }
  async function copy(id: string) {
    try {
      let res = await copyDesktop(id);
      if (res) {
        notification.open({
          type: 'success',
          message: t('复制'),
          description: t('成功'),
        });
        getList();
      }
    } catch (error) {}
  }
  async function handleDownByData(item: DesktopPageModel) {
    try {
      let res: any = await exportDesktop(item.id);
      downloadByData(res, item.name + '.json');
    } catch (error) {}
  }
  function showHistory(id: string) {
    data.historyId = id;
    data.historyVisible = true;
  }

  async function changeEnabledMark(info) {
    const params = {
      id: info.id,
      enabledMark: info.enabledMark,
    };
    try {
      const res = await setEnabled(params);
      if (res) {
        notification.open({
          type: 'success',
          message: `${info.enabledMark ? t('启用') : t('禁用')}${t('成功')}`,
          description: t('成功'),
        });
        getList();
      } else {
        notification.open({
          type: 'error',
          message: `${info.enabledMark ? t('启用') : t('禁用')}${t('失败')}`,
          description: t('失败'),
        });
        info.enabledMark = info.enabledMark ? 0 : 1;
      }
    } catch (error) {}
  }
  async function handleFirst(id) {
    let res = await setFirstHome(id);
    if (res) {
      notification.open({
        type: 'success',
        message: t('设为默认首页'),
        description: t('成功'),
      });
      getList();
      const permissionStore = usePermissionStore();
      await permissionStore.changePermissionCode();
    } else {
      notification.open({
        type: 'error',
        message: t('设为默认首页'),
        description: t('失败'),
      });
    }
  }
</script>
<style lang="less" scoped>
  .deskconbox {
    height: calc(100% - 62px);
    background: #fff;
    border-radius: 16px;
    margin-top: 10px;
    padding: 16px 0 0;
  }

  .list-box {
    display: flex;
    flex-wrap: wrap;
    align-content: baseline;
    padding: 0 16px;
    height: calc(100% - 52px);
    border-bottom: 1px solid rgb(238 238 238 / 93%);

    .item {
      position: relative;
      width: calc((100% - 60px) / 4);
      overflow: hidden;
      margin: 0 20px 20px 0;

      &:nth-child(4n) {
        margin-right: 0;
      }
    }

    .image {
      width: 100%;
      height: 224px;
      border-radius: 16px;
    }

    .mark {
      display: none;
    }

    .edit {
      position: absolute;
      inset: 0;
      height: 35px;
      line-height: 35px;
      padding: 0 30px;
      text-align: center;
      font-size: 14px;
      background-color: @primary-color;
      color: #fff;
      border: none;
      transition: 0.3s ease;
      cursor: pointer;
      opacity: 0;
      z-index: 1;
      margin: 95px auto 0;
      width: 100px;
      border-radius: 8px;
    }

    .item:hover {
      .mark {
        display: block;
        position: absolute;
        inset: 0;
        background: rgb(0 0 0 / 50%);
        border-radius: 16px;
        height: 224px;
      }

      .edit {
        opacity: 1;
      }
    }

    .main {
      height: 50px;
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      border-bottom: 1px solid #eee;
      color: #333;
      font-size: 14px;
      padding-bottom: 10px;

      .name {
        margin-left: 10px;
        font-weight: bold;
      }

      .menu-list {
        margin-right: 10px;
        border-left: 1px solid #eee;
        border-right: 1px solid #eee;
        padding: 0 12px 0 0;
        height: 16px;
        line-height: 16px;

        .menu-item {
          margin-left: 12px;
          cursor: pointer;
        }
      }
    }
  }

  .ant-pagination {
    padding: 10px 6px 10px 0;
    background: #fff;
    border-radius: 0 0 16px 16px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.ant-image) {
    img {
      border-radius: 16px;
    }
  }
</style>
