<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null"
    title="机器人分配" width="80%" @cancel="_close">

    <!-- 查询功能和批量操作 -->
    <div style="margin-bottom: 16px;">
      <Space :wrap="true" style="margin-bottom: 10px;">
      
        <Input v-model:value="data.query.account" allowClear placeholder="请输入机器人账号" />
        <Input v-model:value="data.query.groupName" 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>

        <Button type="primary" @click="handleBatchAssign" :disabled="selectedRowKeys.length === 0 || data.loading">
          {{ $t('common.batchAssign') }}
        </Button>
        <Button danger @click="handleClearRelation" :disabled="!data.userInfo || data.loading">
          {{ $t('common.clearRelation') }}
        </Button>
      </Space>


    </div>

    <!-- 数据展示 -->
    <Table :dataSource="data.datas" :columns="data.columns" bordered :loading="data.loading"
      :pagination="data.pagination" :scroll="{ x: 1500 }" @change="handleQuery" size="small"
      :rowSelection="rowSelection" :rowKey="(record) => record.uuid">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <Button type="link" size="small" @click="handleAssign(record)">{{ $t('common.assign') }}</Button>
        </template>
      </template>

    </Table>
  </Modal>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { $t } from '@vben/locales';
import { Modal, Input, Select, Table, Button, Space, message } from 'ant-design-vue';
import { robotAccount, userRobotRelation } from '#/api';

const SelectOption = Select.Option;

interface Emits {
  (e: 'close', submit: Boolean): void
}

const emits = defineEmits<Emits>();

// 选中的行的key
const selectedRowKeys = ref([]);
const selectedRows = ref([]);

// 行选择配置
const rowSelection = {
  selectedRowKeys,
  onChange: (newSelectedRowKeys: string[], newSelectedRows: any[]) => {
    console.log('selectedRowKeys: ', newSelectedRowKeys);
    selectedRowKeys.value = newSelectedRowKeys;
    selectedRows.value = newSelectedRows;
  }
};

// 列定义
const columns = [
  {
    title: '机器人账号',
    dataIndex: 'account',
   
  },
    {
    title: '机器人分组',
    dataIndex: 'groupName',
   
  },
  {
    title: $t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
    width: 100
  }
];

const data = reactive({
  isShowModal: false,
  loading: false,
  pagination: {
    total: 0,
    current: 1,
    pageSize: 10,
    showTotal: (total, range) => `共 ${total} 条`,
    showSizeChanger: true,
    pageSizeOptions: ['10', '200', '500', '1000', '5000'],
    showQuickJumper: true,
  },
  datas: [],
  query: {
    account: '',
    groupName: '',
  },
  columns,
  masterAccountOptions: [],
  userInfo: null
});

/**
 * 重置内容
 */
function reload(success) {
  success && handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
}

function handleAssign(record) {
  // 实现单个分配功能
  Modal.confirm({
    title: $t('common.assignConfirm'),
    content: `确定要分配机器人 ${record.account} 到运营人员吗？`,
    onOk() {
      // 调用分配API
      userRobotRelation.assignRobot({
        userUuid: data.userInfo?.uid,
        robotUuids: [record.uuid],
        // 这里可以根据实际需求添加运营人员ID等参数
      }).then(res => {
        if (!res.error) {
          message.success($t('common.assignSuccess'));
          // 重新查询并回显选中状态
          handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
        }
      }).catch(() => {
        message.error($t('common.assignFailed'));
      });
    }
  });
}

function handleBatchAssign() {
  // 实现批量分配功能
  if (selectedRowKeys.value.length === 0) {
    message.warning($t('common.pleaseSelectItems'));
    return;
  }

  Modal.confirm({
    title: $t('common.assignConfirm'),
    content: `确定要批量分配选中的机器人到运营人员吗？`,
    onOk() {
      // 调用批量分配API
      userRobotRelation.assignRobot({
        robotUuids: selectedRowKeys.value,
        userUuid: data.userInfo?.uid
        // 这里可以根据实际需求添加运营人员ID等参数
      }).then(res => {
        if (!res.error) {
          message.success($t('common.assignSuccess'));
          // 重新查询并回显选中状态
          handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
        }
      }).catch(() => {
        message.error($t('common.assignFailed'));
      });
    }
  });
}

function handleClearRelation() {
  // 实现清空关系功能
  Modal.confirm({
    title: $t('common.confirm'),
    content: '确定要清空该运营人员所有机器人关系吗？',
    onOk() {
      // 调用清空API
      userRobotRelation.clear({
        userUuid: data.userInfo?.uid
      }).then(res => {
        if (!res.error) {
          message.success($t('common.success'));
          // 重新查询并回显选中状态
          handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
        }
      }).catch(() => {
        message.error($t('common.failed'));
      });
    }
  });
}

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

/**
 * 包装查询参数
 * @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 = {
    accountNumber: null,
    fansNumber: '',
    nickname: '',
    gender: undefined,
  };
  // 清空选中状态
  selectedRowKeys.value = [];
  selectedRows.value = [];
  data.pagination.current = 1;
  handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
}

/**
 * 查询方法
 * @param page
 * @param filter
 * @param sorter
 */
function handleQuery(page, filter, sorter) {
  let param = wrapQueryParam(page, filter, sorter);

  data.loading = true;
  Promise.all([
    robotAccount.queryPage(param),
    // 如果有用户信息，使用getFansList接口查询已分配的机器人列表用于选中回显
    data.userInfo ? userRobotRelation.getRobotList({ userId: data.userInfo.id }) : Promise.resolve({ data: [] })
  ]).then(([fansRes, relationRes]) => {
    if (fansRes.data) {
      data.datas = fansRes.data.list || [];
      data.pagination.current = fansRes.data.pageNum || 1;
      data.pagination.pageSize = fansRes.data.pageSize || 10;
      data.pagination.total = fansRes.data.total;
    }
    
    // 更新已选中的机器人
    if (relationRes.data && data.userInfo) {
      // getFansList返回的是umFans实体格式的列表
      const assignedFans = relationRes.data || [];
      const assignedFanIds = assignedFans.map(item => item.uuid); // 直接使用uuid作为机器人ID
      
      // 从当前页的数据中筛选出已分配的机器人
      const currentPageAssignedIds = data.datas
        .filter(fan => assignedFanIds.includes(fan.uuid))
        .map(fan => fan.uuid);
      
      selectedRowKeys.value = currentPageAssignedIds;
      selectedRows.value = data.datas.filter(fan => assignedFanIds.includes(fan.uuid));
    }
  }).finally(() => {
    data.loading = false;
  });
}

// 获取主播账号列表
function loadMasterAccounts() {
  // masterAccount.queryPage({ pageSize: 100 }).then(res => {
  //   if (res.data) {
  //     data.masterAccountOptions = res.data.list || [];
  //   }
  // });
}

function _open(userInfo) {
  data.isShowModal = true;
  data.userInfo = userInfo;
  // 重置查询，同时会加载并回显选中状态
  resetQuery();
}

function _close(submit: Boolean = false) {
  data.isShowModal = false;
  data.datas = [];
  // 清空选中状态
  selectedRowKeys.value = [];
  selectedRows.value = [];
  submit && typeof submit == 'boolean' && emits('close', submit);
}

//开放方法
defineExpose({ _open, _close });
</script>

<style scoped></style>