<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="merchantId"
          :columns="columns"
          :height="tableHeight"
          :customRow="customRow"
          :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 === 'logo'">
              <a-image :src="record.logo" :preview="false" :width="50" />
            </template>
            <template v-if="column.key === 'merchantName'">
              <div style="display: flex; flex-direction: column">
                <span>{{ record.merchantName }}</span>
                <span class="ele-text-placeholder">
                  {{ record.merchantCode }}
                </span>
              </div>
            </template>
            <template v-if="column.key === 'area'">
              <div
                >{{ record.province }} {{ record.city }} {{ record.region }}
                {{ record.address }}</div
              >
            </template>
            <template v-if="column.key === 'gradeName'">
              <a-tag color="orange">{{ record.gradeName }}</a-tag>
            </template>
            <template v-if="column.key === 'secondRatio'">
              <a-tag>{{ record.firstRatio * 100 }}%</a-tag>
              <a-tag>{{ record.secondRatio * 100 }}%</a-tag>
            </template>
            <template v-if="column.key === 'profit'">
              <a-tooltip title="可提现收益" placement="topLeft">
                <a-tag @click.stop="onFreezeMoney(record)">{{
                  record.money
                }}</a-tag>
              </a-tooltip>
              <a-tooltip title="已冻结" placement="topLeft">
                <a-tag @click.stop="onUnFreezeMoney(record)">{{
                  record.freezeMoney
                }}</a-tag>
              </a-tooltip>
              <a-tooltip title="累计总收益" placement="topLeft">
                <a-tag>{{ record.totalMoney }}</a-tag>
              </a-tooltip>
            </template>
            <template v-if="column.key === 'nickname'">
              <dive>{{ record.nickname }}</dive>
              <div>{{ record.merchantPhone }}</div>
            </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="orange">停业中</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 === 'createTime'">
              <a-tooltip :title="`${toDateString(record.createTime)}`">
                {{ timeAgo(record.createTime) }}
              </a-tooltip>
            </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>
      <!-- 编辑弹窗 -->
      <merchant-edit
        v-model:visible="showEdit"
        :data="current"
        @done="reload"
      />
      <FreezeMoney
        v-model:visible="showFreezeMoney"
        :data="current"
        @done="reload"
      />
      <UnFreezeMoney
        v-model:visible="showUnFreezeMoney"
        :data="current"
        @done="reload"
      />
    </div>
  </div>
</template>

<!--suppress TypeScriptValidateTypes -->
<script lang="ts" setup>
  import { timeAgo } from 'ele-admin-pro';
  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 MerchantEdit from './components/merchant-edit.vue';
  import FreezeMoney from './components/freeze-money.vue';
  import UnFreezeMoney from './components/un-freeze-money.vue';
  import {
    pageMerchant,
    removeMerchant,
    removeBatchMerchant
  } from '@/api/merchant';
  import type { Merchant, MerchantParam } 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: 'logo',
    //   width: 120,
    //   key: 'logo'
    // },
    {
      title: '门店名称',
      dataIndex: 'merchantName',
      key: 'merchantName',
      ellipsis: true
    },
    {
      title: '门店类型',
      dataIndex: 'gradeName',
      key: 'gradeName'
    },
    {
      title: '所在地区',
      dataIndex: 'area',
      key: 'area'
    },
    // {
    //   title: '地址',
    //   dataIndex: 'address',
    //   key: 'address'
    // },
    {
      title: '门店负责人',
      dataIndex: 'nickname',
      key: 'nickname'
    },
    // {
    //   title: '联系电话',
    //   dataIndex: 'merchantPhone',
    //   key: 'merchantPhone'
    // },
    {
      title: '收益比率',
      dataIndex: 'secondRatio',
      key: 'secondRatio'
    },
    {
      title: '收益',
      dataIndex: 'profit',
      key: 'profit'
    },
    {
      title: '备注',
      dataIndex: 'comments',
      key: 'comments',
      hideInTable: true,
      ellipsis: true
    },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   sorter: true,
    //   key: 'status',
    //   showSorterTooltip: false,
    //   customRender: ({ text }) => ['上架', '下架'][text]
    // },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      hideInTable: true,
      sorter: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      ellipsis: true,
      hideInTable: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<Merchant[]>([]);
  // 当前编辑数据
  const current = ref<Merchant | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  const showFreezeMoney = ref(false);
  const showUnFreezeMoney = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    if (filters) {
      where.brand = filters.brand;
    }
    // 只查门店类型
    where.sceneType = 'SHOP_USER';
    where.limit = 100;
    return pageMerchant({ ...where, ...orders, page, limit });
  };

  /* 搜索 */
  const reload = (where?: MerchantParam) => {
    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?: Merchant) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  const onFreezeMoney = (row?: Merchant) => {
    current.value = row ?? null;
    showFreezeMoney.value = true;
  };

  const onUnFreezeMoney = (row?: Merchant) => {
    current.value = row ?? null;
    showUnFreezeMoney.value = true;
  };

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

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

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