<template>
  <div class="app-container order-detail-page" v-loading="loading">
    <div class="detail-container">
      <!-- 顶部信息块 -->
      <div class="info-blocks">
        <!-- 订单信息 -->
        <div class="info-block order-info">
          <div class="block-title">订单信息</div>
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ orderInfo.orderNo }}</span>
            <el-link type="primary" :underline="false" class="ml10" @click="copyText(orderInfo.orderNo)">复制</el-link>
          </div>
          <div class="info-item">
            <span class="label">下单时间：</span>
            <span class="value">{{ orderInfo.createTime }}</span>
          </div>
          <div class="info-item" v-if="orderInfo.payTime">
            <span class="label">支付时间：</span>
            <span class="value">{{ orderInfo.payTime }}</span>
          </div>
          <div class="info-item status-item">
            <span class="label">订单状态：</span>
            <template v-if="String(orderInfo.orderStatus) === '1'">
              <span class="status-tag success">已完成</span>
            </template>
            <template v-else-if="String(orderInfo.orderStatus) === '0'">
              <span class="status-tag warning">待付款</span>
              <span class="status-desc">（请尽快处理）</span>
              <el-link type="primary" :underline="false" class="close-link" @click="openCancelDialog">取消订单</el-link>
            </template>
            <template v-else-if="String(orderInfo.orderStatus) === '3'">
              <span class="status-tag info" style="background-color: #fbe6d5; color: #f08235;">售后中</span>
            </template>
            <template v-else>
              <span class="status-tag info">{{ String(orderInfo.orderStatus) === '2' ? '已关闭' : '未知' }}</span>
            </template>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">{{ orderInfo.payMethod }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单类型：</span>
            <span class="value">{{ orderInfo.orderType }}</span>
          </div>
          <div class="info-item">
            <span class="label">商品类型：</span>
            <span class="value">{{ orderInfo.productType }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单来源：</span>
            <span class="value">{{ orderInfo.source }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单备注：</span>
            <span class="value">{{ orderInfo.remark || '无' }}</span>
            <el-link type="primary" :underline="false" class="ml10" @click="openRemarkDialog">编辑备注</el-link>
          </div>
        </div>

        <!-- 买家信息 -->
        <div class="info-block buyer-info">
          <div class="block-title">
            买家信息
            <el-link type="primary" :underline="false" class="ml10" @click="goToStudentDetail">查看资料</el-link>
          </div>
          <div class="info-item">
            <span class="label">微信昵称：</span>
            <span class="value">{{ buyerInfo.wechatNickname || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户姓名：</span>
            <span class="value">{{ buyerInfo.userName || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户性别：</span>
            <span class="value">
              <dict-tag v-if="buyerInfo.genderCode !== undefined" :options="sys_user_sex" :value="buyerInfo.genderCode" />
              <span v-else>-</span>
            </span>
          </div>
          <div class="info-item">
            <span class="label">用户年龄：</span>
            <span class="value">{{ buyerInfo.age || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">手机号码：</span>
            <span class="value">{{ buyerInfo.phone || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户ID：</span>
            <span class="value">{{ buyerInfo.userId || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">注册时间：</span>
            <span class="value">{{ buyerInfo.registerTime || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">最近登录时间：</span>
            <span class="value">{{ buyerInfo.lastLoginTime || '-' }}</span>
          </div>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="product-block">
        <div class="block-title">商品信息</div>
        <el-table :data="productList" border style="width: 100%" header-cell-class-name="custom-header">
          <el-table-column label="商品" min-width="250">
            <template #default="scope">
              <div class="product-cell">
                <img :src="scope.row.productImg" class="p-img" />
                <el-link type="primary" :underline="false" class="p-name">{{ scope.row.productName }}</el-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价（元）" width="150">
            <template #default="scope">
              <div class="price-cell">
                <div>总价：{{ scope.row.totalPrice }}</div>
                <div>定金：{{ scope.row.deposit }}</div>
                <div>尾款：{{ scope.row.balance }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="productType" label="商品类型" width="120" align="center" />
          <el-table-column label="订单状态" width="120" align="center">
            <template #default="scope">
              <span :class="getStatusClass(scope.row.orderStatus)">{{ scope.row.orderType === '定金' ? '定金支付' : '完成' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单类型" width="150" align="center">
            <template #default="scope">
              {{ scope.row.orderType }} ({{ scope.row.deposit }})
            </template>
          </el-table-column>
          <el-table-column prop="postage" label="邮费" width="100" align="center" />
          <el-table-column prop="actualPayment" label="合计付款（元）" width="150" align="center" />
        </el-table>
      </div>
    </div>

    <!-- 取消订单确认弹窗 -->
    <el-dialog title="取消订单" v-model="cancelDialogVisible" width="500px">
      <el-form :model="cancelForm" label-width="120px" class="cancel-form mt20">
        <el-form-item label="取消订单原因：">
          <el-input 
            type="textarea" 
            v-model="cancelForm.reason" 
            placeholder="请输入取消订单原因" 
            :rows="4" 
            style="width: 250px" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: center;">
          <el-button type="primary" @click="confirmCancel" :loading="cancelLoading">确定</el-button>
          <el-button @click="cancelDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑备注弹窗 -->
    <el-dialog title="编辑订单备注" v-model="remarkDialogVisible" width="500px">
      <el-form :model="remarkForm" label-width="120px" class="cancel-form mt20">
        <el-form-item label="订单备注：">
          <el-input 
            type="textarea" 
            v-model="remarkForm.remark" 
            placeholder="请输入订单备注" 
            :rows="4" 
            style="width: 250px" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: center;">
          <el-button type="primary" @click="confirmRemark" :loading="remarkLoading">确定</el-button>
          <el-button @click="remarkDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getOrder, updateOrder } from '@/api/system/order';
import { getStudent } from '@/api/main/student';
import { OrderVO } from '@/api/system/order/types';

const route = useRoute();
const router = useRouter();
const loading = ref(false);

const { proxy } = getCurrentInstance() as any;
const { sys_user_sex } = proxy.useDict('sys_user_sex');

const orderInfo = ref<any>({});
const buyerInfo = ref<any>({});
const productList = ref<any[]>([]);

const getDetail = async () => {
  const id = route.query.id as string;
  if (!id) return;
  loading.value = true;
  try {
    const res = await getOrder(id);
    const data = res.data;
    orderInfo.value = {
      orderNo: data.orderNo,
      createTime: data.createTime,
      payTime: data.payTime,
      orderStatus: data.orderStatus,
      payMethod: '预见支付', // 后端如有支付方式字段可替换
      orderType: data.orderType === 1 ? '定金' : '全款',
      productType: data.orderType === 1 ? '岗位' : '商品',
      source: data.source || '小程序',
      remark: data.remark,
      paidAmount: data.paidAmount,
      totalAmount: data.totalAmount
    };

    buyerInfo.value = {
      wechatNickname: data.buyerName,
      userName: data.buyerName,
      gender: '-',
      genderCode: undefined,
      age: '-',
      phone: data.phone || '-',
      userId: data.buyerId,
      registerTime: '-',
      lastLoginTime: '-'
    };

    // 如果是学员订单，进一步获取学员详细资料
    if (data.buyerId && data.buyerType === 2) {
      try {
        const studentRes = await getStudent(data.buyerId);
        if (studentRes.data) {
          const s = studentRes.data;
          buyerInfo.value.userName = s.name || data.buyerName;
          buyerInfo.value.phone = s.mobile || data.phone;
          // 处理性别编码
          let gCode = s.gender;
          if (gCode === 'F') gCode = '1';
          if (gCode === 'M') gCode = '0';
          buyerInfo.value.genderCode = gCode;
          
          buyerInfo.value.age = getAgeByIdCard(s.idCardNumber);
          buyerInfo.value.registerTime = s.createTime;
          buyerInfo.value.lastLoginTime = s.loginDate || '-';
        }
      } catch (e) {
        console.error('获取学员详情失败', e);
      }
    }

    productList.value = [{
       productImg: data.productImg || 'https://via.placeholder.com/60',
       productName: data.productName || '未知商品',
       totalPrice: data.totalAmount,
       deposit: data.deposit || 0,
       balance: data.balance || 0,
       quantity: data.quantity || 1,
       productType: data.orderType === 1 ? '岗位' : '商品',
       orderStatus: data.orderStatus,
       orderType: data.orderType === 1 ? '定金' : '全款',
       postage: '0.00',
       actualPayment: data.paidAmount
    }];
  } finally {
    loading.value = false;
  }
};

const getAgeByIdCard = (idCard: string) => {
  if (!idCard || idCard.length !== 18) return '-';
  const birthYear = parseInt(idCard.substring(6, 10));
  const nowYear = new Date().getFullYear();
  return nowYear - birthYear;
};

const goToStudentDetail = () => {
  if (buyerInfo.value.userId) {
    router.push('/system/student/detail/' + buyerInfo.value.userId);
  } else {
    ElMessage.warning('用户ID不存在');
  }
};

onMounted(() => {
  getDetail();
});

const copyText = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('复制成功');
  });
};

const getStatusClass = (status: string) => {
  if (status === '1') return 'status-success';
  if (status === '0') return 'status-warning';
  return 'status-info';
};

const cancelDialogVisible = ref(false);
const cancelLoading = ref(false);
const cancelForm = ref({ reason: '' });

const remarkDialogVisible = ref(false);
const remarkLoading = ref(false);
const remarkForm = ref({ remark: '' });

const openCancelDialog = () => {
  cancelForm.value.reason = '';
  cancelDialogVisible.value = true;
};

const confirmCancel = async () => {
  const id = route.query.id as string;
  if (!id) return;
  
  cancelLoading.value = true;
  try {
    await updateOrder({
      id: id,
      orderStatus: 2, // 2: 已关闭/取消
      remark: orderInfo.value.remark ? `${orderInfo.value.remark} (取消原因: ${cancelForm.value.reason})` : `取消原因: ${cancelForm.value.reason}`
    });
    ElMessage.success('取消订单成功');
    cancelDialogVisible.value = false;
    getDetail(); // 刷新详情
  } catch (error) {
    console.error('取消订单失败', error);
  } finally {
    cancelLoading.value = false;
  }
};

const openRemarkDialog = () => {
  remarkForm.value.remark = orderInfo.value.remark || '';
  remarkDialogVisible.value = true;
};

const confirmRemark = async () => {
  const id = route.query.id as string;
  if (!id) return;

  remarkLoading.value = true;
  try {
    await updateOrder({
      id: id,
      remark: remarkForm.value.remark
    });
    ElMessage.success('修改备注成功');
    remarkDialogVisible.value = false;
    getDetail(); // 刷新详情
  } catch (error) {
    console.error('修改备注失败', error);
  } finally {
    remarkLoading.value = false;
  }
};
</script>

<style scoped lang="scss">
.order-detail-page {
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
  padding: 20px;
}

.detail-container {
  background-color: #fff;
  padding: 30px;
  border-radius: 4px;
}

.info-blocks {
  display: flex;
  margin-bottom: 40px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 40px;
}

.info-block {
  flex: 1;
  padding-right: 20px;

  &.buyer-info {
    padding-left: 200px;
  }
}

.block-title {
  font-size: 16px;
  font-weight: bold;
  color: #1d2129;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
}

.info-item {
  display: flex;
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 22px;
  
  .label {
    width: 120px;
    color: #4e5969;
  }
  
  .value {
    color: #1d2129;
  }
}

.status-item {
  align-items: center;

  .status-tag {
    padding: 2px 8px;
    border-radius: 2px;
    font-size: 13px;
    
    &.success {
      background-color: #e8f3e8;
      color: #52c41a;
      border: 1px solid #b7eb8f;
    }
    
    &.warning {
      background-color: #fffbe6;
      color: #faad14;
      border: 1px solid #ffe58f;
    }

    &.info {
      background-color: #f2f3f5;
      color: #86909c;
      border: 1px solid #e5e6eb;
    }
  }

  .status-desc {
    color: #86909c;
    margin-left: 10px;
    font-size: 13px;
  }

  .close-link {
    margin-left: 10px;
    font-size: 13px;
  }
}

.product-block {
  margin-top: 20px;
  
  .block-title {
    margin-bottom: 16px;
  }
}

.product-cell {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .p-img {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    object-fit: cover;
  }
  
  .p-name {
    font-weight: 500;
  }
}

.price-cell {
  font-size: 13px;
  color: #1d2129;
  line-height: 20px;
}

:deep(.custom-header th) {
  background-color: #f7f8fa !important;
  color: #4e5969;
  font-weight: 500;
}

.status-success { color: #52c41a; font-weight: 600; }
.status-warning { color: #faad14; font-weight: 600; }
.status-info { color: #86909c; }

.ml10 { margin-left: 10px; }
.mt20 { margin-top: 20px; }

.cancel-form {
  :deep(.el-form-item__label) {
    font-weight: 600;
    color: #1d2129;
  }
}
</style>
