<template>
  <el-container class="order-detail">
    <el-main v-loading="loading" :element-loading-text="t('common.loading')">
      <!-- 操作按钮 -->
      <div class="action-buttons sa-m-b-26">
        <!-- 取消订单按钮 - 只在待支付状态显示 -->
        <el-button v-if="state.orderDetail.status === 1" type="warning" plain @click="onCancelOrder">{{
          t('modules.order.cancelOrder') }}</el-button>
        <!-- 立即发货按钮 - 待发货状态显示 -->
        <el-button type="primary" @click="onDispatch" v-if="state.orderDetail.status === 5">{{
          t('modules.order.shipOrder')
        }}</el-button>
        <!-- 全部退款按钮 - 订单状态已支付且拼团状态未成团时显示 -->
        <el-button v-if="state.orderDetail.status === 3 && state.orderDetail.storePink?.status == 1" type="danger" plain
          @click="onRefund">
          {{ t('modules.order.refund') }}
        </el-button>
      </div>
      <!-- 订单轨迹 -->
      <div class="order-track sa-m-b-46">
        <h3 class="sa-m-b-20">{{ t('modules.order.orderTrack') }}</h3>
        <el-steps :active="getActiveStep()" align-center>
          <el-step v-for="(step, index) in orderSteps" :key="index" :title="step.title" :description="step.description"
            :status="step.status" />
        </el-steps>
      </div>

      <!-- 基本信息 -->
      <div class="basic-info sa-m-b-26">
        <h3 class="sa-m-b-20">{{ t('modules.order.basicInfo') }}</h3>
        <!-- 第一列：订单号、用户名、手机号 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.orderNumber') }}：</span>
              <span class="value">{{ state.orderDetail.orderId || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.username') }}：</span>
              <span class="value">{{ state.orderDetail.realName || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.phoneNumber') }}：</span>
              <span class="value">{{ state.orderDetail.userPhone || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <!-- 预留位置 -->
          </el-col>
        </el-row>
        <!-- 第二列：订单状态、拼团状态、中奖状态 -->
        <el-row :gutter="20" class="sa-m-t-12">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.orderStatus') }}：</span>
              <el-tag :type="getStatusType('order', state.orderDetail.status)">
                {{ getStatusText('order', state.orderDetail.status) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.groupStatusLabel') }}：</span>
              <el-tag :type="getStatusType('pink', state.orderDetail.storePink?.status)">
                {{ getStatusText('pink', state.orderDetail.storePink?.status) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.winStatusLabel') }}：</span>
              <el-tag :type="getStatusType('win', state.orderDetail.storePink?.lId)">
                {{ getStatusText('win', state.orderDetail.storePink?.lId) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="6">
            <!-- 预留位置 -->
          </el-col>
        </el-row>
        <!-- 第三列：支付方式、支付金额、奖励佣金 -->
        <el-row :gutter="20" class="sa-m-t-12">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.paymentMethod') }}：</span>
              <span class="value">{{ getPayTypeTextI18n(state.orderDetail.payType) }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.paymentAmount') }}：</span>
              <span class="value">৳{{ state.orderDetail.payPrice || 0 }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">{{ t('modules.order.rewardCommission') }}：</span>
              <span class="value">৳{{ state.orderDetail.brokerage || 0 }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <!-- 预留位置 -->
          </el-col>
        </el-row>
      </div>
      <!-- 备注信息 -->
      <!-- <div class="memo-info sa-m-b-26">
        <h3 class="sa-m-b-20">备注信息</h3>
        <div class="memo sa-flex">
          <template v-if="memoForm.flag">
            <el-input class="sa-w-120 sa-m-r-12" v-model="memoForm.data" size="small" />
            <el-button class="is-link" type="primary" size="small" @click="onConfirmMemo"
              >确定</el-button
            >
            <el-button class="is-link" type="primary" size="small" @click="memoForm.flag = false"
              >取消</el-button
            >
          </template>
<template v-if="!memoForm.flag">
            <div v-if="state.orderDetail.memo" class="sa-m-r-12">
              {{ state.orderDetail.memo }}
            </div>
            <el-button
              class="is-link"
              type="primary"
              size="small"
              @click="onChangeMemoFlag(state.orderDetail.memo)"
              >{{ state.orderDetail.memo ? '修改' : '添加' }}备注</el-button
            >
          </template>
</div>
<div class="remark sa-m-t-12">
  <span class="label">买家留言：</span>
  <span class="value">{{ state.orderDetail.remark || '暂无留言' }}</span>
</div>
</div> -->
      <!-- 商品信息 -->
      <div class="goods-content sa-m-b-16">
        <div class="sa-title sa-m-b-10">{{ t('modules.order.goodsInfo') }}</div>
        <el-table class="sa-table" :data="state.orderDetail.orderInfoVO" stripe border>
          <el-table-column :label="t('modules.order.goodsImage')" width="110" align="center">
            <template #default="{ row }">
              <el-image :src="row.image" class="goods-image ml-10px" fit="cover" />
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.goodsName')" prop="productName" />
          <el-table-column :label="t('modules.order.specification')" prop="sku" align="center" />
          <el-table-column :label="t('modules.order.quantity')" prop="payNum" align="center" />
          <el-table-column :label="t('modules.order.unitPrice')" align="center">
            <template #default="{ row }"> ৳{{ row.price || '0' }} </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 收货信息 - 在待收货和订单完成状态显示 -->
      <div class="address-content sa-m-b-16" v-if="state.orderDetail.orderAddressVO?.realName">
        <div class="sa-title sa-m-b-10">{{ t('modules.order.deliveryInfo') }}</div>
        <el-table class="sa-table" :data="[state.orderDetail.orderAddressVO]" stripe border>
          <el-table-column :label="t('modules.order.recipient')" prop="realName" align="center" />
          <el-table-column :label="t('modules.order.phoneNumber')" prop="phone" align="center" />
          <el-table-column :label="t('modules.order.detailAddress')" min-width="200">
            <template #default="{ row }">
              {{ getFullAddress(row) }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.expressCompany')" align="center">
            <template #default>
              {{ state.orderDetail.deliveryName || '--' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.trackingNumber')" align="center">
            <template #default>
              {{ state.orderDetail.deliveryId || '--' }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 拼团信息 -->
      <div class="group-content" v-if="state.pinkList && state.pinkList.length > 0">
        <div class="sa-title sa-m-b-10">{{ t('modules.order.groupInfo', {
          people: state.pinkList[0]?.people ||
            t('common.unknown')
        }) }}</div>
        <el-table class="sa-table" :data="state.pinkList" stripe border>
          <el-table-column :label="t('modules.order.username')" min-width="120" align="center">
            <template #default="{ row }">
              <el-link type="primary" @click="openUserDetail(row.uid)">
                {{ row.nickname || '--' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.phoneNumber')" min-width="150" align="center">
            <template #default="{ row }">
              {{ row.userPhone || '--' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.groupOrderNumber')" min-width="180" align="center">
            <template #default="{ row }">
              <el-link type="primary" @click="openOrderDetail(row.orderId)">
                {{ row.orderId || '--' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.joinTime')" min-width="160" align="center">
            <template #default="{ row }">
              {{ row.createTime || '--' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.payTime')" min-width="160" align="center">
            <template #default="{ row }">
              {{ row.payTime || '--' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.rewardCommission')" min-width="120" align="center">
            <template #default="{ row }"> ৳{{ row.commission || 0 }} </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
  </el-container>
</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  api,
  getOrderStatusInfo,
  getPinkStatusInfo,
  getWinStatusInfo,
  getOrderStatusConfig,
} from '../order.service';
import { useModal } from '@/sheep/hooks';
import OrderDispatch from './dispatch.vue';
import OrderRefund from './refund.vue';
import UserDetail from '../../user/list/detail.vue';
import OrderDetailC from './detail.vue';

const { t } = useI18n();

const emit = defineEmits(['modalCallBack']);
const props = defineProps(['modal']);

const state = reactive({
  orderDetail: {}, // 订单详情
  pinkList: [], // 拼团信息列表
});

// loading状态
const loading = ref(false);

// 订单步骤配置
const stepConfig = computed(() => [
  { key: 'create_order', title: t('modules.order.steps.createOrder'), waitText: t('modules.order.steps.notSubmitted') },
  { key: 'payment', title: t('modules.order.steps.payment'), waitText: t('modules.order.steps.notPaid') },
  { key: 'group_start', title: t('modules.order.steps.groupStart'), waitText: t('modules.order.steps.notGrouped') },
  { key: 'platform_ship', title: t('modules.order.steps.platformShip'), waitText: t('modules.order.steps.notShipped') },
  { key: 'user_receive', title: t('modules.order.steps.userReceive'), waitText: t('modules.order.steps.notReceived') },
]);

// 计算订单步骤
const orderSteps = computed(() => {
  const trackData = state.orderDetail.orderStatusVO || [];
  const steps = [];

  stepConfig.value.forEach((config, index) => {
    const trackItem = trackData[index];

    if (trackItem) {
      // 有对应的轨迹数据，显示为已完成
      steps.push({
        title: config.title,
        description: trackItem.createTime,
        status: 'finish',
      });
    } else {
      // 没有对应的轨迹数据，显示为等待状态
      steps.push({
        title: config.title,
        description: config.waitText,
        status: 'wait',
      });
    }
  });

  return steps;
});

// 备注表单
const memoForm = reactive({
  flag: false,
  data: '',
});

// 获取订单详情
async function getOrderDetail() {
  try {
    // 支持通过id或orderNo查询订单
    const params = props.modal.params.orderNo
      ? { orderNo: props.modal.params.orderNo }
      : props.modal.params.id;

    const { code, data } = await api.order.detail(params);
    if (code == 200) {
      state.orderDetail = data;
      // 获取拼团信息

      if (data.storePink?.orderId) await getPinkList(data.storePink.orderId);
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error(t('modules.order.getOrderDetailFailed'));
  } finally {
    loading.value = false;
  }
}

// 获取拼团信息
async function getPinkList(orderNo) {
  if (!orderNo) return;
  try {
    const { code, data } = await api.order.getPinkList(orderNo);
    if (code == 200) {
      state.pinkList = data || [];
    }
  } catch (error) {
    console.error('获取拼团信息失败:', error);
    state.pinkList = [];
  }
}

// 获取激活步骤
function getActiveStep() {
  const trackData = state.orderDetail.orderStatusVO || [];
  // 返回已完成步骤的数量减1（因为 el-steps 的 active 是从0开始的索引）
  return Math.max(0, trackData.length - 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 getPayTypeTextI18n = (payType) => {
  const config = getOrderStatusConfig(t);
  return config.PAY_TYPE[payType] || payType || t('common.unknown');
};

// 拼接完整地址
function getFullAddress(addressInfo) {
  if (!addressInfo) return '--';

  const parts = [];
  if (addressInfo.province) parts.push(addressInfo.province);
  if (addressInfo.city) parts.push(addressInfo.city);
  if (addressInfo.district) parts.push(addressInfo.district);
  if (addressInfo.detail) parts.push(addressInfo.detail);
  if (addressInfo.postCode) parts.push(addressInfo.postCode);

  return parts.length > 0 ? parts.join('') : '--';
}

// 打开用户详情
function openUserDetail(uid) {
  if (!uid) {
    ElMessage.warning(t('message.userIdNotExist'));
    return;
  }

  useModal(
    UserDetail,
    {
      title: t('modules.user.userDetail'),
      id: uid,
    },
    {
      success: () => {
        // 用户详情关闭后的回调，如果需要的话
      },
    },
  );
}

// 取消订单
async function onCancelOrder() {
  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(String(state.orderDetail.orderId));
    if (code == 200) {
      ElMessage.success(t('modules.order.cancelOrderSuccess'));
      getOrderDetail(); // 刷新订单详情
    } else {
      ElMessage.error(message || t('modules.order.cancelOrderFailed'));
    }
  } catch (error) { }
}

// 立即发货
function onDispatch() {
  useModal(
    OrderDispatch,
    {
      title: t('modules.order.orderDispatch'),
      data: state.orderDetail,
    },
    {
      confirm: () => {
        getOrderDetail(); // 刷新订单详情
      },
    },
  );
}

// 全部退款
async function onRefund() {
  try {
    await ElMessageBox.confirm(t('modules.order.confirmFullRefund'), t('common.tip'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    });

    const { code } = await api.order.refund(String(state.orderDetail.orderId));
    if (code == 200) {
      ElMessage.success(t('message.refundSuccess'));
      getOrderDetail(); // 刷新订单详情
    }
  } catch (error) { }
}

// 打开订单详情
function openOrderDetail(orderId) {
  if (!orderId) {
    ElMessage.warning(t('message.orderIdNotExist'));
    return;
  }

  // 如果是当前订单，不需要打开新窗口
  if (orderId === state.orderDetail.orderId) {
    ElMessage.info(t('message.currentOrder'));
    return;
  }

  // 需要先根据订单号查找订单ID，然后打开订单详情
  // 这里假设需要调用接口根据订单号获取订单ID
  openOrderDetailByOrderId(orderId);
}

// 根据订单号打开订单详情
async function openOrderDetailByOrderId(orderId) {
  try {
    // 这里需要根据实际情况调用接口获取订单ID
    // 暂时直接使用订单号作为ID打开
    useModal(
      OrderDetailC,
      {
        title: t('modules.order.orderDetail'),
        type: 'detail',
        orderNo: orderId, // 这里可能需要转换为数据库ID
      },
      {
        success: () => {
          // 订单详情关闭后的回调
        },
      },
    );
  } catch (error) {
    console.error('打开订单详情失败:', error);
    ElMessage.error(t('modules.order.openOrderDetailFailed'));
  }
}

// 发货
function onOpenDispatch() {
  // 检查订单数据是否完整
  if (!state.orderDetail || !state.orderDetail.orderInfoVO) {
    ElMessage.error(t('modules.order.orderDataLoading'));
    return;
  }

  useModal(
    OrderDispatch,
    {
      title: t('modules.order.orderDispatch'),
      data: state.orderDetail,
    },
    {
      close: () => {
        getOrderDetail();
      },
    },
  );
}

// 退款
function onOpenRefund() {
  useModal(
    OrderRefund,
    {
      title: t('modules.order.orderRefund'),
      width: '600px',
      params: {
        id: state.orderDetail.id,
      },
    },
    {
      success: () => {
        getOrderDetail();
      },
    },
  );
}

// 联系用户
async function onContactUser() {
  try {
    const { code } = await api.order.contact(state.orderDetail.id);
    if (code == 200) {
      ElMessage.success(t('modules.order.contactSent'));
    }
  } catch (err) {
    ElMessage.error(t('modules.order.contactUserFailed'));
  }
}

// 导出订单
async function onExportOrder() {
  try {
    const { code, data } = await api.order.export(state.orderDetail.id);
    if (code == 200) {
      ElMessage.success(t('modules.order.exportSuccess'));
      if (data.download_url) {
        window.open(data.download_url);
      }
    }
  } catch (err) {
    ElMessage.error(t('modules.order.exportOrderFailed'));
  }
}

// 关闭订单
async function onCloseOrder() {
  try {
    const { code } = await api.order.close(state.orderDetail.id);
    if (code == 200) {
      ElMessage.success(t('modules.order.orderClosed'));
      getOrderDetail();
    }
  } catch (err) {
    ElMessage.error(t('modules.order.closeOrderFailed'));
  }
}

// 修改备注标志
function onChangeMemoFlag(memo) {
  memoForm.flag = true;
  memoForm.data = memo || '';
}

// 确认备注
async function onConfirmMemo() {
  try {
    const { code } = await api.order.editMemo(state.orderDetail.id, { memo: memoForm.data });
    if (code == 200) {
      ElMessage.success(t('modules.order.memoUpdateSuccess'));
      memoForm.flag = false;
      getOrderDetail();
    }
  } catch (err) {
    ElMessage.error(t('modules.order.memoUpdateFailed'));
  }
}

onMounted(() => {
  getOrderDetail();
});
</script>

<style lang="scss" scoped>
.order-detail {
  padding: 20px;

  .order-track {
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: var(--sa-title);
    }
  }

  .basic-info {
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: var(--sa-title);
    }

    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      .label {
        flex-shrink: 0;
        color: var(--sa-subfont);
        font-size: 14px;
      }

      .value {
        color: var(--sa-subtitle);
        font-size: 14px;
        font-weight: 500;
      }
    }
  }

  .action-buttons {
    display: flex;
    justify-content: end;

    .el-button {
      margin-right: 12px;
    }
  }

  .goods-content,
  .address-content,
  .group-content,
  .memo-info {
    .sa-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--sa-title);
    }

    .sa-table {
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #dcdfe6;

      :deep(.el-table) {
        border: none;
        border-radius: 0;
      }

      :deep(.el-table__header-wrapper) {
        background: var(--sa-table-header-bg, #f5f7fa);

        .el-table__header {
          background: var(--sa-table-header-bg, #f5f7fa);

          th {
            background: var(--sa-table-header-bg, #f5f7fa) !important;
            font-weight: 600;
            color: var(--sa-title, #303133);
            border-bottom: 1px solid #dcdfe6;
            border-right: 1px solid #dcdfe6;

            &:first-child {
              border-left: none;
            }

            &:last-child {
              border-right: none;
            }
          }
        }
      }

      :deep(.el-table__body-wrapper) {
        .el-table__body {
          tr {
            &:hover {
              background: #f5f7fa !important;
            }

            td {
              border-bottom: 1px solid #dcdfe6;
              border-right: 1px solid #dcdfe6;
              border-left: none;

              &:first-child {
                border-left: none;
              }

              &:last-child {
                border-right: none;
              }
            }

            &:last-child td {
              border-bottom: none;
            }
          }
        }
      }

      // 确保边框完整性
      :deep(.el-table--border) {
        border: none;

        &::after {
          display: none;
        }

        &::before {
          display: none;
        }
      }

      :deep(.el-table--border .el-table__cell) {
        border-right: 1px solid #dcdfe6;
        border-left: none;

        &:first-child {
          border-left: none;
        }

        &:last-child {
          border-right: none;
        }
      }

      // 修复表格底部和左侧边框
      :deep(.el-table__body) {
        border-left: none;
        border-bottom: none;
      }

      :deep(.el-table__header) {
        border-left: none;
      }
    }
  }

  .group-content {
    .sa-table {
      width: 100% !important;

      :deep(.el-table) {
        width: 100% !important;
      }

      :deep(.el-table__header-wrapper) {
        width: 100% !important;
      }

      :deep(.el-table__body-wrapper) {
        width: 100% !important;
      }
    }
  }

  .memo-info {
    .memo {
      margin-bottom: 12px;
    }

    .remark {
      .label {
        color: var(--sa-subfont);
        font-size: 14px;
      }

      .value {
        color: var(--sa-subtitle);
        font-size: 14px;
      }
    }
  }
}
</style>
