<template>
  <el-container class="order-view panel-block">
    <el-container class="order-index-main">
      <el-container>
        <el-header class="sa-header">
          <!-- 简化搜索组件 -->
          <div class="search-container">
            <sa-search-simple :searchFields="searchFields" :defaultValues="defaultSearchValues"
              v-model="currentSearchParams" @search="handleSearch" @reset="handleReset">
            </sa-search-simple>
          </div>
          <el-tabs class="sa-tabs" v-model="currentStatus" @tab-change="handleTabChange">
            <el-tab-pane :label="t('modules.order.all')" name="all"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.pendingPayment')" name="to_pay"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.paid')" name="paid"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.refunded')" name="refund"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.pendingShipment')" name="to_ship"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.shipped')" name="to_receive"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.completed')" name="completed"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.closed')" name="to_closed"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.cancelled')" name="cancellation"></el-tab-pane>
            <el-tab-pane :label="t('modules.order.recycled')" name="recycled"></el-tab-pane>
          </el-tabs>
          <div class="sa-title sa-flex sa-row-between">
            <div class="label sa-flex">
              <span class="left">{{ t('modules.order.orderList') }}</span>
            </div>
            <div>
              <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
              <el-button :loading="exportLoading" :disabled="exportLoading" @click="onExport()">{{
                t('modules.order.exportOrders')
              }}</el-button>
              <el-button v-if="currentStatus == 'to_ship'" :loading="exportLoading" :disabled="exportLoading"
                @click="onExportDelivery()">{{ t('modules.order.exportDeliveryList') }}</el-button>
            </div>
          </div>
        </el-header>
        <el-main class="sa-p-0">
          <div class="sa-table-wrap" v-loading="loading">
            <el-table height="100%" class="sa-table" :data="table.data" @selection-change="changeSelection"
              @sort-change="fieldFilter" row-key="id" stripe>
              <template #empty>
                <sa-empty></sa-empty>
              </template>
              <el-table-column type="selection" width="48" align="center"></el-table-column>
              <el-table-column sortable="custom" prop="orderId" :label="t('modules.order.orderNumber')" min-width="150">
                <template #default="scope">
                  <div class="order-info">
                    <div class="order-sn">{{ scope.row.orderId }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.goodsInfo')" min-width="300">
                <template #default="scope">
                  <div class="sa-flex" v-if="scope.row.productName">
                    <el-image :src="scope.row.image" class="goods-image" fit="cover" />
                    <div>
                      <div class="goods-title">{{ scope.row.productName }}</div>
                    </div>
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.specification')" min-width="120" align="center">
                <template #default="scope">
                  <div v-if="scope.row.sku">
                    {{ scope.row.sku || '-' }}
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.quantity')" min-width="80" align="center">
                <template #default="scope">
                  <div v-if="scope.row.payNum">
                    {{ scope.row.payNum || 0 }}
                  </div>
                  <div v-else>0</div>
                </template>
              </el-table-column>
              <el-table-column prop="realName" :label="t('modules.order.customerName')" min-width="120" align="center">
                <template #default="scope">
                  <el-link type="primary" @click="openUserDetail(scope.row.uid)">
                    {{ scope.row.realName || t('modules.order.noNickname') }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="payPrice" :label="t('modules.order.payAmount')" min-width="120" align="center">
                <template #default="scope">
                  <div>৳{{ scope.row.payPrice || 0 }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.orderStatus')" min-width="110" align="center">
                <template #default="scope">
                  <el-tag :type="getStatusType('order', scope.row.status)">
                    {{ getStatusText('order', scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.groupStatusLabel')" min-width="100" align="center">
                <template #default="scope">
                  <el-tag :type="getStatusType('pink', scope.row.storePinkStatus)">
                    {{ getStatusText('pink', scope.row.storePinkStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.deliveryInfo')" min-width="150" align="center">
                <template #default="scope">
                  <div v-if="scope.row.deliveryId">
                    <div class="delivery-name">{{ scope.row.deliveryName || t('modules.order.expressCompany') }}：{{
                      scope.row.deliveryId }}</div>
                  </div>
                  <div v-else>{{ t('modules.order.notShipped') }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.orderTime')" min-width="150" align="center">
                <template #default="scope">
                  <div>{{ scope.row.createTime }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.payTime')" min-width="150" align="center">
                <template #default="scope">
                  <div>{{ scope.row.payTime || '-' }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('common.actions')" min-width="150" fixed="right">
                <template #default="scope">
                  <div class="sa-flex">
                    <el-button v-if="scope.row.status === 5" class="is-link" type="primary"
                      @click="onSend(scope.row)">{{ t('modules.order.shipOrder') }}</el-button>
                    <el-button class="is-link" type="primary" @click="detailRow(scope.row.orderId)">{{
                      t('modules.order.viewDetail') }}</el-button>
                    <el-button v-if="scope.row.status === 1" class="is-link sa-m-l-12" type="danger"
                      @click="cancelOrder(scope.row.orderId)">
                      {{ t('modules.order.cancelOrder') }}
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <el-footer class="order-index-footer">
      <sa-view-bar>
        <template #left>
          <sa-batch-handle :batchHandleTools="batchHandleTools" :selectedLeng="table.selected.length"
            @batchHandle="batchHandle"></sa-batch-handle>
        </template>
        <template #right>
          <sa-pagination :pageData="pageData" @updateFn="getData" />
        </template>
      </sa-view-bar>
    </el-footer>
  </el-container>
</template>
<script>
export default {
  name: 'shop.admin.order.order',
};
</script>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import { api, getOrderStatusInfo, getPinkStatusInfo, getOrderStatusConfig } from '../order.service';
import { useModal, usePagination } from '@/sheep/hooks';
import OrderDispatch from './dispatch.vue';
import OrderBatchDispatch from './batchDispatch.vue';
import OrderDetail from './detail.vue';
import UserDetail from '../../user/list/detail.vue';

const { t } = useI18n();

// 设置默认每页20条
// const { pageData } = usePagination(); // 已在下方声明

// 快递公司列表配置
const deliveryCompanies = [
  { label: 'FedEx', value: 'FedEx' },
  { label: 'UPS', value: 'UPS' },
  { label: 'DHL', value: 'DHL' },
  { label: 'Pathao Courier', value: 'Pathao Courier' },
  { label: 'eDesh', value: 'eDesh' },
  { label: 'Steadfast', value: 'Steadfast' },
  { label: 'Redx', value: 'Redx' },
];

// 搜索字段配置 - 使用计算属性以支持语言切换
const searchFields = computed(() => ({
  orderId: {
    type: 'input',
    label: t('modules.order.orderNo'),
    placeholder: t('placeholders.inputOrderNo'),
    width: 200,
  },
  realName: {
    type: 'input',
    label: t('modules.order.customerName'),
    placeholder: t('placeholders.inputUserName'),
    width: 200,
  },
  userPhone: {
    type: 'input',
    label: t('modules.order.customerPhone'),
    placeholder: t('placeholders.inputPhone'),
    width: 200,
  },
  deliveryId: {
    type: 'input',
    label: t('modules.order.trackingNumber'),
    placeholder: t('placeholders.inputTrackingNumber'),
    width: 200,
  },
  deliveryName: {
    type: 'select',
    label: t('modules.order.deliveryCompany'),
    placeholder: t('form.pleaseSelect') + t('modules.order.deliveryCompany'),
    width: 180,
    options: deliveryCompanies,
  },
  timeType: {
    type: 'select',
    label: t('modules.withdraw.timeType'),
    placeholder: t('form.pleaseSelect') + t('modules.withdraw.timeType'),
    width: 150,
    options: [
      { label: t('modules.order.orderTime'), value: 'create' },
      { label: t('modules.order.payTime'), value: 'pay' },
      { label: t('modules.order.deliveryTime'), value: 'delivery' },
      { label: t('modules.order.finishTime'), value: 'finish' },
    ],
  },
  date_range: {
    type: 'daterange',
    label: t('modules.withdraw.timeRange'),
    placeholder: t('modules.withdraw.selectTimeRange'),
    width: 400,
  },
}));

// 默认搜索值
const defaultSearchValues = reactive({
  orderId: '',
  realName: '',
  userPhone: '',
  deliveryId: '',
  deliveryName: '',
  timeType: 'create', // 默认下单时间
  date_range: [],
  createTime: [],
});

// 当前状态标签 - 默认为全部
const currentStatus = ref('all');

// 状态映射 - 根据新的状态机定义
const statusMap = {
  all: null, // 全部 - 不传订单状态参数，使用null而不是空对象
  to_pay: { status: 1 }, // 待支付：订单状态为1
  cancellation: { status: 2 }, // 订单取消：订单状态为2
  paid: { status: 3 }, // 已支付：订单状态为3
  refund: { status: 4 }, // 失败已退款：订单状态为4
  to_ship: { status: 5 }, // 待发货：订单状态为5
  to_closed: { status: 6 }, // 未中奖关闭：订单状态为6
  to_receive: { status: 7 }, // 待收货：订单状态为7
  completed: { status: 8 }, // 订单完成：订单状态为8
  recycled: { status: 9 }, // 已回收：订单状态为9
};


// 标签切换处理
const handleTabChange = (status) => {
  // 立即更新tab状态
  currentStatus.value = status;

  // 直接调用getData，重置到第一页
  getData(1);
};

// 通用状态处理函数 - 使用国际化配置
const getStatusText = (type, value) => {
  const config = getOrderStatusConfig(t);
  const statusMap = {
    order: config.ORDER_STATUS,
    pink: config.PINK_STATUS,
    win: config.WIN_STATUS,
  };
  return statusMap[type]?.[value]?.text || t('common.unknown');
};

const getStatusType = (type, value) => {
  const config = getOrderStatusConfig(t);
  const statusMap = {
    order: config.ORDER_STATUS,
    pink: config.PINK_STATUS,
    win: config.WIN_STATUS,
  };
  return statusMap[type]?.[value]?.type || 'info';
};

const loading = ref(true);

// 表格
const table = reactive({
  data: [],
  order: 'desc',
  sort: 'id',
  selected: [],
});

const { pageData } = usePagination();

// 保存当前搜索条件（不包含状态参数）
const currentSearchParams = ref({});

// 处理时间范围搜索的统一函数
function processTimeRange(params) {
  // 处理旧版createTime字段
  if (params.createTime && params.createTime.length === 2) {
    params.startTime = params.createTime[0];
    params.endTime = params.createTime[1];
    delete params.createTime;
  }

  // 处理新版时间类型筛选
  if (params.date_range && params.date_range.length === 2) {
    const timeType = params.timeType || 'create';
    const [startTime, endTime] = params.date_range;

    // 时间字段映射表
    const timeFieldMap = {
      pay: { start: 'payStartTime', end: 'payEndTime' },
      delivery: { start: 'deliveryStartTime', end: 'deliveryEndTime' },
      finish: { start: 'finishStartTime', end: 'finishEndTime' },
      create: { start: 'startTime', end: 'endTime' }
    };

    const fields = timeFieldMap[timeType] || timeFieldMap.create;
    params[fields.start] = startTime;
    params[fields.end] = endTime;

    delete params.date_range;
    delete params.timeType;
  }

  return params;
}

// 获取数据
async function getData(page, searchParams = null) {
  if (page) pageData.page = page;
  loading.value = true;

  try {
    // 构建请求参数 - 优先使用传入的参数，否则使用双向绑定的搜索条件
    const finalSearchParams = searchParams !== null ? searchParams : currentSearchParams.value;

    // 根据当前状态添加筛选条件
    const statusParams = statusMap[currentStatus.value];

    // 构建请求参数 - 只有当statusParams不为null时才合并状态参数
    const requestData = {
      page: pageData.page,
      size: pageData.size,
      ...finalSearchParams,
    };

    // 只有当statusParams存在时才添加状态参数
    if (statusParams) {
      Object.assign(requestData, statusParams);
    }

    // 使用统一的时间处理函数
    processTimeRange(requestData);

    const { code, data } = await api.order.list(requestData);

    if (code == '200') {
      table.data = data.list;
      pageData.page = data.pageNum;
      pageData.total = data.total;
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    // 接口失败时也要确保loading状态正确
  } finally {
    loading.value = false;
  }
}

// 搜索处理函数
function handleSearch(searchParams) {
  // 由于使用了 v-model，currentSearchParams 会自动更新
  // 直接调用 getData，会自动使用当前的搜索条件
  getData(1);
}

// 重置搜索参数处理函数
function handleReset() {
  // 手动清空搜索参数
  currentSearchParams.value = {};
  // 传递空参数重新请求数据
  getData(1, {});
}

// table 字段排序
function fieldFilter({ prop, order }) {
  table.order = order == 'ascending' ? 'asc' : 'desc';
  table.sort = prop;
  getData();
}

// table 批量选择
function changeSelection(row) {
  table.selected = row;
}

// 导出订单/导出发货单
const exportLoading = ref(false);
async function onExport() {
  exportLoading.value = true;
  try {
    // 构建导出参数：合并搜索条件、当前tab状态和分页参数
    const statusParams = statusMap[currentStatus.value];
    const exportParams = {
      ...currentSearchParams.value,
      ...(statusParams || {}),
      // 添加分页参数，与列表保持一致
      page: pageData.page,
      size: pageData.size,
    };

    // 使用统一的时间处理函数
    processTimeRange(exportParams);

    await api.order.export(exportParams, t('modules.order.orderRecords'));
  } catch (error) {
    console.error('导出订单失败:', error);
  } finally {
    exportLoading.value = false;
  }
}

async function onExportDelivery() {
  try {
    exportLoading.value = true;

    // 构建导出发货单参数：合并搜索条件、当前tab状态和分页参数
    const exportParams = {
      ...currentSearchParams.value,
      // 添加分页参数，与列表保持一致(默认先100)
      page: pageData.page,
      size: 100 || pageData.size,
    };

    // 使用统一的时间处理函数
    processTimeRange(exportParams);

    await api.order.exportDelivery(exportParams, t('modules.order.deliveryOrders'), 'exportDelivery');
  } finally {
    exportLoading.value = false;
  }
}

const batchHandleTools = computed(() => [
  {
    operType: 'all',
    type: 'all',
    label: t('modules.order.batchDispatch'),
    buttonType: 'default',
  },
]);

function batchHandle() {
  let order_ids = [];
  table.selected.forEach((s) => {
    order_ids.push(s.id);
  });
  useModal(
    OrderBatchDispatch,
    {
      title: t('modules.order.batchDispatch'),
      order_ids,
    },
    {
      close: (result) => {
        // 如果批量发货成功，刷新当前页面数据
        getData();
      },
    },
  );
}

function detailRow(orderNo) {
  useModal(
    OrderDetail,
    {
      title: t('modules.order.orderDetail'),
      type: 'detail',
      orderNo,
    },
    {
      confirm: () => {
        getData();
      },
      close: () => {
        getData();
      },
    },
  );
}

async function cancelOrder(orderNo) {
  try {
    await ElMessageBox.confirm(t('modules.order.confirmCancelOrder'), t('common.tip'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    });

    const { code, message } = await api.order.cancel(orderNo);
    if (code == 200) {
      ElMessage.success(t('modules.order.cancelOrderSuccess'));
      getData(); // 刷新列表
    } else {
      ElMessage.error(message || t('modules.order.cancelOrderFailed'));
    }
  } catch (error) { }
}

// 打开用户详情
function openUserDetail(uid) {
  if (uid) {
    useModal(
      UserDetail,
      {
        title: t('modules.user.userDetail'),
        type: 'edit',
        id: uid,
      },
      {
        confirm: () => {
          // 用户编辑完成后可以选择是否刷新订单列表
          // getData();
        },
      },
    );
  }
}

function onSend(row) {
  useModal(
    OrderDispatch,
    {
      title: t('modules.order.orderDispatch'),
      data: row,
    },
    {
      close: (result) => {
        // 如果批量发货成功，刷新当前页面数据
        getData();
      },
    },
  );
}

onMounted(() => {
  // 页面初始化时加载数据
  getData(1);
});
</script>
<style lang="scss" scoped>
.order-view {
  .el-main {
    .sa-table-wrap {
      overflow: hidden;
      height: 100%;

      :deep() {
        .el-table__empty-text {
          margin-left: 0;
        }
      }

      .order-info {
        .order-sn {
          font-size: 14px;
          font-weight: 500;
          color: var(--sa-font);
          margin-bottom: 4px;
          line-height: 1.4;
        }

        .order-time {
          font-size: 12px;
          color: var(--sa-subfont);
          line-height: 1.2;
        }
      }

      .goods-title {
        font-size: 14px;
        font-weight: 500;
        color: var(--sa-font);
        margin-bottom: 4px;
        line-height: 1.4;
      }

      .goods-sku {
        font-size: 12px;
        color: var(--sa-subfont);
        line-height: 1.2;
      }
    }
  }

  .order-index-main {
    overflow: hidden;
  }

  .order-index-footer {
    --el-footer-height: fit-content;
  }

  .search-container {
    .range-input-group {
      display: flex;
      align-items: center;
      gap: 8px;
      width: 100%;

      .el-input {
        flex: 1;
      }

      .range-separator {
        color: var(--el-text-color-regular);
        font-size: 14px;
        white-space: nowrap;
      }
    }
  }

  // 商品信息样式
  .goods-title {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
    line-height: 1.4;
  }

  .goods-info {
    font-size: 12px;
    color: #909399;
    line-height: 1.3;
  }

  // 用户名按钮样式
  .user-name-btn {
    color: #409eff;
    text-decoration: none;
    padding: 0;
    font-size: 14px;

    &:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }

  // 物流信息样式
  .delivery-name {
    font-size: 14px;
    color: #303133;
    margin-bottom: 2px;
  }

  // 订单号样式
  .order-sn {
    font-weight: 500;
    color: #303133;
  }
}
</style>
