<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="productId"
          :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"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
              @advanced="openAdvanced"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
              <div class="product-box">
                <a-image
                  :height="45"
                  :width="45"
                  :preview="false"
                  :src="record.logo"
                  fallback="https://file.wsdns.cn/20230218/550e610d43334dd2a7f66d5b20bd58eb.svg"
                />
                <div class="product-info">
                  <a
                    class="ele-text-heading"
                    @click="openUrl('/product/detail/' + record.productId)"
                  >
                    {{ record.name }}
                  </a>
                  <span class="ele-text-placeholder">
                    {{ record.code }}
                  </span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'productCode'">
              <span>{{ record.productCode }}</span>
            </template>
            <template v-if="column.key === 'status'">
              <a-tag v-if="record.status === 0" color="success">已上架</a-tag>
              <a-tag 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 === 'productQrcode'">
              <a-image
                v-if="record.productQrcode"
                :height="45"
                :width="45"
                :src="record.productQrcode"
              />
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">管理</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>
    <!-- 编辑弹窗 -->
    <ProductEdit 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 { ExclamationCircleOutlined } from '@ant-design/icons-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 ProductEdit from './components/product-edit.vue';
  import {
    pageProduct,
    removeBatchProduct,
    removeProduct
  } from '@/api/oa/product';
  import { Product, ProductParam } from '@/api/oa/product/model';
  import { toDateString } from 'ele-admin-pro';
  import { openUrl } from '@/utils/common';

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

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      dataIndex: 'productId',
      width: 80
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '产品类型',
      dataIndex: 'type',
      align: 'center',
      width: 180,
      key: 'type'
    },
    {
      title: '产品状态',
      dataIndex: 'status',
      align: 'center',
      width: 180,
      key: 'status'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 180,
      sorter: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:ss')
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      fixed: 'right',
      hideInSetting: true
    }
  ]);

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

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    // 默认类型
    if (where.keywords == undefined) {
      where.productStatus = '开发中';
      where.showExpiration = undefined;
    }
    return pageProduct({
      ...where,
      ...orders,
      page,
      limit
    });
  };

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

  /* 打开编辑弹窗 */
  const openEdit = (row?: Product) => {
    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: Product) => {
    const hide = message.loading('请求中..', 0);
    removeProduct(row.productId)
      .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);
        removeBatchProduct(selection.value.map((d) => d.productId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

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

  reload();
</script>

<script lang="ts">
  export default {
    name: 'ProductIndex'
  };
</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;
  }
  .product-box {
    display: flex;
    .product-info {
      display: flex;
      margin-left: 5px;
      flex-direction: column;
    }
  }
</style>
