<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        tool-class="ele-toolbar-form"
        class="sys-org-table"
      >
        <template #toolbar>
          <search
            @search="reload"
            :selection="selection"
            @add="openEdit"
            @remove="removeBatch"
            @batchMove="openMove"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'image'">
            <a-image :src="record.image" :width="50" />
          </template>
          <template v-if="column.key === 'status'">
            <a-tag v-if="record.status === 0" color="green">显示</a-tag>
            <a-tag v-if="record.status === 1" color="red">隐藏</a-tag>
          </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>

    <!-- 编辑弹窗 -->
    <ClinicOrderEdit
      v-model:visible="showEdit"
      :data="current"
      @done="reload"
    />
  </a-page-header>
</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 { 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 { getPageTitle } from '@/utils/common';
  import ClinicOrderEdit from './components/clinicOrderEdit.vue';
  import {
    pageClinicOrder,
    removeClinicOrder,
    removeBatchClinicOrder
  } from '@/api/clinic/clinicOrder';
  import type {
    ClinicOrder,
    ClinicOrderParam
  } from '@/api/clinic/clinicOrder/model';

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

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

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

  // 完整的列配置（包含所有字段）
  const columns = ref<ColumnItem[]>([
    {
      title: '订单号',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 90
    },
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      ellipsis: true
    },
    {
      title: '订单类型，0商城订单 1预定订单/外卖 2会员卡',
      dataIndex: 'type',
      key: 'type',
      width: 120
    },
    {
      title: '订单标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true
    },
    {
      title: '快递/自提',
      dataIndex: 'deliveryType',
      key: 'deliveryType',
      width: 120
    },
    {
      title: '下单渠道，0小程序预定 1俱乐部训练场 3活动订场',
      dataIndex: 'channel',
      key: 'channel',
      width: 120
    },
    {
      title: '微信支付交易号号',
      dataIndex: 'transactionId',
      key: 'transactionId',
      ellipsis: true
    },
    {
      title: '微信退款订单号',
      dataIndex: 'refundOrder',
      key: 'refundOrder',
      ellipsis: true
    },
    {
      title: '商户ID',
      dataIndex: 'merchantId',
      key: 'merchantId',
      width: 120
    },
    {
      title: '商户名称',
      dataIndex: 'merchantName',
      key: 'merchantName',
      ellipsis: true
    },
    {
      title: '商户编号',
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      ellipsis: true
    },
    {
      title: '使用的优惠券id',
      dataIndex: 'couponId',
      key: 'couponId',
      width: 120
    },
    {
      title: '使用的会员卡id',
      dataIndex: 'cardId',
      key: 'cardId',
      ellipsis: true
    },
    {
      title: '关联管理员id',
      dataIndex: 'adminId',
      key: 'adminId',
      width: 120
    },
    {
      title: '核销管理员id',
      dataIndex: 'confirmId',
      key: 'confirmId',
      width: 120
    },
    {
      title: 'IC卡号',
      dataIndex: 'icCard',
      key: 'icCard',
      ellipsis: true
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      ellipsis: true
    },
    {
      title: '关联收货地址',
      dataIndex: 'addressId',
      key: 'addressId',
      width: 120
    },
    {
      title: '收货地址',
      dataIndex: 'address',
      key: 'address',
      ellipsis: true
    },
    {
      title: '',
      dataIndex: 'addressLat',
      key: 'addressLat',
      ellipsis: true
    },
    {
      title: '',
      dataIndex: 'addressLng',
      key: 'addressLng',
      ellipsis: true
    },
    {
      title: '买家留言',
      dataIndex: 'buyerRemarks',
      key: 'buyerRemarks',
      ellipsis: true
    },
    {
      title: '自提店铺id',
      dataIndex: 'selfTakeMerchantId',
      key: 'selfTakeMerchantId',
      width: 120
    },
    {
      title: '自提店铺',
      dataIndex: 'selfTakeMerchantName',
      key: 'selfTakeMerchantName',
      ellipsis: true
    },
    {
      title: '配送开始时间',
      dataIndex: 'sendStartTime',
      key: 'sendStartTime',
      ellipsis: true
    },
    {
      title: '配送结束时间',
      dataIndex: 'sendEndTime',
      key: 'sendEndTime',
      ellipsis: true
    },
    {
      title: '发货店铺id',
      dataIndex: 'expressMerchantId',
      key: 'expressMerchantId',
      width: 120
    },
    {
      title: '发货店铺',
      dataIndex: 'expressMerchantName',
      key: 'expressMerchantName',
      ellipsis: true
    },
    {
      title: '订单总额',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: 120
    },
    {
      title: '减少的金额，使用VIP会员折扣、优惠券抵扣、优惠券折扣后减去的价格',
      dataIndex: 'reducePrice',
      key: 'reducePrice',
      width: 120
    },
    {
      title: '实际付款',
      dataIndex: 'payPrice',
      key: 'payPrice',
      width: 120
    },
    {
      title: '用于统计',
      dataIndex: 'price',
      key: 'price',
      width: 120
    },
    {
      title: '价钱，用于积分赠送',
      dataIndex: 'money',
      key: 'money',
      width: 120
    },
    {
      title: '取消时间',
      dataIndex: 'cancelTime',
      key: 'cancelTime',
      width: 120
    },
    {
      title: '取消原因',
      dataIndex: 'cancelReason',
      key: 'cancelReason',
      ellipsis: true
    },
    {
      title: '退款金额',
      dataIndex: 'refundMoney',
      key: 'refundMoney',
      width: 120
    },
    {
      title: '教练价格',
      dataIndex: 'coachPrice',
      key: 'coachPrice',
      width: 120
    },
    {
      title: '购买数量',
      dataIndex: 'totalNum',
      key: 'totalNum',
      width: 120
    },
    {
      title: '教练id',
      dataIndex: 'coachId',
      key: 'coachId',
      width: 120
    },
    {
      title: '商品ID',
      dataIndex: 'formId',
      key: 'formId',
      width: 120
    },
    {
      title: '支付的用户id',
      dataIndex: 'payUserId',
      key: 'payUserId',
      width: 120
    },
    {
      title:
        '0余额支付，1微信支付，2支付宝支付，3银联支付，4现金支付，5POS机支付，6免费，7积分支付',
      dataIndex: 'payType',
      key: 'payType',
      width: 120
    },
    {
      title: '微信支付子类型：JSAPI小程序支付，NATIVE扫码支付',
      dataIndex: 'wechatPayType',
      key: 'wechatPayType',
      ellipsis: true
    },
    {
      title:
        '0余额支付，1微信支付，2支付宝支付，3银联支付，4现金支付，5POS机支付，6免费，7积分支付',
      dataIndex: 'friendPayType',
      key: 'friendPayType',
      width: 120
    },
    {
      title: '0未付款，1已付款',
      dataIndex: 'payStatus',
      key: 'payStatus',
      width: 120
    },
    {
      title:
        '0未使用，1已完成，2已取消，3取消中，4退款申请中，5退款被拒绝，6退款成功，7客户端申请退款',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      width: 120
    },
    {
      title: '发货状态(10未发货 20已发货 30部分发货)',
      dataIndex: 'deliveryStatus',
      key: 'deliveryStatus',
      width: 120
    },
    {
      title: '无需发货备注',
      dataIndex: 'deliveryNote',
      key: 'deliveryNote',
      ellipsis: true
    },
    {
      title: '发货时间',
      dataIndex: 'deliveryTime',
      key: 'deliveryTime',
      width: 120
    },
    {
      title: '评价状态(0未评价 1已评价)',
      dataIndex: 'evaluateStatus',
      key: 'evaluateStatus',
      width: 120
    },
    {
      title: '评价时间',
      dataIndex: 'evaluateTime',
      key: 'evaluateTime',
      width: 120
    },
    {
      title:
        '优惠类型：0无、1抵扣优惠券、2折扣优惠券、3、VIP月卡、4VIP年卡，5VIP次卡、6VIP会员卡、7IC月卡、8IC年卡、9IC次卡、10IC会员卡、11免费订单、12VIP充值卡、13IC充值卡、14VIP季卡、15IC季卡',
      dataIndex: 'couponType',
      key: 'couponType',
      width: 120
    },
    {
      title: '优惠说明',
      dataIndex: 'couponDesc',
      key: 'couponDesc',
      ellipsis: true
    },
    {
      title: '二维码地址，保存订单号，支付成功后才生成',
      dataIndex: 'qrcode',
      key: 'qrcode',
      ellipsis: true
    },
    {
      title: 'vip月卡年卡、ic月卡年卡回退次数',
      dataIndex: 'returnNum',
      key: 'returnNum',
      width: 120
    },
    {
      title: 'vip充值回退金额',
      dataIndex: 'returnMoney',
      key: 'returnMoney',
      width: 120
    },
    {
      title: '预约详情开始时间数组',
      dataIndex: 'startTime',
      key: 'startTime',
      ellipsis: true
    },
    {
      title: '是否已开具发票：0未开发票，1已开发票，2不能开具发票',
      dataIndex: 'isInvoice',
      key: 'isInvoice',
      width: 120
    },
    {
      title: '发票流水号',
      dataIndex: 'invoiceNo',
      key: 'invoiceNo',
      ellipsis: true
    },
    {
      title: '商家留言',
      dataIndex: 'merchantRemarks',
      key: 'merchantRemarks',
      ellipsis: true
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      key: 'payTime',
      width: 120
    },
    {
      title: '退款时间',
      dataIndex: 'refundTime',
      key: 'refundTime',
      width: 120
    },
    {
      title: '申请退款时间',
      dataIndex: 'refundApplyTime',
      key: 'refundApplyTime',
      width: 120
    },
    {
      title: '过期时间',
      dataIndex: 'expirationTime',
      key: 'expirationTime',
      width: 120
    },
    {
      title: '自提码',
      dataIndex: 'selfTakeCode',
      key: 'selfTakeCode',
      ellipsis: true
    },
    {
      title: '是否已收到赠品',
      dataIndex: 'hasTakeGift',
      key: 'hasTakeGift',
      width: 120
    },
    {
      title:
        '对账情况：0=未对账；1=已对账；3=已对账，金额对不上；4=未查询到该订单',
      dataIndex: 'checkBill',
      key: 'checkBill',
      width: 120
    },
    {
      title: '订单是否已结算(0未结算 1已结算)',
      dataIndex: 'isSettled',
      key: 'isSettled',
      width: 120
    },
    {
      title: '系统版本号 0当前版本 value=其他版本',
      dataIndex: 'version',
      key: 'version',
      width: 120
    },
    {
      title: '用户id',
      dataIndex: 'userId',
      key: 'userId',
      width: 120
    },
    {
      title: '备注',
      dataIndex: 'comments',
      key: 'comments',
      ellipsis: true
    },
    {
      title: '排序号',
      dataIndex: 'sortNumber',
      key: 'sortNumber',
      width: 120
    },
    {
      title: '是否删除, 0否, 1是',
      dataIndex: 'deleted',
      key: 'deleted',
      width: 120
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
      align: 'center',
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
      align: 'center',
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

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

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

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

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

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

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

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

<style lang="less" scoped></style>
