<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="appId"
          :columns="columns"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
              @advanced="openAdvanced"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'companyName'">
              <div class="app-box">
                <a-image
                  :height="45"
                  :width="45"
                  :preview="false"
                  :src="record.companyLogo"
                  fallback="https://file.wsdns.cn/20230218/550e610d43334dd2a7f66d5b20bd58eb.svg"
                />
                <div class="app-info">
                  <span class="ele-text-heading">
                    {{ record.shortName }}
                  </span>
                  <span class="ele-text-placeholder">
                    {{ record.companyName }}
                  </span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'appName'">
              <div class="app-box">
                <a-image
                  :height="45"
                  :width="45"
                  :preview="false"
                  :src="record.appIcon"
                  fallback="https://file.wsdns.cn/20230218/550e610d43334dd2a7f66d5b20bd58eb.svg"
                />
                <div class="app-info">
                  <a
                    class="ele-text-heading"
                    @click="openUrl('/oa/app/detail/' + record.appId)"
                  >
                    {{ record.appName }}
                  </a>
                  <span class="ele-text-placeholder">
                    {{ record.appCode }}
                  </span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'appCode'">
              <span>{{ record.appCode }}</span>
            </template>
            <template v-if="column.key === 'appStatus'">
              <a-tag v-if="record.appStatus === '开发中'" color="red">{{
                record.appStatus
              }}</a-tag>
              <a-tag v-if="record.appStatus === '已上架'" color="success">{{
                record.appStatus
              }}</a-tag>
              <a-tag v-if="record.appStatus === '维护中'" color="orange">{{
                record.appStatus
              }}</a-tag>
              <a-tag v-if="record.appStatus === '已下架'">{{
                record.appStatus
              }}</a-tag>
            </template>
            <template v-if="column.key === 'appUrl'">
              <a-tooltip v-if="record.appUrl" :title="record.appUrl">
                <a class="ele-text-heading" @click="openUrl(record.appUrl)"
                  >前往</a
                >
              </a-tooltip>
            </template>
            <template v-if="column.key === 'appTypeMultiple'">
              <a-space
                :size="2"
                direction="vertical"
                v-if="record.appTypeMultiple"
              >
                <template
                  v-for="(item, index) in JSON.parse(record.appTypeMultiple)"
                  :key="index"
                >
                  <span v-if="index == 0">{{ item }}</span>
                </template>
              </a-space>
            </template>
            <template v-if="column.key === 'expirationTime'">
              <template v-if="expirationTime(record.expirationTime) < 30">
                <a-space>
                  <span class="ele-text-danger">{{
                    toDateString(record.expirationTime, 'yyyy-MM-dd')
                  }}</span>
                  <span class="ele-text-placeholder"
                    >(剩余{{ expirationTime(record.expirationTime) }}天)</span
                  >
                </a-space>
              </template>
              <template v-else>
                {{ toDateString(record.expirationTime, 'yyyy-MM-dd') }}
              </template>
            </template>
            <!--            <template v-if="column.key === 'appQrcode'">-->
            <!--              <a-image-->
            <!--                v-if="record.appQrcode"-->
            <!--                :height="50"-->
            <!--                :width="50"-->
            <!--                :src="record.appQrcode"-->
            <!--              />-->
            <!--            </template>-->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="moveUp(record)">上移<ArrowUpOutlined /></a>
                <a-divider type="vertical" />
                <a @click="openUrl('/oa/app/detail/' + record.appId)">管理</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>
      </a-card>
    </div>
    <!-- 编辑弹窗 -->
    <AppEdit v-model:visible="showEdit" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import {
    ArrowUpOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import { openUrl } from '@/utils/common';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import AppEdit from './components/app-edit.vue';
  import {
    pageApp,
    removeBatchApp,
    removeApp,
    getCount,
    updateApp
  } from '@/api/oa/app';
  import { App, AppParam } from '@/api/oa/app/model';
  import { toDateString } from 'ele-admin-pro';

  defineProps<{
    activeKey?: boolean;
    data?: any;
  }>();

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'appId',
      width: 80,
      hideInTable: true
    },
    {
      title: '租户ID',
      dataIndex: 'tenantCode',
      width: 80
    },
    {
      title: '项目名称',
      dataIndex: 'appName',
      key: 'appName'
    },
    {
      title: '项目类型',
      dataIndex: 'appTypeMultiple',
      width: 120,
      align: 'center',
      key: 'appTypeMultiple'
    },
    // {
    //   title: '二维码',
    //   dataIndex: 'appQrcode',
    //   width: 120,
    //   align: 'center',
    //   key: 'appQrcode'
    // customRender: ({ text }) => {
    //   if (text) {
    //     const split = text.split('|||');
    //     console.log(split[0]);
    //     return split[0];
    //   }
    // }
    // },
    // {
    //   title: '到期时间',
    //   dataIndex: 'expirationTime',
    //   key: 'expirationTime',
    //   sorter: true
    // },
    {
      title: '状态',
      dataIndex: 'appStatus',
      align: 'center',
      width: 120,
      key: 'appStatus'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 120,
      sorter: true,
      customRender: ({ text }) => toDateString(text, 'MM-dd')
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      width: 120,
      align: 'center',
      sorter: true
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center',
      fixed: 'right',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<App[]>([]);
  // 当前编辑数据
  const current = ref<App | null>(null);
  // 是否显示资产详情
  // const showInfo = ref(false);
  const active = ref<any>('开发中');
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示高级搜索
  const showAdvancedSearch = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 默认类型
    if (where.keywords == undefined) {
      where.appStatus = '开发中';
      where.showExpiration = undefined;
    }
    if (where.appStatus == '未签续费') {
      where.appStatus = '已上架';
      where.showExpiration = false;
      where.sort = 'expirationTime';
      where.order = 'asc';
    }
    return pageApp({
      ...where,
      ...orders,
      page,
      limit
    });
  };

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

  // const onTab = (type: any) => {
  //   active.value = type;
  //   reload({ keywords: '', appStatus: active.value });
  // };

  /* 打开编辑弹窗 */
  const openEdit = (row?: App) => {
    // openUrl('/oa/app/detail/' + row?.appId);
    current.value = row ?? null;
    showEdit.value = true;
  };

  const expirationTime = (dateTime) => {
    const now = new Date().getTime();
    const expiration = new Date(dateTime).getTime();
    const mss = expiration - now;
    let days = Math.floor(mss / (1000 * 60 * 60 * 24));
    let hours = Math.floor((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((mss % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.round((mss % (1000 * 60)) / 1000);
    return days;
  };

  /* 打开高级搜索 */
  const openAdvanced = () => {
    showAdvancedSearch.value = !showAdvancedSearch.value;
  };

  /* 删除单个 */
  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 = () => {
    console.log(selection.value);
    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) => d.appId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  const moveUp = (row?: App) => {
    updateApp({
      appId: row?.appId,
      sortNumber: Number(row?.sortNumber) - 1
    }).then((msg) => {
      message.success(msg);
      reload();
    });
  };

  /* 自定义行属性 */
  const customRow = (record: App) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openUrl('/oa/app/detail/' + record.appId);
        // window.open('/oa/app/detail/' + record.appId);
      }
    };
  };

  // 统计数据
  const conut = ref({
    totalNum: 0,
    totalNum2: 0,
    totalNum3: 0,
    totalNum4: 0,
    totalNum5: 0
  });
  getCount().then((data: any) => {
    conut.value = data;
  });

  reload();
</script>

<script lang="ts">
  export default {
    name: 'AppIndex'
  };
</script>

<style lang="less" scoped>
  p {
    line-height: 0.8;
  }
  .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;
  }
  .price-edit {
    padding-right: 5px;
  }
  .comments {
    max-width: 200px;
  }
  .app-box {
    display: flex;
    .app-info {
      display: flex;
      margin-left: 5px;
      flex-direction: column;
    }
  }
  .count {
    display: flex;
    .btn {
      margin: 0 12px;
      padding: 5px 16px;
      background-color: #f3f3f3;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      align-items: center;
      font-size: 15px;
      .divider {
        width: 4px;
        height: 14px;
        border-radius: 8px;
        margin-right: 8px;
        background-color: #c9c9c9;
      }
      .divider-active {
        width: 4px;
        height: 14px;
        border-radius: 8px;
        margin-right: 8px;
        background-color: #16a90b;
      }
      .active {
        color: #16a90b;
      }
    }
  }
</style>
