<template>
  <div class="ele-body">
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="appId"
      :columns="columns"
      :datasource="datasource"
      :expanded-row-keys="expandedRowKeys"
      :expand-icon-column-index="1"
      tool-class="ele-toolbar-form"
      :scroll="{ x: 800 }"
      class="sys-org-table"
      @done="onDone"
      @expand="onExpand"
    >
      <template #toolbar>
        <search
          @search="reload"
          :selection="selection"
          @add="openEdit"
          @remove="removeBatch"
        />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'appName'">
          <component :is="record.appIcon" class="ant-menu-item-icon" />
          <a-tooltip title="插件详情">
            <span
              class="app-name cursor-pointer ele-text-primary"
              @click="openSetting(record)"
              >{{ record.appName }}</span
            >
          </a-tooltip>
        </template>
        <template v-if="column.key === 'appType'">
          <a-tag v-if="isExternalLink(record.path)" color="orange">
            外链
          </a-tag>
          <a-tag v-else-if="isExternalLink(record.component)" color="green">
            内链
          </a-tag>
          <a-tag v-else-if="record.menuType === 0" color="blue">菜单</a-tag>
          <a-tag v-else-if="record.menuType === 1">按钮</a-tag>
        </template>
        <template v-if="column.key === 'nickname'">
          <a-tooltip :title="`${record.nickname}`">
            <a-avatar :src="record.userAvatar" size="small" />
          </a-tooltip>
        </template>
        <template v-if="column.key === 'price'">
          <span class="ele-text-warning" v-if="record.price > 0"
            >￥{{ formatNumber(record.price) }}</span
          >
          <span class="ele-text-success" v-else>免费</span>
        </template>
        <template v-if="column.key === 'createTime'">
          <a-tooltip :title="`${toDateString(record.createTime)}`">
            {{ timeAgo(record.createTime) }}
          </a-tooltip>
        </template>
        <template v-if="column.key === 'edition'">
          <div v-if="record.edition == '正式版'" class="ele-text-success">
            正式版
          </div>
          <span v-if="record.edition == '开发版'" class="ele-text-info">
            开发版
            <a-tooltip
              :title="`${record.version}`"
              @click="openUrl('https://www.gxwebsoft.com')"
            >
              <question-circle-outlined style="margin-left: 16px" />
            </a-tooltip>
          </span>
        </template>
        <template v-if="column.key === 'status'">
          <a-tag v-if="record.status === 0" color="green">正常</a-tag>
          <a-tag v-if="record.status === 1" color="red">待审核</a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space v-role="'admin'">
            <!-- 已安装 -->
            <template v-if="appIds.indexOf(record.appId) > -1">
              <a @click="uninstallApp(record)">卸载</a>
            </template>
            <!-- 未安装 -->
            <template v-else>
              <template v-if="record.price > 0">
                <a class="ele-text-warning" @click="onBuy(record)">购买</a>
              </template>
              <template v-else>
                <a @click="install(record)">安装</a>
              </template>
            </template>
          </a-space>

          <!-- 开发者权限 -->
          <a-space v-permission="'sys:user:add'">
            <a @click="openSetting(record)">编辑</a>
            <a-divider type="vertical" />
            <!--            <a @click="openEdit(record)" class="ele-text-danger">编辑</a>-->
            <!--            <a-divider type="vertical" />-->
            <a-popconfirm
              title="确定要删除此记录吗？"
              @confirm="remove(record)"
            >
              <a class="ele-text-danger">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
    <!-- 编辑弹窗 -->
    <Edit v-model:visible="showEdit" :data="current" @done="reload" />
    <!-- 应用设置 -->
    <Setting v-model:visible="showSetting" :data="current" @done="reload" />
    <!-- 购买弹窗 -->
    <Buy v-model:visible="showBuy" :data="current" @done="reload" />
    <!-- 安装弹窗 -->
    <Step v-model:visible="showStep" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { computed, createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import {
    formatNumber,
    toDateString,
    isExternalLink,
    messageLoading
  } from 'ele-admin-pro';
  import Search from './components/search.vue';
  import Edit from './components/edit.vue';
  import Buy from './components/buy.vue';
  import Step from './components/step/index.vue';
  import Setting from './components/setting.vue';
  import type { EleProTable } from 'ele-admin-pro';
  import {
    listApp,
    pageApp,
    removeApp,
    removeBatchApp,
    saveMenu
  } from '@/api/dashboard/appstore';
  import { timeAgo } from 'ele-admin-pro';
  import type { App, AppParam } from '@/api/dashboard/appstore/model';
  import { useUserStore } from '@/store/modules/user';
  import { EleProTableDone } from 'ele-admin-pro/es/ele-pro-table/types';
  import { openUrl } from '@/utils/common';
  import type { Menu } from '@/api/system/menu/model';
  // import type { RoleMenu } from '@/api/system/menu/model/role-menu';

  const userStore = useUserStore();
  // 当前用户信息
  const loginUser = computed(() => userStore.info ?? {});
  // const appType = localStorage.getItem('AppType');
  const props = defineProps<{
    // 机构 id
    type?: any;
    // 当前选项卡
    activeKey?: any;
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格选中数据
  const selection = ref<App[]>([]);
  // 当前编辑数据
  const current = ref<App | null>(null); // 当前编辑数据
  // 菜单数据
  const menuData = ref<App[]>([]);
  const expandedRowKeys = ref();
  const appIds = ref<any>([]);
  // 上级菜单id
  const parentId = ref<number>();
  // 获取字典数据

  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示设置弹窗
  const showSetting = ref(false);
  // 是否显示购买弹窗
  const showBuy = ref(false);
  const showStep = ref(false);
  const authorityData = ref<Menu[]>([] || null);
  // const roleMenuData = ref<RoleMenu[]>([] || null);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    if (filters) {
      where.progress = filters.progress;
      where.appstoreSource = filters.appstoreSource;
      where.appType = filters.appType;
      where.status = filters.status;
      where.edition = filters.edition;
    }
    // 搜索条件
    if (props.activeKey > 0) {
      // 指定应用分类
      where.appType = props.type.value;
    } else {
      // 全部应用
      where.appType = undefined;
    }
    where.menuType = 0;
    where.parentId = 0;
    return pageApp({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '应用名称',
      dataIndex: 'appName',
      key: 'appName',
      ellipsis: true
    },
    {
      title: '应用标识',
      dataIndex: 'appCode'
    },
    {
      title: '备注',
      dataIndex: 'comments',
      ellipsis: true
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price'
    },
    {
      title: '开发商',
      dataIndex: 'developer',
      hideInTable: true
    },
    {
      title: '版本号',
      key: 'edition',
      filters: [
        {
          text: '正式版',
          value: '正式版'
        },
        {
          text: '开发版',
          value: '开发版'
        }
      ],
      filterMultiple: false
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      hideInTable: true,
      width: 90
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      ellipsis: true,
      hideInTable: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center',
      hideInSetting: true
    }
  ]);

  /* 表格渲染完成回调 */
  const onDone: EleProTableDone<App> = ({ data }) => {
    menuData.value = data;
  };

  /* 安装应用 */
  const install2 = (row?: App) => {
    current.value = row ?? null;
    showStep.value = true;
  };

  // 安装与卸载软件
  const install = (data) => {
    Modal.confirm({
      title: '提示',
      content: '确定要安装吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = messageLoading('模块安装中...', 0);
        saveMenu(data)
          .then((menuId) => {
            // 获取权限列表
            setTimeout(() => {
              listApp({ parentId: data.appId }).then((list) => {
                authorityData.value = list.map((d) => {
                  return {
                    title: d.appName,
                    menuType: d.menuType,
                    authority: d.authority,
                    parentId: menuId
                  };
                });
              });
            }, 1000);

            // 收集菜单ID
            setTimeout(() => {
              // saveAuthority(authorityData.value).then((response) => {
              //   roleMenuData.value = response?.data.map((d) => {
              //     return {
              //       menuId: d.menuId,
              //       roleId: 22
              //     };
              //   });
              // });
            }, 1000);

            // 添加应用权限
            setTimeout(() => {
              // saveRoleMenu(roleMenuData.value).then((result) => {
              //   hide();
              //   message.success('安装成功');
              // });
            }, 1000);
          })
          .catch(() => {
            hide();
            message.error('安装失败 请勿重复安装');
          });
      }
    });
  };
  const uninstallApp = (data) => {
    console.log(data);
    // removeMenu(data);
  };

  /* 点击展开图标时触发 */
  const onExpand = (expanded: boolean, record: App) => {
    if (expanded) {
      expandedRowKeys.value = [
        ...expandedRowKeys.value,
        record.appId as number
      ];
    } else {
      expandedRowKeys.value = expandedRowKeys.value.filter(
        (d) => d !== record.appId
      );
    }
  };

  /* 搜索 */
  const reload = (where?: AppParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: App) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 打开设置弹窗 */
  const openSetting = (row?: App) => {
    current.value = row ?? null;
    showSetting.value = true;
  };

  /* 进入应用 */
  const enterApp = (row?: App) => {
    openUrl(row?.component);
  };

  /* 购买应用 */
  const onBuy = (row?: App) => {
    current.value = row ?? null;
    showBuy.value = true;
  };

  /* 打开应用详情弹窗 */
  // const openDetail = (row?: App) => {
  //   current.value = row ?? null;
  //   showInfo.value = true;
  // };

  /* 删除单个 */
  const remove = (row: App) => {
    const hide = message.loading('请求中..', 0);
    removeApp(row.appId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchApp(
          selection.value.map((d) => {
            if (loginUser.value.userId === d.userId) {
              return d.appId;
            }
          })
        )
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  // 已安装的应用
  const getAppIds = () => {
    // listMenus({}).then((res) => {
    //   console.log(res, 'sdfsdfsdf>>>>');
    // });
    appIds.value =
      loginUser.value.authorities
        ?.filter((d) => !!d.appId && d.appId > 0)
        ?.map((d) => d.appId) ?? [];
  };

  getAppIds();
</script>

<script lang="ts">
  import * as MenuIcons from './menu-icons';
  export default {
    name: 'App',
    components: MenuIcons
  };
</script>

<style lang="less" scoped>
  .app-name {
    margin-left: 5px;
    margin-right: 5px;
  }
  .cursor-pointer {
    cursor: pointer;
  }
  .sys-org-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-org-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
</style>
