<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="profitId"
          :columns="columns"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'categoryId'">
              {{ record.categoryId === 25 ? '早餐' : '' }}
              {{ record.categoryId === 26 ? '午餐' : '' }}
              {{ record.categoryId === 27 ? '晚餐' : '' }}
            </template>
            <template v-if="column.key === 'player'">
              <div class="user-box">
                <a-avatar
                  :size="30"
                  :src="`${record.playerAvatar}`"
                  style="margin-right: 4px"
                >
                  <template #icon>
                    <UserOutlined />
                  </template>
                </a-avatar>
                <div class="user-info">
                  <span>{{ record.playerNickname }}</span>
                  <span class="ele-text-placeholder">{{
                    record.gradeName
                  }}</span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'nickname'">
              <div class="user-box">
                <a-avatar
                  :size="30"
                  :src="`${record.avatar}`"
                  style="margin-right: 4px"
                >
                  <template #icon>
                    <UserOutlined />
                  </template>
                </a-avatar>
                <div class="user-info">
                  <span>{{ record.nickname }}</span>
                  <span class="ele-text-placeholder">{{
                    record.merchantName
                  }}</span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'orderPrice'">
              <div class="ele-text-danger">￥{{ record.orderPrice }}</div>
            </template>
            <template v-if="column.key === 'money'">
              <div class="ele-text-success">￥{{ record.money }}</div>
              <div class="ele-text-placeholder">￥{{ record.balance }}</div>
            </template>
            <template v-if="column.key === 'scene'">
              <a-tag v-if="record.scene === 10">推广收益</a-tag>
              <a-tag v-if="record.scene === 20">团队收益</a-tag>
              <a-tag v-if="record.scene === 40">区域业绩提成</a-tag>
              <a-tag v-if="record.scene === 41">市级业绩提成</a-tag>
              <a-tag v-if="record.scene === 42">省级级业绩提成</a-tag>
              <a-tag v-if="record.scene === 50">充值收益</a-tag>
              <a-tag v-if="record.scene === 60">门店服务费</a-tag>
            </template>
            <template v-if="column.key === 'deliveryTime'">
              {{ toDateString(record.deliveryTime, 'MM-dd') }}
              {{ getWeek(record.week) }}
            </template>
            <template v-if="column.key === 'deliveryStatus'">
              <a-tag
                v-if="record.deliveryStatus === 10"
                color="orange"
                @click="onDeliveryStatus(record, 20)"
                >未签到</a-tag
              >
              <a-tag
                v-if="record.deliveryStatus === 20"
                color="green"
                @click="onDeliveryStatus(record, 10)"
                >已签到</a-tag
              >
            </template>
            <template v-if="column.key === 'createTime'">
              {{ record.createTime }}
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button @click="openInfo(record)">详情</a-button>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 订单详情 -->
    <order-info v-model:visible="showInfo" :data="current" @done="reload" />
  </div>
</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 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 OrderInfo from './components/order-info.vue';
  import { getWeek } from '@/utils/common';
  import {
    pageProfit,
    removeBatchProfit,
    updateProfit
  } from '@/api/love/profit';
  import type { Profit, ProfitParam } from '@/api/love/profit/model';
  import useFormData from '@/utils/use-form-data';

  defineProps<{
    activeKey?: boolean;
    data?: any;
  }>();

  // 表格实例
  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: '操作',
    //   key: 'action',
    //   width: 120,
    //   align: 'center',
    //   fixed: 'left',
    //   hideInSetting: true
    // },
    // {
    //   title: '菜品封面图',
    //   dataIndex: 'imageUrl',
    //   key: 'imageUrl',
    //   align: 'center'
    // },
    // {
    //   title: 'ID',
    //   dataIndex: 'profitId',
    //   width: 80
    // },
    {
      title: '订单号',
      dataIndex: 'logId',
      key: 'logId',
      width: 120
    },
    {
      title: '买家信息',
      dataIndex: 'player',
      key: 'player'
    },
    {
      title: '订单金额',
      dataIndex: 'orderPrice',
      key: 'orderPrice'
    },
    {
      title: '获得收益',
      dataIndex: 'nickname',
      key: 'nickname',
      width: 320
    },
    {
      title: '收益金额',
      dataIndex: 'money',
      key: 'money'
    },
    {
      title: '收益类型',
      dataIndex: 'scene',
      key: 'scene'
    },
    {
      title: '备注',
      dataIndex: 'comments',
      key: 'comments'
    },
    {
      title: '结算时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      sorter: true,
      customRender: ({ text }) => toDateString(text)
    }
  ]);

  // 表格选中数据
  const selection = ref<Profit[]>([]);
  // 当前编辑数据
  const current = ref<Profit | null>(null);
  // 是否显示资产详情
  const showInfo = ref(false);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    // 搜索条件
    if (filters.payStatus) {
      where.payStatus = filters.payStatus;
    }
    if (filters.deliveryStatus) {
      where.deliveryStatus = filters.deliveryStatus;
    }
    where.payStatus = 20;
    where.hasNum = false;
    where.orderStatus = 10;
    where.tenantId = localStorage.getItem('tenantId');
    return pageProfit({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表单数据
  const { form } = useFormData<Profit>({
    profitId: undefined,
    payStatus: undefined,
    playerAvatar: '',
    playerNickname: '',
    balance: undefined,
    playerBalance: undefined,
    orderPrice: undefined,
    status: undefined
  });

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

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

  const onDeliveryStatus = (row?: Profit, deliveryStatus?: number) => {
    Modal.confirm({
      title: '提示',
      content: '确定要修改签到状态吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        form.orderGoodsId = row?.orderGoodsId;
        form.deliveryStatus = deliveryStatus;
        updateProfit(form).then((msg) => {
          message.success(msg);
          reload();
        });
      }
    });
  };

  /* 批量删除 */
  const removeBatch = () => {
    console.log(selection.value);
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchProfit(selection.value.map((d) => d.orderGoodsId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

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

  reload();
</script>

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

<style lang="less" scoped>
  p {
    line-height: 0.8;
  }
  .sys-org-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-org-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
  .price-edit {
    padding-right: 5px;
  }
  .comments {
    max-width: 200px;
  }
  .user-box {
    display: flex;
    align-items: center;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
    }
  }
</style>
