<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.giftId" allowClear placeholder="请输入礼物ID" />
        <Input v-model:value="data.query.giftName" 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="handleOpenOnlineAdd" :disabled="data.loading">
          在线添加
        </Button>
        <Button type="primary" @click="handleBatchDelete" :disabled="selectedRowKeys.length === 0 || data.loading">
          {{ $t('common.batchDelete') }}
        </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" danger @click="handleDeleteConfirm(record)">{{ $t('common.delete')
          }}</Button>
        </template>
        <template v-if="column.dataIndex === 'iconUrl'">
          <img v-if="record.iconUrl" :src="record.iconUrl" :alt="record.gift_name"
            style="width: 40px; height: 40px; object-fit: cover;" />
          <span v-else></span>
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <span>{{ data.statusMap[record.status] }}</span>
        </template>
      </template>
    </Table>


    <!-- 删除确认 -->
    <DeleteConfirm ref="deleteRef"></DeleteConfirm>
    <!-- <Edit ref="editRef" @close="reload"></Edit> -->

    <!-- 在线添加弹窗 -->
    <Modal v-model:visible="data.onlineAddVisible" title="在线添加礼物关联" width="80%" :footer="null"
      @cancel="handleCloseOnlineAdd">
      <div class="online-add-modal">
        <div class="modal-header">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <span>已选择 {{ data.selectedGifts.length }} 个礼物</span>
            <Button type="primary" @click="handleBatchAdd" :disabled="data.selectedGifts.length === 0">
              批量添加选中的礼物
            </Button>
          </div>

          <!-- 查询表单 -->
          <div style="margin-bottom: 16px;">
            <Space :wrap="true" style="margin-bottom: 10px;">
              <Input v-model:value="data.onlineQuery.giftId" allowClear placeholder="请输入礼物ID" />
              <Input v-model:value="data.onlineQuery.giftName" allowClear placeholder="请输入礼物名称" />
              <InputNumber v-model:value="data.onlineQuery.giftPrice" :min="0" :precision="2" placeholder="请输入礼物价格"
                style="width: 150px;" />

              <!-- 查询按钮 -->
              <Button @click="handleOnlineQuery" :loading="data.giftListLoading" :disabled="data.giftListLoading"
                style="background-color: #0084CA;color: white">
                查询
              </Button>
              <Button @click="resetOnlineQuery" :loading="data.giftListLoading" :disabled="data.giftListLoading" danger>
                重置
              </Button>
            </Space>
          </div>
        </div>

        <Table :dataSource="data.giftList" :columns="giftListColumns" :loading="data.giftListLoading"
          :pagination="data.giftListPagination"
          :row-selection="{ selectedRowKeys: data.selectedGifts.map(g => g.gift_id), onChange: handleGiftSelect }"
          rowKey="gift_id" @change="handleGiftListTableChange">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'gift_image'">
              <img v-if="record.gift_image" :src="record.gift_image" :alt="record.gift_name"
                style="width: 40px; height: 40px; object-fit: cover;" />
              <span v-else></span>
            </template>
            <template v-else-if="column.dataIndex === 'status'">
              <span :class="record.status === 1 ? 'status-enabled' : 'status-disabled'">
                {{ record.status === 1 ? '启用' : '禁用' }}
              </span>
            </template>
          </template>
        </Table>
      </div>
    </Modal>
  </Modal>
</template>

<script setup lang="ts">
import DeleteConfirm from "#/components/myui/deleteConfirm/index.vue";
import Add from "./giftRelationAdd.vue";
import Edit from "./giftRelationEdit.vue";
import { reactive, ref } from "vue";
import { $t } from '@vben/locales';
import { Modal, Input, Table, Button, Space, message, Select, Form, FormItem, InputNumber, Checkbox } from 'ant-design-vue';
import { giftRelation, giftService } 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[]) => {
    selectedRowKeys.value = newSelectedRowKeys;
    selectedRows.value = newSelectedRows;
  }
};

// 列定义
const columns = [
  {
    title: '礼物ID',
    dataIndex: 'giftId',
    width: 120
  },
  {
    title: '礼物名称',
    dataIndex: 'giftName',
    width: 150
  },
  {
    title: '礼物单价',
    dataIndex: 'unitPrice',
    width: 100,
    //排序
    sorter: (a, b) => a.unitPrice - b.unitPrice
  },
  {
    title: '礼物图标',
    dataIndex: 'iconUrl',
    width: 120
  },
  {
    title: $t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
    width: 120
  }
];

// 礼物列表列定义
const giftListColumns = [
  {
    title: '礼物ID',
    dataIndex: 'gift_id',
    width: 100
  },
  {
    title: '礼物名称',
    dataIndex: 'gift_name',
    width: 150
  },
  {
    title: '礼物单价',
    dataIndex: 'gift_price',
    width: 100,
    //排序
    sorter: (a, b) => a.gift_price - b.gift_price
  },
  {
    title: '礼物图标',
    dataIndex: 'gift_image',
    width: 120
  }
];

const data = reactive({
  isShowModal: false,
  loading: false,
  pagination: {
    total: 0,
    current: 1,
    pageSize: 10,
    showTotal: (total, range) => `共 ${total} 条`,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100', '500'],
    showQuickJumper: true,
  },
  datas: [],
  query: {
    relationType: 'giftConfig',
    giftId: '',
    giftName: '',
  },
  columns,
  statusMap: {
    0: '禁用',
    1: '启用'
  },
  giftConfigInfo: null,
  // 在线添加相关数据
  onlineAddVisible: false,
  giftList: [],
  selectedGifts: [],
  giftListLoading: false,
  giftListPagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  // 在线添加弹窗查询参数
  onlineQuery: {
    giftId: '',
    giftName: '',
    giftPrice: null
  }
});

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

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

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

function handleOpenEdit(record) {
  editRef.value._open(record, data.giftConfigInfo);
}

// 打开在线添加弹窗
const handleOpenOnlineAdd = async () => {
  data.onlineAddVisible = true;
  data.selectedGifts = [];
  await loadGiftList();
};

// 加载礼物列表
const loadGiftList = async () => {
  data.giftListLoading = true;
  try {
    // 构建查询参数
    const queryParams = {};
    if (data.onlineQuery.giftId) {
      queryParams.gift_id = data.onlineQuery.giftId;
    }
    if (data.onlineQuery.giftName) {
      queryParams.gift_name = data.onlineQuery.giftName;
    }
    if (data.onlineQuery.giftPrice !== null && data.onlineQuery.giftPrice !== '') {
      queryParams.gift_price = data.onlineQuery.giftPrice;
    }

    const res = await giftService.getGiftList(queryParams);
    data.giftList = res.data;
  } catch (error) {
    message.error('获取礼物列表失败');
    console.error(error);
  } finally {
    data.giftListLoading = false;
  }
};

// 在线添加弹窗查询
const handleOnlineQuery = () => {
  data.giftListPagination.current = 1;
  loadGiftList();
};

// 重置在线添加弹窗查询
const resetOnlineQuery = () => {
  data.onlineQuery = {
    giftId: '',
    giftName: '',
    giftPrice: null
  };
  data.giftListPagination.current = 1;
  loadGiftList();
};

// 处理礼物选择
const handleGiftSelect = (selectedRowKeys, selectedRows) => {
  data.selectedGifts = selectedRows;
};

// 批量添加选中的礼物
const handleBatchAdd = async () => {
  if (data.selectedGifts.length === 0) {
    message.warning('请选择要添加的礼物');
    return;
  }


  const list = data.selectedGifts.map(gift => {
    return {
      relationType: data.giftConfigInfo?.relationType || 'giftConfig',
      relationCode: data.giftConfigInfo?.uuid,
      giftId: gift.gift_id,
      giftName: gift.gift_name,
      unitPrice: gift.gift_price,
      iconUrl: gift.gift_image,
      quantity: 1
    };
  });
  console.log(list);

  const results = await giftRelation.addBatch({ queries: list });
  //关闭弹窗
  data.onlineAddVisible = false;
  message.info('添加成功功');
  handleQuery();
};

// 关闭在线添加弹窗
const handleCloseOnlineAdd = () => {
  data.onlineAddVisible = false;
  data.selectedGifts = [];
};

// 处理礼物列表表格分页变化
const handleGiftListTableChange = (pagination) => {
  data.giftListPagination.current = pagination.current;
  data.giftListPagination.pageSize = pagination.pageSize;
  loadGiftList();
};

function handleDeleteConfirm(record) {
  deleteRef.value._open($t('common.deleteConfirm') + '【' + record.giftName + '】?').then(() => {
    giftRelation.removeByUid({ uuid: record.uuid }).then(res => {
      if (!res.error) {
        message.success($t('common.deleteSuccess'));
        handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
      }
    }).catch(() => {
      message.error($t('common.deleteFailed'));
    });
  });
}

function handleBatchDelete() {
  if (selectedRowKeys.value.length === 0) {
    message.warning($t('common.pleaseSelectItems'));
    return;
  }

  Modal.confirm({
    title: $t('common.deleteConfirm'),
    content: `确定要批量删除选中的礼物关联吗？`,
    onOk() {
      giftRelation.removeBatchByUid({ uids: selectedRowKeys.value }).then(res => {
        if (!res.error) {
          message.success($t('common.deleteSuccess'));
          // 重新查询并清空选中状态
          handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
          selectedRowKeys.value = [];
          selectedRows.value = [];
        }
      }).catch(() => {
        message.error($t('common.deleteFailed'));
      });
    }
  });
}

/**
 * 包装查询参数
 * @param page
 * @param filter
 * @param sorter
 */
function wrapQueryParam(page, filter, sorter) {
  let { current, pageSize } = { ...data.pagination, ...(page || {}) };
  let param = {
    pageNum: current,
    pageSize: pageSize,
    relationCode: data.giftConfigInfo?.uuid
  };
  //查询
  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 = {
    relationType: 'giftConfig',
    giftId: '',
    giftName: '',
  };
  // 清空选中状态
  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;
  giftRelation.queryPage(param).then(res => {
    if (res.data) {
      data.datas = res.data.list || [];
      data.pagination.current = res.data.pageNum || 1;
      data.pagination.pageSize = res.data.pageSize || 10;
      data.pagination.total = res.data.total;
    }
  }).finally(() => {
    data.loading = false;
  });
}

function _open(giftConfigInfo) {
  data.isShowModal = true;
  data.giftConfigInfo = giftConfigInfo;
  // 重置查询
  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>