<template>
  <div class="order-evaluation-container">
    <PageTitle title="订单评价" />
    <StatusTabs v-model="activeMainTab" :tabs="mainTabs" type="line" />

    <!-- <div class="search-bar">
      <el-input v-model="queryParams.keyword" placeholder="搜索" style="width: 260px" clearable>
        <template #prefix
          ><el-icon><Search /></el-icon
        ></template>
      </el-input>
      <div style="width: 260px">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="—"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 260px"
        />
      </div>
    </div> 

    <div class="filter-bar">
      <el-tree-select
        v-model="queryParams.department"
        style="width: 160px"
        :data="deptList"
        :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
        value-key="deptId"
        placeholder="下单部门"
        check-strictly
        :render-after-expand="false"
        clearable
      >
      </el-tree-select>
      <el-select v-model="queryParams.status" placeholder="状态" style="width: 160px" clearable>
        <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
      <el-select v-model="queryParams.payType" placeholder="支付方式" style="width: 160px" clearable>
        <el-option v-for="dict in pay_method" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
    </div>-->

    <div class="order-list">
      <div v-for="(order, orderIndex) in orderList" :key="orderIndex" class="order-card">
        <div class="order-header flex-row-between">
          <div class="flex-row-start">
            <span class="order-time">{{ order.orderTime }}</span>
            <span class="order-no">订单号：{{ order.orderNo }}</span>
          </div>
          <div class="flex-row-start">
            <!-- <div class="expand-btn" @click="handleViewDetail(order)">
              <span style="margin-right: 5px; margin-bottom: 2px">订单详情</span>
              <el-icon><ArrowRight /></el-icon>
            </div> -->
            <div class="open-btn" v-if="order.products && order.products.length > 1" @click="order.expanded = !order.expanded">
              <span style="margin-right: 5px"> {{ order.expanded ? '收起' : '展开' }}</span>
              <el-icon v-if="order.expanded"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
            </div>
          </div>
        </div>
        <div class="product-list">
          <div
            v-for="(product, productIndex) in order.expanded ? order.products : order.products.slice(0, 1)"
            :key="productIndex"
            class="product-row"
          >
            <div class="product-info-cell">
              <div class="product-image">
                <el-image :src="product.image" fit="contain">
                  <template #error
                    ><div class="image-placeholder">
                      <el-icon :size="30" color="#ccc"><Picture /></el-icon></div
                  ></template>
                </el-image>
              </div>
              <div class="product-detail">
                <div class="product-name ellipsis">{{ product.name }}</div>
                <div class="product-spec">{{ product.spec1 }} | {{ product.spec2 }}</div>
                <div class="product-price">¥{{ product.price }}</div>
              </div>
              <div class="product-quantity">x{{ product.quantity }}</div>
            </div>
            <div class="amount-cell" v-if="productIndex === 0">
              <div class="amount-info">
                <span class="label">支付款：</span><span class="value highlight">¥{{ order.payAmount }}</span>
              </div>
              <div class="amount-info">
                <span class="label">{{ order.payMethod }}</span>
              </div>
            </div>
            <div class="status-cell" v-if="productIndex === 0">
              <span class="status-text success">{{ order.statusText }}</span>
            </div>
            <div class="action-cell" v-if="productIndex === 0">
              <el-button v-if="activeMainTab === '0'" type="primary" link @click="handleEvaluate(order)">评价</el-button>
              <el-button v-if="activeMainTab === '1'" type="primary" link @click="handleFollowUpEvaluate(order)">追评</el-button>
              <el-button v-if="activeMainTab === '2'" type="primary" link @click="handleViewEvaluation(order)">查看评价</el-button>
            </div>
          </div>
          <!-- 显示更多商品提示 -->
          <div v-if="!order.expanded && order.products.length > 1" class="more-products-hint">
            该订单共 {{ order.products.length }} 件商品，点击展开查看全部
          </div>
        </div>
      </div>
      <el-empty v-if="orderList.length === 0" description="暂无订单" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance, toRefs, ComponentInternalInstance, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Search, Edit, ChatDotRound, Document, ArrowRight, Picture, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { PageTitle, StatusTabs } from '@/components';
import { getOrderList, getOrderProducts, getEvalutionList } from '@/api/pc/enterprise/order';
import type { OrderMain, OrderStatusStats } from '@/api/pc/enterprise/orderTypes';
import { getDeptTree } from '@/api/pc/organization';
import { DeptInfo } from '@/api/pc/organization/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status, pay_method } = toRefs<any>(proxy?.useDict('order_status', 'pay_method'));
const router = useRouter();
const activeMainTab = ref('0');

const deptList = ref([]);

const mainTabs = [
  { key: '0', label: '待评价', icon: Edit },
  { key: '1', label: '待追评', icon: ChatDotRound },
  { key: '2', label: '已评价', icon: Document }
];

const queryParams = reactive({ keyword: '', dateRange: null, department: '', status: '', payType: '', evaluationStatus: '' });

const pendingOrders = ref([]);
const followUpOrders = ref([]);
const evaluatedOrders = ref([]);

const orderList = computed(() => {
  if (activeMainTab.value === '0') return pendingOrders.value;
  else if (activeMainTab.value === '1') return followUpOrders.value;
  else return evaluatedOrders.value;
});

// 根据订单状态获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    '0': '待支付',
    '1': '待确认',
    '2': '待发货',
    '3': '部分发货',
    '4': '发货完成',
    '5': '已完成',
    '6': '已关闭',
    '7': '已取消'
  };
  return statusMap[status] || status;
};

// 获取支付方式文本
const getPayMethodText = (payType: string) => {
  const payMethod = pay_method.value?.find((item: any) => item.value === payType);
  return payMethod ? payMethod.label : payType;
};

// 加载订单商品
const loadOrderProducts = async (orderId: number) => {
  try {
    const res = await getOrderProducts([orderId]);
    if (res.code === 200 && res.rows) {
      return res.rows.map((product: any) => ({
        id: product.id,
        productId: product.productId,
        name: product.productName || '',
        productName: product.productName || '',
        spec1: product.productUnit || '',
        spec2: product.productNo || '',
        price: product.orderPrice || 0,
        quantity: product.orderQuantity || 0,
        image: product.productImage || '',
        productImg: product.productImage || ''
      }));
    }
    return [];
  } catch (error) {
    console.error('加载订单商品失败:', error);
    return [];
  }
};

// 获取订单列表
const getorders = async () => {
  try {
    const params: any = {
      pageNum: 1,
      pageSize: 100
    };

    if (queryParams.keyword) params.orderNo = queryParams.keyword;
    if (queryParams.dateRange && queryParams.dateRange.length === 2) {
      params.params = {
        beginTime: queryParams.dateRange[0],
        endTime: queryParams.dateRange[1]
      };
    }
    if (queryParams.department) params.department = queryParams.department;
    if (queryParams.status) params.orderStatus = queryParams.status;
    if (queryParams.payType) params.payType = queryParams.payType;

    // 根据当前标签页设置评价状态
    params.evaluationStatus = activeMainTab.value;

    const res = await getEvalutionList(params);
    if (res.code === 200 && res.rows) {
      // 转换订单数据并加载商品信息
      const orders = await Promise.all(
        res.rows.map(async (order: any) => {
          const products = await loadOrderProducts(order.orderId);
          return {
            orderId: order.orderId || 0,
            orderTime: order.createTime || '',
            orderNo: order.orderNo || '',
            payAmount: order.totalAmount || 0,
            payMethod: getPayMethodText(order.payType || ''),
            statusText: getStatusText(order.orderStatus || ''),
            orderStatus: order.orderStatus || '',
            products: products,
            expanded: false, // 默认收起状态
            evaluationStatus: order.evaluationStatus || '0' // 评价状态
          };
        })
      );

      // 根据当前标签页设置对应的订单列表
      if (activeMainTab.value === '0') {
        pendingOrders.value = orders;
      } else if (activeMainTab.value === '1') {
        followUpOrders.value = orders;
      } else {
        evaluatedOrders.value = orders;
      }
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  }
};

// 监听标签页切换，重新获取数据
watch(activeMainTab, () => {
  getorders();
});

// 加载部门树
const loadDeptTree = async () => {
  try {
    const res = await getDeptTree();
    if (res.code === 200 && res.data) {
      deptList.value = res.data;

      if (Array.isArray(res.data)) {
        const treeData = proxy?.handleTree<DeptInfo>(res.data, 'deptId', 'parentId');
        deptList.value = treeData || res.data;
      } else {
        deptList.value = [];
      }
    }
  } catch (error) {
    console.error('获取部门树失败:', error);
    ElMessage.error('获取部门树失败');
  }
};

const handleViewDetail = (order: any) => {
  router.push(`/order/orderManage/detail?orderId=${order.id}`);
};
const navigateToEvaluation = (order: any, type: number) => {
  router.push({
    path: '/order/orderEvaluation/evaluation',
    query: {
      orderId: order.orderId,
      orderNo: order.orderNo,
      orderTime: order.orderTime,
      type: type
    },
    state: {
      products: JSON.stringify(order.products)
    }
  } as any);
};
const handleEvaluate = (order: any) => {
  navigateToEvaluation(order, 1);
};
const handleFollowUpEvaluate = (order: any) => {
  navigateToEvaluation(order, 2);
};
const handleViewEvaluation = (order: any) => {
  navigateToEvaluation(order, 3);
};

// 页面加载时获取订单列表
onMounted(() => {
  loadDeptTree();
  getorders();
});
</script>

<style scoped lang="scss">
.order-evaluation-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  width: 100%;
  margin-bottom: 20px;
}
.search-bar {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}
.filter-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  .filter-label {
    font-size: 14px;
    color: #666;
  }
}
.order-list {
  .order-card {
    border: 1px solid #eee;
    border-radius: 4px;
    margin-bottom: 15px;
    overflow: hidden;
    .order-header {
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 12px 15px;
      background: #f9f9f9;
      border-bottom: 1px solid #eee;
      font-size: 13px;
      color: #666;
      .open-btn {
        color: #364153;
        margin-left: 10px;
        cursor: pointer;
      }
      .expand-btn {
        color: #165dff;
        margin-left: 10px;
        cursor: pointer;
      }
      .order-time {
        color: #333;
      }
      .expand-btn {
        margin-left: auto;
        margin-right: 10px;
      }
      .detail-btn {
        margin-left: 0;
      }
    }
    .product-list {
      .product-row {
        display: flex;
        border-bottom: 1px solid #f5f5f5;
        &:last-child {
          border-bottom: none;
        }
      }
      .product-cell {
        padding: 15px;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      .product-info-cell {
        display: flex;
        flex: 1;
        padding: 15px;
        gap: 15px;
        .product-image {
          width: 80px;
          height: 80px;
          background: #f5f5f5;
          border-radius: 4px;
          overflow: hidden;
          flex-shrink: 0;
          .el-image {
            width: 100%;
            height: 100%;
          }
          .image-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
        .product-detail {
          flex: 1;
          .product-name {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
          }
          .product-spec {
            font-size: 12px;
            color: #999;
            margin-bottom: 10px;
          }
          .product-price {
            font-size: 16px;
            font-weight: bold;
            color: #e60012;
          }
        }
        .product-quantity {
          font-size: 13px;
          color: #666;
        }
      }
      .amount-cell {
        width: 200px;
        padding: 15px;
        .amount-info {
          margin-bottom: 5px;
          .label {
            font-size: 12px;
            color: #999;
          }
          .value {
            font-size: 14px;
            color: #333;
            &.highlight {
              font-size: 16px;
              font-weight: bold;
              color: #e60012;
            }
          }
        }
      }
      .status-cell {
        width: 80px;
        align-items: center;
        padding: 15px;
        .status-text {
          font-size: 13px;
          font-weight: 500;
          &.success {
            color: #e60012;
          }
        }
      }
      .action-cell {
        padding: 15px;
        width: 80px;
        align-items: center;
      }
    }
    .more-products-hint {
      padding: 10px 15px;
      background: #f5f5f5;
      font-size: 12px;
      color: #666;
      text-align: center;
      border-top: 1px solid #f0f0f0;
    }
  }
}
</style>
