<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="shopDealerWithdrawId"
          :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 === 'applyStatus'">
              <a-tag v-if="record.applyStatus === 10" color="processing">待审核</a-tag>
              <a-tag v-if="record.applyStatus === 20" color="success">审核通过</a-tag>
              <a-tag v-if="record.applyStatus === 30" color="error">已驳回</a-tag>
              <a-tag v-if="record.applyStatus === 40" color="green">已打款</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="viewDetail(record)" class="ele-text-info">
                  <EyeOutlined /> 详情
                </a>
                <template v-if="record.applyStatus === 10">
                  <a-divider type="vertical" />
                  <a @click="approveWithdraw(record)" class="ele-text-success">
                    <CheckOutlined /> 通过
                  </a>
                  <a-divider type="vertical" />
                  <a @click="rejectWithdraw(record)" class="ele-text-warning">
                    <CloseOutlined /> 驳回
                  </a>
                </template>
                <template v-if="record.applyStatus === 20">
                  <a-divider type="vertical" />
                  <a @click="confirmPayment(record)" class="ele-text-success">
                    <DollarOutlined /> 确认打款
                  </a>
                </template>
                <a-divider type="vertical" />
                <a @click="openEdit(record)" class="ele-text-primary">
                  <EditOutlined /> 编辑
                </a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要删除此提现记录吗？"
                  @confirm="remove(record)"
                  placement="topRight"
                >
                  <a class="ele-text-danger">
                    <DeleteOutlined /> 删除
                  </a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>

      <!-- 编辑弹窗 -->
      <ShopDealerWithdrawEdit 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,
    EyeOutlined,
    CheckOutlined,
    CloseOutlined,
    DollarOutlined,
    EditOutlined,
    DeleteOutlined
  } 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 ShopDealerWithdrawEdit from './components/shopDealerWithdrawEdit.vue';
  import { pageShopDealerWithdraw, removeShopDealerWithdraw, removeBatchShopDealerWithdraw } from '@/api/shop/shopDealerWithdraw';
  import type { ShopDealerWithdraw, ShopDealerWithdrawParam } from '@/api/shop/shopDealerWithdraw/model';

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

  // 表格选中数据
  const selection = ref<ShopDealerWithdraw[]>([]);
  // 当前编辑数据
  const current = ref<ShopDealerWithdraw | 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 pageShopDealerWithdraw({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      align: 'center',
      width: 100,
      fixed: 'left'
    },
    {
      title: '提现金额',
      dataIndex: 'money',
      key: 'money',
      align: 'center',
      width: 120,
      customRender: ({ text }) => {
        const amount = parseFloat(text || '0').toFixed(2);
        return {
          type: 'span',
          props: {
            style: {
              color: '#ff4d4f',
              fontWeight: 'bold'
            }
          },
          children: `¥${amount}`
        };
      }
    },
    {
      title: '打款方式',
      dataIndex: 'payType',
      key: 'payType',
      align: 'center',
      width: 120,
      customRender: ({ text }) => {
        const typeMap = {
          10: { text: '微信', color: 'success' },
          20: { text: '支付宝', color: 'processing' },
          30: { text: '银行卡', color: 'warning' }
        };
        const type = typeMap[text] || { text: '未知', color: 'default' };
        return { type: 'tag', props: { color: type.color }, children: type.text };
      }
    },
    {
      title: '收款信息',
      key: 'paymentInfo',
      align: 'left',
      width: 200,
      customRender: ({ record }) => {
        if (record.payType === 20) {
          return `支付宝: ${record.alipayName || '-'} (${record.alipayAccount || '-'})`;
        } else if (record.payType === 30) {
          return `银行卡: ${record.bankAccount || '-'} (${record.bankName || '-'})`;
        } else if (record.payType === 10) {
          return '微信提现';
        }
        return '-';
      }
    },
    {
      title: '申请状态',
      dataIndex: 'applyStatus',
      key: 'applyStatus',
      align: 'center',
      width: 120,
      filters: [
        { text: '待审核', value: 10 },
        { text: '审核通过', value: 20 },
        { text: '已驳回', value: 30 },
        { text: '已打款', value: 40 }
      ]
    },
    // {
    //   title: '审核时间',
    //   dataIndex: 'auditTime',
    //   key: 'auditTime',
    //   align: 'center',
    //   width: 120,
    //   customRender: ({ text }) => text ? toDateString(new Date(text), 'yyyy-MM-dd HH:mm') : '-'
    // },
    // {
    //   title: '驳回原因',
    //   dataIndex: 'rejectReason',
    //   key: 'rejectReason',
    //   align: 'left',
    //   ellipsis: true,
    //   customRender: ({ text }) => text || '-'
    // },
    // {
    //   title: '来源平台',
    //   dataIndex: 'platform',
    //   key: 'platform',
    //   align: 'center',
    //   width: 100,
    //   customRender: ({ text }) => text || '-'
    // },
    {
      title: '驳回原因',
      dataIndex: 'rejectReason',
      key: 'rejectReason',
      align: 'center',
    },
    {
      title: '来源客户端',
      dataIndex: 'platform',
      key: 'platform',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 180,
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
    },
    {
      title: '操作',
      key: 'action',
      width: 420,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

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

  /* 查看详情 */
  const viewDetail = (row: ShopDealerWithdraw) => {
    Modal.info({
      title: '提现申请详情',
      width: 600,
      content: createVNode('div', { style: 'max-height: 400px; overflow-y: auto;' }, [
        createVNode('div', { class: 'detail-item' }, [
          createVNode('strong', null, '申请信息'),
          createVNode('p', null, `申请ID: ${row.id || '-'}`),
          createVNode('p', null, `用户ID: ${row.userId || '-'}`),
          createVNode('p', null, `提现金额: ¥${parseFloat(row.money || '0').toFixed(2)}`),
          createVNode('p', null, `来源平台: ${row.platform || '-'}`),
        ]),
        createVNode('div', { class: 'detail-item', style: 'margin-top: 16px;' }, [
          createVNode('strong', null, '收款信息'),
          createVNode('p', null, `打款方式: ${row.payType === 10 ? '微信' : row.payType === 20 ? '支付宝' : row.payType === 30 ? '银行卡' : '未知'}`),
          ...(row.payType === 20 ? [
            createVNode('p', null, `支付宝姓名: ${row.alipayName || '-'}`),
            createVNode('p', null, `支付宝账号: ${row.alipayAccount || '-'}`)
          ] : []),
          ...(row.payType === 30 ? [
            createVNode('p', null, `开户行: ${row.bankName || '-'}`),
            createVNode('p', null, `开户名: ${row.bankAccount || '-'}`),
            createVNode('p', null, `银行卡号: ${row.bankCard || '-'}`)
          ] : [])
        ]),
        createVNode('div', { class: 'detail-item', style: 'margin-top: 16px;' }, [
          createVNode('strong', null, '审核信息'),
          createVNode('p', null, `申请状态: ${row.applyStatus === 10 ? '待审核' : row.applyStatus === 20 ? '审核通过' : row.applyStatus === 30 ? '已驳回' : row.applyStatus === 40 ? '已打款' : '未知'}`),
          createVNode('p', null, `审核时间: ${row.auditTime ? toDateString(new Date(row.auditTime), 'yyyy-MM-dd HH:mm:ss') : '-'}`),
          createVNode('p', null, `驳回原因: ${row.rejectReason || '-'}`),
        ]),
        createVNode('div', { class: 'detail-item', style: 'margin-top: 16px;' }, [
          createVNode('strong', null, '其他信息'),
          createVNode('p', null, `创建时间: ${row.createTime ? toDateString(row.createTime, 'yyyy-MM-dd HH:mm:ss') : '-'}`),
          createVNode('p', null, `更新时间: ${row.updateTime ? toDateString(row.updateTime, 'yyyy-MM-dd HH:mm:ss') : '-'}`),
        ])
      ]),
      okText: '关闭'
    });
  };

  /* 审核通过 */
  const approveWithdraw = (row: ShopDealerWithdraw) => {
    Modal.confirm({
      title: '审核通过确认',
      content: `确定要通过用户 ${row.userId} 的提现申请吗？提现金额：¥${parseFloat(row.money || '0').toFixed(2)}`,
      icon: createVNode(CheckOutlined),
      okText: '确认通过',
      okType: 'primary',
      cancelText: '取消',
      onOk: () => {
        const hide = message.loading('正在处理审核...', 0);
        // 这里需要调用审核通过的API
        setTimeout(() => {
          hide();
          message.success('审核通过成功');
          reload();
        }, 1000);
      }
    });
  };

  /* 审核驳回 */
  const rejectWithdraw = (row: ShopDealerWithdraw) => {
    let rejectReason = '';
    Modal.confirm({
      title: '审核驳回',
      content: createVNode('div', null, [
        createVNode('p', null, `用户ID: ${row.userId}`),
        createVNode('p', null, `提现金额: ¥${parseFloat(row.money || '0').toFixed(2)}`),
        createVNode('p', { style: 'margin-top: 12px;' }, '请输入驳回原因:'),
        createVNode('textarea', {
          placeholder: '请输入驳回原因...',
          style: 'width: 100%; height: 80px; margin-top: 8px; padding: 8px; border: 1px solid #d9d9d9; border-radius: 4px;',
          onInput: (e: any) => {
            rejectReason = e.target.value;
          }
        })
      ]),
      icon: createVNode(CloseOutlined),
      okText: '确认驳回',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        if (!rejectReason.trim()) {
          message.error('请输入驳回原因');
          return Promise.reject();
        }
        const hide = message.loading('正在处理审核...', 0);
        setTimeout(() => {
          hide();
          message.success('审核驳回成功');
          reload();
        }, 1000);
      }
    });
  };

  /* 确认打款 */
  const confirmPayment = (row: ShopDealerWithdraw) => {
    Modal.confirm({
      title: '确认打款',
      content: `确定已向用户 ${row.userId} 打款 ¥${parseFloat(row.money || '0').toFixed(2)} 吗？此操作不可撤销。`,
      icon: createVNode(DollarOutlined),
      okText: '确认打款',
      okType: 'primary',
      cancelText: '取消',
      onOk: () => {
        const hide = message.loading('正在确认打款...', 0);
        setTimeout(() => {
          hide();
          message.success('打款确认成功');
          reload();
        }, 1000);
      }
    });
  };

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

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

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

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

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

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

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