<template>
  <div class="page">
    <a-page-header :ghost="false" title="资金提现">
      <a-row type="flex">
        <a-statistic
          title="可提现金额"
          prefix="￥"
          :precision="2"
          :value="money"
        />
        <a-statistic
          title="待提现"
          prefix="￥"
          :precision="2"
          :value="freezeMoney"
          :style="{
            margin: '0 80px'
          }"
        />
        <a-statistic
          title="累计已提现"
          prefix="￥"
          :precision="2"
          :value="totalMoney"
        />
      </a-row>
      <!--      <template #extra>-->
      <!--        <a-button key="1" type="primary" danger>申请提现</a-button>-->
      <!--      </template>-->
    </a-page-header>
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="id"
          :columns="columns"
          :height="tableHeight"
          :datasource="datasource"
          v-model:selection="selection"
          :scroll="{ x: 800 }"
        >
          <template #toolbar>
            <search
              :selection="selection"
              @search="reload"
              @add="openEdit"
              @remove="removeBatch"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'image'">
              <a-image :src="record.image" :width="80" />
            </template>
            <template v-if="column.key === 'money'">
              ￥{{ formatNumber(record.money, 2) }}
            </template>
            <template v-if="column.key === 'bankName'">
              <p>{{ record.bankName }}</p>
              <p>{{ record.bankAccount }}</p>
              <p>{{ record.bankCard }}</p>
            </template>
            <template v-if="column.key === 'payType'">
              <a-tag v-if="record.payType === 10" color="green">微信</a-tag>
              <a-tag v-if="record.payType === 20" color="blue">支付宝</a-tag>
              <a-tag v-if="record.payType === 30" color="purple">银行卡</a-tag>
            </template>
            <template v-if="column.key === 'comments'">
              <a-tooltip :title="record.comments" placement="topLeft">
                {{ record.comments }}
              </a-tooltip>
            </template>
            <template v-if="column.key === 'status'">
              <a-tag v-if="record.status === 0" color="red">未处理</a-tag>
              <a-tag v-if="record.status === 1" color="green">已处理</a-tag>
            </template>
            <template v-if="column.key === 'createTime'">
              <a-tooltip :title="`${toDateString(record.createTime)}`">
                {{ timeAgo(record.createTime) }}
              </a-tooltip>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-popconfirm>
                  <template #title>
                    <span style="font-weight: bold">
                      您确定要标记为已打款状态吗?
                    </span>
                    <p>
                      该操作仅改变提现申请状态，实际付款/支付需要您线下操作。
                    </p>
                  </template>
                  <a>已打款</a>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="您确定要使用微信企业支付到零钱功能自动打款吗?"
                >
                  <a class="ele-text-success">微信打款</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
      <!-- 编辑弹窗 -->
      <Edit
        v-model:visible="showEdit"
        :data="current"
        :merchant="merchant"
        @done="reload"
      />
    </div>
  </div>
</template>

<!--suppress TypeScriptValidateTypes -->
<script lang="ts" setup>
  import { timeAgo } from 'ele-admin-pro';
  import { formatNumber } from 'ele-admin-pro/es';
  import { createVNode, computed, 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 Edit from './components/edit.vue';
  import {
    pageMerchantWithdraws,
    // removeMerchantWithdraw,
    removeMerchantWithdraws
  } from '@/api/merchant/withdraw';
  import type {
    MerchantWithdraw,
    MerchantWithdrawParam
  } from '@/api/merchant/withdraw/model';
  // import { Category } from '@/api/goods/category/model';
  import { listMerchant } from '@/api/merchant';
  import { Merchant } from '@/api/merchant/model';

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '所属商户',
      dataIndex: 'merchantName',
      sorter: true,
      ellipsis: true,
      hideInTable: true
    },
    {
      title: '编号',
      dataIndex: 'withdrawCode',
      sorter: true
    },
    {
      title: '提现金额',
      dataIndex: 'money',
      key: 'money'
    },
    {
      title: '打款方式',
      dataIndex: 'payType',
      key: 'payType'
    },
    {
      title: '收款账号',
      dataIndex: 'bankName',
      key: 'bankName'
    },
    // {
    //   title: '备注',
    //   dataIndex: 'comments',
    //   key: 'comments',
    //   width: 380,
    //   ellipsis: true
    // },
    {
      title: '审核状态',
      dataIndex: 'status',
      key: 'status',
      sorter: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<MerchantWithdraw[]>([]);
  // 当前编辑数据
  const current = ref<MerchantWithdraw | null>(null);
  const merchant = ref<Merchant | null>(null);
  // 当前商户资金
  const money = ref<any>(0.0);
  const freezeMoney = ref<any>(0.0);
  const totalMoney = ref<any>(0.0);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

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

  // 加载状态
  const loading = ref(true);
  /* 查询 */
  const query = () => {
    loading.value = true;
    const merchantCode = localStorage.getItem('merchantCode');
    listMerchant({ merchantCode: String(merchantCode) }).then((res) => {
      if (res.length > 0) {
        loading.value = false;
        merchant.value = res[0];
        money.value = merchant.value.money;
        freezeMoney.value = merchant.value.freezeMoney;
        totalMoney.value = merchant.value.totalMoney;
      }
    });
  };

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

  // 搜索是否展开
  const searchExpand = ref(false);

  // 表格固定高度
  const fixedHeight = ref(false);

  // 表格高度
  const tableHeight = computed(() => {
    return fixedHeight.value
      ? searchExpand.value
        ? 'calc(100vh - 618px)'
        : 'calc(100vh - 562px)'
      : void 0;
  });

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

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

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

<style lang="less" scoped>
  // 文字超出隐藏(两行)
  // 需要设置文字容器的宽度
  .twoline-hide {
    width: 320px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    white-space: normal;
  }
</style>
