<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="bcPlanId"
          :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 === 'dayTime'">
              {{ toDateString(record.dayTime, 'YYYY-MM-dd') }}
              {{ getWeek(record.week) }}
            </template>
            <template v-if="column.key === 'nickname'">
              {{ record.nickname }}
            </template>
            <template v-if="column.key === 'createTime'">
              {{ record.createTime }}
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button @click="openEdit(record)">详情</a-button>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 编辑弹窗 -->
    <PlanEdit v-model:visible="showEdit" :data="current" @done="reload" />
    <!-- 订单详情 -->
    <order-info v-model:visible="showInfo" :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 { toDateString } from 'ele-admin-pro';
  import Search from './components/search.vue';
  import PlanEdit from './components/plan-edit.vue';
  import OrderInfo from './components/order-info.vue';
  import { getWeek } from '@/utils/common';
  import {
    pageBCPlan,
    removeBCPlan,
    removeBatchBCPlan
  } from '@/api/apps/bc/plan';
  import { BCPlan, BCPlanParam } from '@/api/apps/bc/plan/model';

  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,
    //   hideInTable: true,
    //   customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    // },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      fixed: 'left',
      hideInSetting: true
    },
    {
      title: '发布日期',
      dataIndex: 'dayTime',
      key: 'dayTime',
      align: 'center'
    },
    {
      title: '发布类型',
      dataIndex: 'period',
      key: 'period',
      align: 'center'
    },
    {
      title: '发布状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      customRender: ({ text }) => ['待发布', '已发布'][text]
    },
    {
      title: '发布人',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center'
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      sorter: true,
      customRender: ({ text }) => toDateString(text)
    }
  ]);

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

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    // 搜索条件
    if (filters.payMethod) {
      where.payMethod = filters.payMethod;
    }
    if (filters.deliveryType) {
      where.deliveryType = filters.deliveryType;
    }
    if (filters.payStatus) {
      where.payStatus = filters.payStatus;
    }
    if (filters.orderSource) {
      where.orderSource = filters.orderSource;
    }
    where.tenantId = localStorage.getItem('tenantId');
    where.payStatus = 20;
    return pageBCPlan({
      ...where,
      ...orders,
      page,
      limit
    });
  };

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

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

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

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

  /* 删除单个 */
  const remove = (row: BCPlan) => {
    const hide = message.loading('请求中..', 0);
    removeBCPlan(row.bcPlanId)
      .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);
        removeBatchBCPlan(selection.value.map((d) => d.bcPlanId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

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

  reload();
</script>

<script lang="ts">
  export default {
    name: 'BCPlanIndex'
  };
</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;
  }
</style>
