<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="appId"
          :columns="columns"
          :datasource="datasource"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search @search="reload" @add="openEdit" />
          </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="openEdit(record)">
                    {{ 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 === 'status'">
              <a-tag color="orange" v-if="record.status == 0">未缴费</a-tag>
              <a-tag color="green" v-if="record.status == 1">已缴费</a-tag>
            </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 === 'renewMoney'">
              <span @click="getLastMoney(record)"
                >￥{{ record.renewMoney }}</span
              >
            </template>
            <template v-if="column.key === 'images'">
              <div class="files">
                <a-upload
                  v-model:file-list="record.files"
                  disabled
                  class="upload-list-inline"
                />
              </div>
            </template>
            <template v-if="column.key === 'comments'">
              <div class="comments">{{ record.comments }}</div>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">管理</a>
                <template v-if="hasRole('superAdmin')">
                  <a-divider type="vertical" />
                  <a-popconfirm
                    title="确定要删除此记录吗？"
                    @confirm="removeRel(record)"
                  >
                    <a class="ele-text-info">删除</a>
                  </a-popconfirm>
                </template>
              </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 { ref } from 'vue';
  import type { EleProTable } from 'ele-admin-pro';
  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 { App, AppParam } from '@/api/oa/app/model';
  import { toDateString } from 'ele-admin-pro';
  import {
    pageAppRenew,
    removeAppRenew
  } from '@/api/oa/app/renew';
  import { hasRole } from '@/utils/permission';
  import { message } from 'ant-design-vue';
  import { AppRenew } from '@/api/oa/app/renew/model';
  import { pageApp, updateApp } from '@/api/oa/app';

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

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '所属企业',
      dataIndex: 'companyName',
      width: 280,
      key: 'companyName'
    },
    {
      title: '应用名称',
      dataIndex: 'appName',
      width: 300,
      key: 'appName'
    },
    {
      title: '到期时间',
      dataIndex: 'expirationTime',
      key: 'expirationTime',
      sorter: true
    },
    {
      title: '续费金额',
      dataIndex: 'renewMoney',
      key: 'renewMoney',
      sorter: true,
      customRender: ({ text }) => `￥${text}`
    },
    {
      title: '缴费状态',
      dataIndex: 'status',
      key: 'status',
      hideInTable: true,
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'appStatus',
      key: 'appStatus',
      width: 120
    },
    {
      title: '备注',
      dataIndex: 'comments',
      key: 'comments'
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      fixed: 'right',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<App[]>([]);
  // 当前编辑数据
  const current = ref<App | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 搜索条件
    where.sort = 'expirationTime';
    where.order = 'asc';
    where.appStatus = '已上架';
    where.showExpiration = true;
    return pageApp({
      ...where,
      ...orders,
      page,
      limit
    });
    // .then((res) => {
    //     res?.list.map((d) => {
    //       if (d.images) {
    //         d.files = JSON.parse(d.images);
    //       }
    //     });
    //     return res;
    //   })
  };

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

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

  const getLastMoney = (item: AppRenew) => {
    pageAppRenew({
      appId: item.appId,
      limit: 1
    }).then((res) => {
      if (res?.list.length == 1) {
        const item = res.list[0];
        console.log(item);
        updateApp({
          appId: item.appId,
          renewMoney: item.money,
          expirationTime: item.endTime + ' 23:59:59'
        });
        reload();
      }
    });
  };

  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 removeRel = (item: AppRenew) => {
    removeAppRenew(item.appRenewId).then(() => {
      message.success('删除成功');
      reload();
    });
  };

  /* 自定义行属性 */
  const customRow = (record: App) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };

  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;
    }
  }
</style>
