<template>
  <Page>
    <!-- 查询和全局功能 -->
    <Row>
      <Col :span="22">
      <!-- 查询 -->
      <Space v-if="data.isShowQuery" :wrap="true">
        <!-- <Input v-model:value="data.query.uuid" allowClear :placeholder="$t('robot.runRecord.uuid')" /> -->
        <!-- <Input v-model:value="data.query.robotUuid" allowClear :placeholder="$t('robot.runRecord.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.runRecord.robotAccount')" />
               <Input v-model:value="data.query.robotNickName" allowClear placeholder="机器人昵称" />
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.configType"
          placeholder="动作" style="width: 120px">
          <SelectOption v-for="(item, index) in data.actionOptions" :key="index" :value="item" :label="item"
            :text="item">{{ item }}
          </SelectOption>
        </Select>
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.executeStatus"
          :placeholder="$t('robot.runRecord.executeStatus')" style="width: 120px">
          <SelectOption v-for="(item, index) in data.executeStatusOptions" :key="index" :value="item.value" :label="item.label"
            :text="item.label">{{ item.label }}
          </SelectOption>
        </Select>
        <!-- <Input v-model:value="data.query.creator" allowClear :placeholder="$t('robot.runRecord.creator')" /> -->
        <!-- 查询按钮 -->
        <Button @click="handleQuery" :loading="data.loading" :disabled="data.loading" style="background-color: #0084CA;color: white">
          {{ $t('common.query') }}
        </Button>
        <Button @click="handleReset" :loading="data.loading" :disabled="data.loading" danger>
          {{ $t('common.reset') }}
        </Button>
      </Space>

      <!-- 全局功能 -->
      <Flex gap="middle"  style="padding: 15px 0">
        <!-- <Button @click="handleAdd" style="background-color: #0084CA;color: white">
          {{ $t('robot.runRecord.addTitle') }}
        </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: 1500 }" @change="handleTableChange" size="small">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <!-- <Button type="link" size="small" @click="handleEdit(record)">{{ $t('common.edit') }}</Button>
          <Button type="link" size="small" @click="handleDelete(record)">{{ $t('common.delete') }}</Button> -->
        </template>
        <template v-else-if="column.dataIndex === 'configType'">
          <span>{{ data.configTypeMap[record.configType] || record.configType }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'executeStatus'">
          <span>{{ data.executeStatusMap[record.executeStatus] || record.executeStatus }}</span>
        </template>
      </template>
    </Table>

    <!-- 添加模态框 -->
    <!-- <AddModal ref="addModalRef" @close="handleAddModalClose"/> -->
    
    <!-- 编辑模态框 -->
    <!-- <EditModal ref="editModalRef" @close="handleEditModalClose"/> -->
  </Page>
</template>

<script setup lang="ts">
import AddModal from "./components/add.vue";
import EditModal 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, Modal, Dropdown, Menu, Flex, MenuItem } from 'ant-design-vue';
import { robotRunRecord, exportFile, robotGroup } from '#/api';
import { d } from './index';
import {
  DownOutlined
} from '@ant-design/icons-vue';

const SelectOption = Select.Option;

const data = reactive({
  ...d,
  configTypeOptions: [
    { label: $t('robot.runRecord.configTypeOptions.v1'), value: 'v1' },
    { label: $t('robot.runRecord.configTypeOptions.v2'), value: 'v2' },
    { label: $t('robot.runRecord.configTypeOptions.v3'), value: 'v3' }
  ],
  executeStatusOptions: [
    { label: $t('robot.runRecord.executeStatusOptions.v0'), value: 0 },
    { label: $t('robot.runRecord.executeStatusOptions.v1'), value: 1 },
    { label: $t('robot.runRecord.executeStatusOptions.v2'), value: 2 },
    { label: $t('robot.runRecord.executeStatusOptions.v3'), value: 3 },
    { label: $t('robot.runRecord.executeStatusOptions.v4'), value: 4 }
  ],
  groupOptions: []
});

const addModalRef = ref();
const editModalRef = 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 handleAdd() {
  addModalRef.value._open();
}

function handleEdit(item) {
  editModalRef.value._open(item);
}

function handleDelete(item) {
  Modal.confirm({
    title: $t('common.deleteConfirm'),
    content: $t('common.deleteConfirmContent') + '【' + item.configName + '】?',
    onOk() {
      robotRunRecord.removeByUid({ uuid: item.uuid }).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 handleReset() {
  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);
  robotRunRecord.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 handleTableChange(pagination: any, filters: any, sorter: any) {
  handleQuery(pagination, filters, sorter);
}

function handleAddModalClose(submit: Boolean) {
  if (submit) {
    handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
  }
}

function handleEditModalClose(submit: Boolean) {
  if (submit) {
    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(robotRunRecord.exportAllUrl(param),param , '机器人运行记录' + new Date().getTime() + '.xlsx');
}

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

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