<template>
  <Page>
    <!-- 查询和全局功能 -->
    <Row>
      <Col :span="22">
      <!-- 查询 -->
      <Space v-if="data.isShowQuery" :wrap="true">
        <!-- <Input v-model:value="data.query.code" allowClear :placeholder="$t('robot.account.code')" /> -->
        <Input v-model:value="data.query.email" allowClear :placeholder="$t('robot.account.email')" />
        <Input v-model:value="data.query.nickname" allowClear :placeholder="$t('robot.account.nickname')" />
        <Input v-model:value="data.query.mobile" allowClear :placeholder="$t('robot.account.mobile')" />
        <Input v-model:value="data.query.userNumber" allowClear :placeholder="$t('robot.account.userNumber')" />
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.status"
          :placeholder="$t('robot.account.status')" style="width: 120px">
          <SelectOption v-for="(item, index) in data.statusOptions" :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.groupName" :placeholder="$t('robot.account.groupName')" style="width: 150px">
          <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.managerName" allowClear :placeholder="$t('robot.account.managerName')" /> -->
        <!-- 查询按钮 -->
        <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>
        <Button @click="handleValidateAccount" style="background-color: #52c41a;color: white">
          验证账号
        </Button>
        <Button @click="handleValidateInvalidAccount" style="background-color: #faad14;color: white">
          验证无效账号
        </Button>
        <Upload
            v-model:file-list="data.batchUpdateFileList"
            :maxCount="1"
            :action="robotAccount.importBatchUpdateUrl()"
            accept=".xls, .xlsx, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :headers="uploadHeader()"
            @change="handleBatchUpdateUploadChange"
            :show-upload-list="false"
          >
            <Button style="background-color: #722ed1;color: white">
              <upload-outlined></upload-outlined>
              批量更新导入
            </Button>
          </Upload>
         <Upload
            v-model:file-list="data.fileList"
            :maxCount="1"
            :action="robotAccount.importUrl()"
            accept=".xls, .xlsx, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :headers="uploadHeader()"
            @change="handleUploadChange"
            :show-upload-list="false"
          >
            <Button>
              <upload-outlined></upload-outlined>
              导入
            </Button>
          </Upload>
          
          <Dropdown>
            <template #overlay>
              <Menu @click="handleExportClick">
                <MenuItem key="1">
                  导出全部数据
                </MenuItem>
                <MenuItem key="2">
                  导出当前数据
                </MenuItem>
                <MenuItem key="3">
                  导出上传模板
                </MenuItem>
              </Menu>
            </template>
            <Button>
              导出
              <DownOutlined/>
            </Button>
          </Dropdown>
          <Button @click="handleBatchEdit" :disabled="data.selectedRowKeys.length === 0" style="background-color: #1890ff;color: white">
            批量修改
          </Button>
      </Flex>
      </Col>
    </Row>

    <!-- 数据展示 -->
    <Table :dataSource="data.datas" :columns="data.columns" bordered :loading="data.loading"
      :pagination="data.pagination" :scroll="{ x: 1500 }" @change="handleQuery" size="small"
      :row-selection="{ selectedRowKeys: data.selectedRowKeys, onChange: onSelectChange }"
      :row-key="record => record.uuid">
      <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>
          <Button type="link" size="small" @click="handleValidateSingleAccount(record)" style="color: #52c41a">验证账号</Button>
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <span>{{ data.statusMap[record.status] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'valid'">
          <span>{{record.valid == undefined ? '未验证' : data.validMap[record.valid] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'lastValidationTime'">
          <span>{{ formatDateTime(record.lastValidationTime) }}</span>
        </template>
      </template>
    </Table>

    <!-- 添加 -->
    <Add ref="addRef" @close="reload"></Add>
    <!-- 编辑 -->
    <Edit ref="editRef" @close="reload"></Edit>
    <!-- 删除 -->
    <DeleteConfirm ref="deleteRef"></DeleteConfirm>
    <!-- 批量修改 -->
    <BatchEdit ref="batchEditRef" @close="reload"></BatchEdit>
  </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 BatchEdit from "./components/batchEdit.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, Upload ,Dropdown,Menu,Flex } from 'ant-design-vue';
import {
  UploadOutlined,
  DownOutlined
} from '@ant-design/icons-vue';
import { robotAccount ,exportFile, robotGroup } from '#/api';
import { d } from './index.ts';
import { useAccessStore } from '@vben/stores';


const accessStore = useAccessStore();

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

const data = reactive({
  ...d,
  statusOptions: [
    { label: $t('robot.account.statusOptions.v0'), value: 0 },
    { label: $t('robot.account.statusOptions.v1'), value: 1 }
  ],
  groupOptions: [],
  selectedRowKeys: [],
  selectedRows: []
});

const addRef = ref();
const deleteRef = ref();
const editRef = ref();
const batchEditRef = 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 handleUploadChange(info) {
  console.log(info);
  if (info.file.status !== 'uploading') {
    message.info('文件上传中');
  }
  if (info.file.status === 'done') {
    let response = info.file.response;
    console.log(response);
    if (response.code != null && response.code !== '00000') {
      console.log('上传文件失败：', response)
      message.error(response.msg);
      return;
    }
    message.success('导入成功');
    reload();
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

function handleBatchUpdateUploadChange(info) {
  console.log(info);
  if (info.file.status !== 'uploading') {
    message.info('批量更新文件上传中');
  }
  if (info.file.status === 'done') {
    let response = info.file.response;
    console.log(response);
    if (response.code != null && response.code !== '00000') {
      console.log('批量更新文件上传失败：', response)
      message.error(response.msg);
      return;
    }
    message.success('批量更新导入成功');
    reload();
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 批量更新文件上传失败`);
  }
};

function uploadHeader() {
  const Authorization = accessStore.accessToken
  return {
    Authorization
  }
}

function onSelectChange(selectedRowKeys, selectedRows) {
  data.selectedRowKeys = selectedRowKeys;
  data.selectedRows = selectedRows;
}

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(robotAccount.exportAllUrl(param),param , '机器人信息' + new Date().getTime() + '.xlsx');
}
function handleExportPart() {
  // 包装查询参数，确保导出的数据与查询条件一致
  const param = wrapQueryParam();
  exportFile(robotAccount.exportPartUrl(param),param , '机器人信息' + new Date().getTime() + '.xlsx');
}
function handleExportTemplate() {
  exportFile(robotAccount.dwonloadTemplateUrl(),{} , '机器人模板' + new Date().getTime() + '.xlsx');
}



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

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

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

/**
 * 验证账号（全局）
 */
function handleValidateAccount() {
  data.loading = true;
  robotAccount.isValidAll({}).then((res) => {
    if (res.error) {
      message.error('验证失败：' + res.msg);
      return;
    }
    message.success('账号验证中，可能需要一些时间，请稍后刷新列表');
    reload();
  }).catch((error) => {
    message.error('验证失败：' + error.message);
  }).finally(() => {
    data.loading = false;
  });
}

/**
 * 验证无效账号（全局）
 */
function handleValidateInvalidAccount() {
  data.loading = true;
  robotAccount.isValidNot({}).then((res) => {
    if (res.error) {
      message.error('验证失败：' + res.msg);
      return;
    }
    message.success('无效账号验证中，可能需要一些时间，请稍后刷新列表');
    reload();
  }).catch((error) => {
    message.error('验证失败：' + error.message);
  }).finally(() => {
    data.loading = false;
  });
}

/**
 * 验证单个账号
 */
function handleValidateSingleAccount(record) {
  data.loading = true;
  robotAccount.isValid({ uuid: record.uuid }).then((res) => {
    if (res.error) {
      message.error('验证失败：' + res.msg);
      return;
    }
    message.success('账号验证中，可能需要一些时间，请稍后刷新列表');
    reload();
  }).catch((error) => {
    message.error('验证失败：' + error.message);
  }).finally(() => {
    data.loading = false;
  });
}

/**
 * 批量修改
 */
function handleBatchEdit() {
  if (data.selectedRowKeys.length === 0) {
    message.warning('请先选择要修改的账号');
    return;
  }
  batchEditRef.value._open(data.selectedRows);
}

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

/**
 * 格式化日期时间
 * @param {string} dateTime 日期时间字符串
 * @returns {string} 格式化后的日期时间
 */
function formatDateTime(dateTime) {
  if (!dateTime) {
    return '-';
  }
  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) {
      return dateTime;
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    return dateTime;
  }
}
</script>