<template>
  <Page>
    <!-- 查询和全局功能 -->
    <Row>
      <Col :span="22">
      <!-- 查询 -->
      <Space v-if="data.isShowQuery" :wrap="true">
        <!-- <Input v-model:value="data.query.robotUuid" allowClear :placeholder="$t('robot.runningInfo.robotUuid')" /> -->
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.robotGroupName"
          placeholder="分组" style="width: 120px">
          <SelectOption v-for="(item, index) in data.groupOptions" :key="index" :value="item.groupName" :label="item.groupName"
            :text="item.groupName">{{ item.groupName }}
          </SelectOption>
        </Select>
        <Input v-model:value="data.query.robotAccount" allowClear :placeholder="$t('robot.runningInfo.robotAccount')" />
               <Input v-model:value="data.query.robotNickName" allowClear placeholder="机器人昵称" />
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.runningStatus"
          :placeholder="$t('robot.runningInfo.runningStatus')" style="width: 120px">
          <SelectOption v-for="(item, index) in data.runningStatusOptions" :key="index" :value="item.value" :label="item.label"
            :text="item.label">{{ item.label }}
          </SelectOption>
        </Select>
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.currentBehavior"
          :placeholder="$t('robot.runningInfo.currentBehavior')" style="width: 120px">
          <SelectOption v-for="(item, index) in data.currentBehaviorOptions" :key="index" :value="item.value" :label="item.label"
            :text="item.label">{{ item.label }}
          </SelectOption>
        </Select>
        <Input v-model:value="data.query.liveRoomId" allowClear :placeholder="$t('robot.runningInfo.liveRoomId')" />
        <Input v-model:value="data.query.anchorId" allowClear :placeholder="$t('robot.runningInfo.anchorId')" />
        <!-- 查询按钮 -->
        <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">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <Button type="link" size="small" @click="handleOpenTakeover(record)">{{ $t('robot.runningInfo.takeover') }}</Button>
        </template>
        <template v-else-if="column.dataIndex === 'runningStatus'">
          <span>{{ data.runningStatusMap[record.runningStatus] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'currentBehavior'">
          <span>{{ data.currentBehaviorMap[record.currentBehavior] }}</span>
        </template>
      </template>
    </Table>

    <!-- 添加 -->
    <!-- <Add ref="addRef" @close="reload"></Add> -->
    <!-- 编辑 -->
    <!-- <Edit ref="editRef" @close="reload"></Edit> -->
    <!-- 删除 -->
    <!-- <DeleteConfirm ref="deleteRef"></DeleteConfirm> -->
    <!-- 接管 -->
    <Takeover ref="takeoverRef" @close="reload"></Takeover>
  </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 Takeover from "./components/takeover.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, Dropdown, Menu, Flex, MenuItem } from 'ant-design-vue';
import { robotRunningInfo, exportFile, robotGroup } from '#/api';
import { d } from './index.ts';
import {
  DownOutlined
} from '@ant-design/icons-vue';

const SelectOption = Select.Option;

const data = reactive({
  ...d,
  runningStatusOptions: [
    { label: $t('robot.runningInfo.runningStatusOptions.v1'), value: 1 },
    { label: $t('robot.runningInfo.runningStatusOptions.v2'), value: 2 },
    { label: $t('robot.runningInfo.runningStatusOptions.v3'), value: 3 }
  ],
  currentBehaviorOptions: [
    { label: $t('robot.runningInfo.currentBehaviorOptions.v1'), value: 1 },
    { label: $t('robot.runningInfo.currentBehaviorOptions.v2'), value: 2 },
    { label: $t('robot.runningInfo.currentBehaviorOptions.v3'), value: 3 },
    { label: $t('robot.runningInfo.currentBehaviorOptions.v4'), value: 4 }
  ],
  groupOptions: []
});

const addRef = ref();
const deleteRef = ref();
const editRef = ref();
const takeoverRef = 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 handleOpenAdd() {
  addRef.value._open();
}

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

function handleOpenTakeover(item) {
  takeoverRef.value._open(item);
}

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

/**
 * 包装查询参数
 * @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);
  robotRunningInfo.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 });
}

/**
 * 导出点击事件
 */
function handleExportClick(e) {
  switch (e.key) {
    case '1':
      handleExportAll();
      break;
    case '2':
      handleExportPart();
      break;
    default:
      break;
  }
}

function handleExportAll(){
  // 包装查询参数，确保导出的数据与查询条件一致
  const param = wrapQueryParam();
  param.pageNum = 1;
  param.pageSize  = 100000;
  exportFile(robotRunningInfo.exportAllUrl(param),param , '机器人运行信息' + new Date().getTime() + '.xlsx');
}

function handleExportPart() {
  // 包装查询参数，确保导出的数据与查询条件一致
  const param = wrapQueryParam();
  exportFile(robotRunningInfo.exportPartUrl(param),param , '机器人运行信息' + new Date().getTime() + '.xlsx');
}

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


</script>