<template>
  <el-container class="order-detail">
    <el-main>
      <!-- 订单轨迹 -->
      <div class="order-track sa-m-b-26">
        <h3 class="sa-m-b-20">订单轨迹</h3>
        <el-steps :active="getActiveStep()" align-center>
          <el-step
            v-for="(step, index) in state.orderDetail.status_steps"
            :key="index"
            :title="step.status_text"
            :description="step.time"
            :status="step.completed ? 'finish' : 'wait'"
          />
        </el-steps>
      </div>

      <!-- 基本信息 -->
      <div class="basic-info sa-m-b-26">
        <h3 class="sa-m-b-20">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">订单编号：</span>
              <span class="value">{{ state.orderDetail.order_sn || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">订单状态：</span>
              <span class="value">{{ state.orderDetail.status_text || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">全部金额：</span>
              <span class="value">৳{{ state.orderDetail.total_amount || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">中奖状态：</span>
              <span class="value">{{ state.orderDetail.lottery_status || '--' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="sa-m-t-12">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">用户昵称：</span>
              <span class="value">{{ state.orderDetail.user_nickname || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">支付方式：</span>
              <span class="value">{{ state.orderDetail.payment_method || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">优惠金额：</span>
              <span class="value">৳{{ state.orderDetail.discount_amount || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">奖励佣金：</span>
              <span class="value">৳{{ state.orderDetail.commission_amount || '--' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="sa-m-t-12">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">手机号码：</span>
              <span class="value">{{ state.orderDetail.mobile || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">支付金额：</span>
              <span class="value">৳{{ state.orderDetail.pay_amount || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">实付金额：</span>
              <span class="value">৳{{ state.orderDetail.actual_amount || '--' }}</span>
            </div>
          </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="action-buttons sa-m-b-26">
        <template v-if="state.orderDetail.btns">
          <el-button
            v-if="state.orderDetail.btns.includes('send')"
            type="primary"
            @click="onOpenDispatch"
            >立即发货</el-button
          >
          <el-button v-if="state.orderDetail.btns.includes('refund')" @click="onOpenRefund"
            >全部退款</el-button
          >
          <el-button v-if="state.orderDetail.btns.includes('contact_user')" @click="onContactUser"
            >联系用户</el-button
          >
          <el-button v-if="state.orderDetail.btns.includes('export_order')" @click="onExportOrder"
            >导出订单</el-button
          >
          <el-button v-if="state.orderDetail.btns.includes('close_order')" @click="onCloseOrder"
            >关闭订单</el-button
          >
        </template>
      </div>
      <!-- 商品信息 -->
      <div class="goods-content sa-m-b-16">
        <div class="sa-title sa-m-b-10">商品信息</div>
        <el-table class="sa-table" :data="state.orderDetail.items" stripe border>
          <el-table-column label="商品图片" width="100" align="center">
            <template #default="{ row }">
              <el-image
                :src="row.goods_image"
                style="width: 60px; height: 60px; border-radius: 4px"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="goods_title" min-width="200" />
          <el-table-column label="规格" prop="goods_sku_text" width="120" align="center" />
          <el-table-column label="数量" prop="goods_num" width="80" align="center" />
          <el-table-column label="单价" width="120" align="center">
            <template #default="{ row }"> ৳{{ row.goods_price || '--' }} </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 收货信息 -->
      <div class="address-content sa-m-b-16">
        <div class="sa-title sa-m-b-10">收货信息</div>
        <el-table class="sa-table" :data="[state.orderDetail.address]" stripe border>
          <el-table-column label="收件人" prop="consignee" width="120" align="center" />
          <el-table-column label="手机号" prop="mobile" width="150" align="center" />
          <el-table-column label="详细地址" prop="address" min-width="200" />
          <el-table-column label="物流公司" prop="express_company" width="120" align="center" />
          <el-table-column label="物流单号" prop="express_no" width="180" align="center" />
        </el-table>
      </div>

      <!-- 拼团信息 -->
      <div class="group-content" v-if="state.orderDetail.group_info">
        <div class="sa-title sa-m-b-10"
          >拼团信息（{{ state.orderDetail.group_info.group_type }}）</div
        >
        <el-table class="sa-table" :data="state.orderDetail.group_info.members" stripe border>
          <el-table-column label="昵称" prop="nickname" min-width="120" align="center" />
          <el-table-column label="手机号" prop="mobile" min-width="150" align="center" />
          <el-table-column label="参团订单号" prop="order_sn" min-width="180" align="center" />
          <el-table-column label="参团时间" prop="join_time" min-width="160" align="center" />
          <el-table-column label="支付时间" prop="pay_time" min-width="160" align="center" />
          <el-table-column label="奖励佣金" prop="commission" min-width="120" align="center" />
        </el-table>
      </div>
    </el-main>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import { api } from '../order.service';
  import { useModal } from '@/sheep/hooks';
  import OrderDispatch from './dispatch.vue';
  import OrderRefund from './refund.vue';

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

  const state = reactive({
    orderDetail: {}, // 订单详情
  });

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

  // 获取订单详情
  async function getOrderDetail() {
    const { error, data } = await api.order.detail(props.modal.params.id);
    if (error === 0) {
      state.orderDetail = data;
    }
  }

  // 获取激活步骤
  function getActiveStep() {
    if (!state.orderDetail.status_steps) return 0;
    return state.orderDetail.status_steps.filter((step) => step.completed).length - 1;
  }

  // 发货
  function onOpenDispatch() {
    // 检查订单数据是否完整
    if (!state.orderDetail || !state.orderDetail.items) {
      ElMessage.error('订单数据加载中，请稍后再试');
      return;
    }

    useModal(
      OrderDispatch,
      {
        title: '订单发货',
        params: {
          data: state.orderDetail,
        },
      },
      {
        success: () => {
          getOrderDetail();
        },
      },
    );
  }

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

  // 联系用户
  async function onContactUser() {
    try {
      const { error } = await api.order.contact(state.orderDetail.id);
      if (error === 0) {
        ElMessage.success('已发送联系信息');
      }
    } catch (err) {
      ElMessage.error('联系用户失败');
    }
  }

  // 导出订单
  async function onExportOrder() {
    try {
      const { error, data } = await api.order.export(state.orderDetail.id);
      if (error === 0) {
        ElMessage.success('导出成功');
        if (data.download_url) {
          window.open(data.download_url);
        }
      }
    } catch (err) {
      ElMessage.error('导出订单失败');
    }
  }

  // 关闭订单
  async function onCloseOrder() {
    try {
      const { error } = await api.order.close(state.orderDetail.id);
      if (error === 0) {
        ElMessage.success('订单已关闭');
        getOrderDetail();
      }
    } catch (err) {
      ElMessage.error('关闭订单失败');
    }
  }

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

  // 确认备注
  async function onConfirmMemo() {
    try {
      const { error } = await api.order.editMemo(state.orderDetail.id, { memo: memoForm.data });
      if (error === 0) {
        ElMessage.success('备注更新成功');
        memoForm.flag = false;
        getOrderDetail();
      }
    } catch (err) {
      ElMessage.error('备注更新失败');
    }
  }

  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 {
      .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>
