<template>
  <Page>
    <!-- 查询和全局功能 -->
    <Row>
      <Col :span="22">
      <!-- 查询 -->
      <Space v-if="data.isShowQuery" :wrap="true">
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.robotGroupName" placeholder="分组" style="width: 150px">
          <Select.Option v-for="(item, index) in data.groupOptions" :key="index" :value="item.groupName" :label="item.groupName"
            :text="item.groupName">{{ item.groupName }}
          </Select.Option>
        </Select>
        <Input v-model:value="data.query.robotAccount" allowClear :placeholder="$t('robot.consumptionRecord.robotAccount')" />
        <InputNumber v-model:value="data.query.consumptionAmount" allowClear :placeholder="$t('robot.consumptionRecord.consumptionAmount')" style="width: 150px" />
       <Input v-model:value="data.query.robotNickName" allowClear placeholder="机器人昵称" />
        <Input v-model:value="data.query.giftName" allowClear placeholder="礼物名称" />
        <Input v-model:value="data.query.anchorName" allowClear placeholder="主播名称" />
                <Input v-model:value="data.query.anchorId" allowClear placeholder="主播ID" />
        <Input v-model:value="data.query.roomName" allowClear placeholder="直播间名称" />
        <!-- 查询按钮 -->
        <Button @click="handleQuery" :loading="data.loading" :disabled="data.loading"
          style="background-color: #0084CA;color: white">
          {{ $t('common.search') }}
        </Button>
        <Button @click="resetQuery" :loading="data.loading" :disabled="data.loading" danger>
          {{ $t('common.reset') }}
        </Button>
      </Space>

      <!-- 全局功能 -->
      <Flex gap="middle"  style="padding: 15px 0">
        <!-- <Button @click="handleOpenAdd" style="background-color: #0084CA;color: white">
          {{ $t('common.add') }}
        </Button> -->
        
        <Dropdown>
          <template #overlay>
            <Menu @click="handleExportClick">
              <MenuItem key="1">
                导出全部数据
              </MenuItem>
              <MenuItem key="2">
                导出当前数据
              </MenuItem>
            </Menu>
          </template>
          <Button>
            导出
            <DownOutlined/>
          </Button>
        </Dropdown>
      </Flex>
      </Col>
    </Row>

    <!-- 数据展示 -->
    <Table :dataSource="data.datas" :columns="data.columns" bordered :loading="data.loading"
      :pagination="data.pagination" :scroll="{ x: 1800 }" @change="handleQuery" size="small"
      :resizable="true">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <!-- <Button type="link" size="small" @click="handleOpenEdit(record)">{{ $t('common.edit') }}</Button>
          <Button type="link" size="small" @click="handleDeleteConfirm(record)">{{ $t('common.delete') }}</Button> -->
        </template>
        <template v-else-if="column.dataIndex === 'consumptionAmount'">
          <Tooltip :title="record.consumptionAmount">
            <span>{{ record.consumptionAmount }}</span>
          </Tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'giftIcon'">
          <img v-if="record.giftIcon" :src="record.giftIcon" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;" alt="礼物图片" />
          <span v-else>-</span>
        </template>
        <template v-else-if="column.dataIndex === 'anchorAvatar'">
          <img v-if="record.anchorAvatar" :src="record.anchorAvatar" style="width: 40px; height: 40px; object-fit: cover; border-radius: 50%;" alt="主播头像" />
          <span v-else>-</span>
        </template>
        <template v-else-if="column.dataIndex === 'giftInfo'">
          <Tooltip :title="record.giftName ? `${record.giftName} x ${record.giftQuantity || 1}` : '-'">
            <span v-if="record.giftName">{{ record.giftName }} x {{ record.giftQuantity || 1 }}</span>
            <span v-else>-</span>
          </Tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'anchorInfo'">
          <Tooltip :title="record.anchorName ? `${record.anchorName} (ID: ${record.anchorId || '-'})` : '-'">
            <span v-if="record.anchorName">{{ record.anchorName }} (ID: {{ record.anchorId || '-' }})</span>
            <span v-else>-</span>
          </Tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'roomInfo'">
          <Tooltip :title="record.roomName ? `${record.roomName} (ID: ${record.roomId || '-'})` : '-'">
            <span v-if="record.roomName">{{ record.roomName }} (ID: {{ record.roomId || '-' }})</span>
            <span v-else>-</span>
          </Tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'giftUnitPrice'">
          <Tooltip :title="record.giftUnitPrice">
            <span v-if="record.giftUnitPrice">{{ record.giftUnitPrice }}</span>
            <span v-else>-</span>
          </Tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'giftTotalPrice'">
          <Tooltip :title="record.giftTotalPrice">
            <span v-if="record.giftTotalPrice">{{ record.giftTotalPrice }}</span>
            <span v-else>-</span>
          </Tooltip>
        </template>
        <!-- 为其他文本列添加默认的 Tooltip -->
        <template v-else-if="['robotGroupName', 'robotAccount', 'robotNickName', 'consumptionTime', 'consumptionMethod', 'roomId', 'consumptionInfo', 'notes'].includes(column.dataIndex)">
          <Tooltip :title="record[column.dataIndex] || '-'">
            <span>{{ record[column.dataIndex] || '-' }}</span>
          </Tooltip>
        </template>
      </template>
    </Table>

    <!-- 添加 -->
    <!-- <Add ref="addRef" @close="reload"></Add> -->
    <!-- 编辑 -->
    <!-- <Edit ref="editRef" @close="reload"></Edit> -->
    <!-- 删除 -->
    <!-- <DeleteConfirm ref="deleteRef"></DeleteConfirm> -->
  </Page>
</template>

<script setup lang="ts">
import DeleteConfirm from "#/components/myui/deleteConfirm/index.vue";
import Add from "./components/add.vue";
import Edit from "./components/edit.vue";
import { reactive, onMounted, ref } from "vue";
import { $t } from '@vben/locales';
import { Page } from '@vben/common-ui';
import { Button, Input, Space, Table, Row, Col, message, Select, DatePicker, InputNumber, Dropdown, Menu, Flex, Tooltip } from 'ant-design-vue';
import {
  DownOutlined
} from '@ant-design/icons-vue';
import { robotConsumptionRecord, exportFile, robotGroup } from '#/api';
import { d } from './index.ts';

const SelectOption = Select.Option;
const MenuItem = Menu.Item;

const data = reactive({
  ...d,
  groupOptions: []
});

const addRef = ref();
const deleteRef = ref();
const editRef = ref();

// 选择框过滤方法
const selectFilterOption = (input: string, option: any) => {
  return option.text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

onMounted(() => {
  loadGroupOptions();
  handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
})

// 加载分组选项
function loadGroupOptions() {
  robotGroup.queryList({}).then((res) => {
    if (res.error) {
      return;
    }
    data.groupOptions = res.data || [];
  });
}

function handleOpenAdd() {
  addRef.value._open();
}

function handleOpenEdit(item) {
  editRef.value._open(item);
}

function handleDeleteConfirm(item) {
  deleteRef.value._open($t('common.deleteConfirm') + '【' + item.robotAccount + '】?').then(() => {
    robotConsumptionRecord.removeByUid(item).then((res) => {
      if (res.error) {
        return;
      }
      message.success($t('common.deleteSuccess'));
      handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
    })
  })
}

function handleExportClick(item){
  console.log(item);
  if(item.key == 1){
    //导出全部数据
    handleExportAll();
  }else if(item.key == 2) {
    //导出当前数据
    handleExportPart();
  }else if(item.key == 3){
    //导出上传模板
    handleExportTemplate();
  }
}

function handleExportAll(){
  // 包装查询参数，确保导出的数据与查询条件一致
  const param = wrapQueryParam();
  param.pageNum = 1;
  param.pageSize  = 100000;
  exportFile(robotConsumptionRecord.exportAllUrl(param),param , '消费记录' + new Date().getTime() + '.xlsx');
}

function handleExportPart() {
  // 包装查询参数，确保导出的数据与查询条件一致
  const param = wrapQueryParam();
  exportFile(robotConsumptionRecord.exportPartUrl(param),param , '消费记录' + new Date().getTime() + '.xlsx');
}

function handleExportTemplate() {
  exportFile(robotConsumptionRecord.downloadTemplateUrl(),{} , '消费记录模板' + new Date().getTime() + '.xlsx');
}

/**
 * 包装查询参数
 * @param page
 * @param filter
 * @param sorter
 */
function wrapQueryParam(page, filter, sorter) {
  let { current, pageSize } = { ...data.pagination, ...(page || {}) };
  let param = {
    pageNum: current,
    pageSize: pageSize,
  }
  //查询
  for (const key in data.query) {
    if (data.query[key] == null || data.query[key] === '') {
      continue;
    }
    param[key] = data.query[key];
  }
  //过滤
  if (filter) {
    for (const key in filter) {
      const value = Array.isArray(filter[key]) && filter[key].length > 0 ? filter[key][0] : filter[key];
      param[key] = value || param[key];
    }
  }
  //排序
  if (sorter && sorter.field && sorter.order) {
    param.sorts = [{ name: sorter.field, desc: sorter.order == 'descend' }]
  }
  return param;
}

/**
 * 重置查询
 */
function resetQuery() {
  data.query = {}
  handleQuery({ current: 1, pageSize: data.pagination.pageSize });
}

/**
 * 查询
 * @param page
 * @param filter
 * @param sorter
 */
function handleQuery(page, filter, sorter) {
  data.loading = true;
  let param = wrapQueryParam(page, filter, sorter);
  robotConsumptionRecord.queryPage(param).then((res) => {
    if (res.error) {
      return;
    }
    data.datas = res.data.list || [];
    data.pagination.total = res.data.total || 0;
    data.pagination.current = res.data.current || res.data.pageNum || 1;
    data.pagination.pageSize = res.data.pageSize && res.data.pageSize > 10 ? res.data.pageSize : 10;
    
  }).finally(() => {
    data.loading = false;
  })
}

function reload() {
  handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
}
</script>