<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false" :body-style="{ padding: '16px' }">
        <search
          @search="reload"
          :selection="selection"
          @add="openEdit"
          @remove="removeBatch"
          @batchMove="openMove"
        />
      </a-card>
      <template v-for="(item, index) in periodList" :key="index">
        <div class="checkout-body">
          <view class="period-item">
            <view class="period ele-text-primary">{{ item.timePeriod }}</view>
            <view class="field-list">
              <template v-for="(field, index2) in item.fieldList" :key="index2">
                <view
                  class="field"
                  :class="isActive(field)"
                  style="cursor: pointer"
                  @click="openEdit(field)"
                >
                  <text class="field-name">{{ field.fieldName }}</text>
                  <text class="price">{{ item.price }}元</text>
                </view>
              </template>
            </view>
          </view>
        </div>
      </template>
      <!-- 编辑弹窗 -->
      <OrderInfo
        v-model:visible="showEdit"
        :data="current"
        :week="week"
        @done="reload"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import {
    ExclamationCircleOutlined,
    CheckOutlined,
    CloseOutlined,
    ClockCircleOutlined,
    IdcardOutlined,
    WechatOutlined,
    CoffeeOutlined,
    AlipayCircleOutlined
  } from '@ant-design/icons-vue';
  import { EleProTable, messageLoading, toDateString } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import OrderInfo from './components/orderInfo.vue';
  import {
    pageOrder,
    removeOrder,
    removeBatchOrder
  } from '@/api/booking/order';
  import type { Order } from '@/api/booking/order/model';
  import { formatNumber } from 'ele-admin-pro/es';
  import { Period, PeriodParam } from '@/api/booking/period/model';
  import { listPeriod } from '@/api/booking/period';
  import { Field } from '@/api/booking/field/model';
  import { getOrder } from '@/api/booking/order';
  import { reloadPageTab } from '@/utils/page-tab-util';
  import { getMerchantId } from '@/utils/common';

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

  // 表格选中数据
  const selection = ref<Order[]>([]);
  // 当前编辑数据
  const current = ref<Order | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示批量移动弹窗
  const showMove = ref(false);
  const week = ref<any>(0);
  // 加载状态
  const loading = ref(true);
  const periodList = ref<Period[]>([]);
  const merchantId = ref(0);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    if (filters) {
      where.status = filters.status;
    }
    where.type = 1;
    where.merchantId = getMerchantId();
    return pageOrder({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: '订单号',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 90
    },
    {
      title: '姓名',
      dataIndex: 'realName',
      key: 'realName',
      align: 'center'
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
      align: 'center'
    },
    {
      title: '总额',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      align: 'center',
      customRender: ({ text }) => `￥${formatNumber(text)}`
    },
    {
      title: '减少金额',
      dataIndex: 'reducePrice',
      key: 'reducePrice',
      align: 'center',
      customRender: ({ text }) => `￥${formatNumber(text)}`
    },
    {
      title: '实付金额',
      dataIndex: 'payPrice',
      key: 'payPrice',
      align: 'center',
      customRender: ({ text }) => `￥${formatNumber(text)}`
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      key: 'payType',
      align: 'center'
    },
    {
      title: '付款状态',
      dataIndex: 'payStatus',
      key: 'payStatus',
      align: 'center'
    },
    {
      title: '付款时间',
      dataIndex: 'payTime',
      key: 'payTime',
      align: 'center',
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      align: 'center'
    },
    {
      title: '优惠类型',
      dataIndex: 'couponType',
      key: 'couponType',
      align: 'center'
    },
    {
      title: '是否已开票',
      dataIndex: 'isInvoice',
      key: 'isInvoice',
      align: 'center'
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      customRender: ({ text }) =>
        ['商城订单', '客户预定', '俱乐部训练场', '活动订场'][text]
    },
    // {
    //   title: '申请退款时间',
    //   dataIndex: 'refundApplyTime',
    //   key: 'refundApplyTime',
    //   align: 'center',
    //   customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
    // },
    // {
    //   title: '备注',
    //   dataIndex: 'comments',
    //   key: 'comments',
    //   align: 'center'
    // },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

  /* 搜索 */
  const reload = (where?: PeriodParam) => {
    const hide = messageLoading('请求中..', 0);
    week.value = where?.week;
    listPeriod(where)
      .then((list) => {
        if (list) {
          hide();
          periodList.value = list;
        }
      })
      .catch((err) => {
        message.error('该场馆没有添加时间段，或预约时间已过');
        hide();
      });
    // selection.value = [];
    // tableRef?.value?.reload({ where: where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: Field) => {
    const orderId = Number(row?.orderId);
    if (periodList.value.length == 0) {
      console.log('sssssss');
      return message.error('该场馆没有添加时间段，或预约时间已过');
    }
    if (orderId > 0) {
      getOrder(orderId)
        .then((res) => {
          console.log(res);
          current.value = res ?? null;
          showEdit.value = true;
        })
        .catch((err) => {
          message.error(err.message);
        });
    }
  };

  /* 打开批量移动弹窗 */
  const openMove = () => {
    showMove.value = true;
  };

  const isActive = (item) => {
    if (item.sold) {
      if (item.isHalf == 1) {
        return 'web-bg-warning';
      }
      return 'web-bg-info';
    }
    // if (index) {
    //
    // }
  };
  const onField = (item) => {};

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

  /* 查询 */
  // const query = (where: PeriodParam) => {
  //   loading.value = true;
  // };

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

<script lang="ts">
  import * as MenuIcons from '@/layout/menu-icons';
  export default {
    name: 'Order',
    components: MenuIcons
  };
</script>
<style lang="less" scoped>
  .tag-icon {
    padding-right: 6px;
  }
  .checkout-body {
    padding: 10px 0;

    .period-item {
      margin: 16px 0;

      .period {
        line-height: 2em;
        padding-left: 6px;
        font-size: 16px;
      }

      .field-list {
        display: flex;
        flex-wrap: wrap;

        .web-bg-info {
          background-color: #909399 !important;
          color: #ffffff !important;
        }

        .web-bg-success {
          color: #2ba91c !important;
          border: 1px solid #2ba91c !important;
        }

        .web-bg-warning {
          // background-color: #c9e294 !important;
        }

        .active {
          &:before {
            border-radius: 0 0 6px 0;
            content: '';
            position: absolute;
            right: 0;
            bottom: 0;
            border: 12px solid #2ba91c;
            border-top-color: transparent;
            border-left-color: transparent;
          }

          &:after {
            content: '';
            width: 5px;
            height: 10px;
            position: absolute;
            right: 3px;
            bottom: 4px;
            border: 1px solid #fff;
            border-top-color: transparent;
            border-left-color: transparent;
            transform: rotate(45deg);
            border-radius: 2px;
          }
        }

        .field {
          width: 59px;
          height: 59px;
          margin: 5px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          border-radius: 8px;
          line-height: 1.3em;
          position: relative;
          color: #333333;
          background-color: #ffffff;
          border: 1px solid #808080;

          .field-name {
            font-size: 12px;
            text-align: center;
          }

          .price {
            font-size: 14px;
          }
        }
      }
    }
  }
</style>
