<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: 150px" clearable>
        <template #prefix
          ><el-icon><Search /></el-icon
        ></template>
      </el-input>
      <el-date-picker
        v-model="queryParams.dateRange"
        type="daterange"
        range-separator="—"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px"
      />
    </div>

    <div class="filter-bar">
      <span class="filter-label">下单部门</span>
      <el-tree-select
        v-model="queryParams.department"
        style="width: 100px"
        :data="deptList"
        :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
        value-key="deptId"
        placeholder="请选择"
        check-strictly
        :render-after-expand="false"
        clearable
      >
      </el-tree-select>
      <span class="filter-label">状态</span>
      <el-select v-model="queryParams.status" placeholder="请选择" style="width: 100px" clearable>
        <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
      <span class="filter-label">支付方式</span>
      <el-select v-model="queryParams.payType" placeholder="请选择" style="width: 100px" 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">
          <span class="order-time">{{ order.orderTime }}</span>
          <span class="order-no">订单号：{{ order.orderNo }}</span>
          <el-button type="primary" link class="expand-btn" @click="order.expanded = !order.expanded"
            >{{ order.expanded ? '收起' : '展开' }} <el-icon><ArrowRight /></el-icon
          ></el-button>
          <el-button type="primary" link class="detail-btn" @click="handleViewDetail(order)"
            >订单详情 <el-icon><ArrowRight /></el-icon
          ></el-button>
        </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-cell 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">{{ 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="product-cell 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="product-cell status-cell" v-if="productIndex === 0">
              <span class="status-text success">{{ order.statusText }}</span>
            </div>
            <div class="product-cell action-cell" v-if="productIndex === 0">
              <el-button v-if="activeMainTab === '0'" type="primary" link size="small" @click="handleEvaluate(order)">评价</el-button>
              <el-button v-if="activeMainTab === '1'" type="primary" link size="small" @click="handleFollowUpEvaluate(order)">追评</el-button>
              <el-button v-if="activeMainTab === '2'" type="primary" link size="small" @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>

    <el-dialog v-model="evaluateDialogVisible" :title="evaluateDialogTitle" width="600px">
      <div class="evaluate-product">
        <div class="product-image">
          <el-image :src="currentProduct?.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-info">
          <div class="product-name">{{ currentProduct?.name }}</div>
          <div class="product-spec">{{ currentProduct?.spec1 }} {{ currentProduct?.spec2 }}</div>
        </div>
      </div>
      <el-form ref="evaluateFormRef" :model="evaluateForm" :rules="evaluateRules" label-width="80px">
        <el-form-item label="商品评分" prop="deliverGoods">
          <el-rate v-model="evaluateForm.deliverGoods" :colors="['#e60012', '#e60012', '#e60012']" />
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input v-model="evaluateForm.content" type="textarea" :rows="4" placeholder="请输入评价内容" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="5">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="evaluateDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmitEvaluate">提交评价</el-button>
      </template>
    </el-dialog>
  </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, cancelOrder, deleteOrder, getEvalutionList, addOrderEvaluation } 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 evaluateDialogVisible = ref(false);
const evaluateDialogTitle = ref('商品评价');
const evaluateFormRef = ref();
const currentOrder = ref<any>(null);
const currentProduct = ref<any>(null);

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 evaluateForm = reactive({ deliverGoods: 5, content: '', evaluationType: null });
const evaluateRules = {
  deliverGoods: [{ required: true, message: '请选择评分', trigger: 'change' }],
  content: [{ required: true, message: '请输入评价内容', trigger: 'blur' }]
};

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,
        name: product.productName || '',
        spec1: product.productUnit || '',
        spec2: product.productNo || '',
        price: product.orderPrice || 0,
        quantity: product.orderQuantity || 0,
        image: 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.beginTime = queryParams.dateRange[0];
      params.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.payableAmount || 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/${order.orderId}`);
};
const handleEvaluate = (order: any) => {
  currentOrder.value = order;
  currentProduct.value = order.products[0];
  evaluateDialogTitle.value = '商品评价';
  evaluateForm.deliverGoods = undefined;
  evaluateForm.content = '';
  evaluateForm.evaluationType = 1;
  evaluateDialogVisible.value = true;
};
const handleFollowUpEvaluate = (order: any) => {
  currentOrder.value = order;
  currentProduct.value = order.products[0];
  evaluateDialogTitle.value = '追加评价';
  evaluateForm.deliverGoods = undefined;
  evaluateForm.content = '';
  evaluateForm.evaluationType = 2;
  evaluateDialogVisible.value = true;
};
const handleViewEvaluation = (order: any) => {
  ElMessage.info('查看评价详情');
};
const handleSubmitEvaluate = async () => {
  const valid = await evaluateFormRef.value?.validate();
  if (!valid) return;

  try {
    const submitData = {
      orderId: currentOrder.value?.orderId,
      productId: currentProduct.value?.id,
      evaluationType: evaluateForm.evaluationType, // 1-评价 2-追评
      deliverGoods: evaluateForm.deliverGoods,
      content: evaluateForm.content,
      // 图片上传暂时留空，后续可以添加
      images: []
    };

    const res = await addOrderEvaluation(submitData);
    if (res.code === 200) {
      ElMessage.success('评价提交成功');
      evaluateDialogVisible.value = false;

      // 重新获取订单列表
      await getorders();

      // 如果需要手动更新本地数据（可选）
      if (activeMainTab.value === '0') {
        const index = pendingOrders.value.findIndex((o) => o.orderId === currentOrder.value.orderId);
        if (index > -1) {
          const order = pendingOrders.value.splice(index, 1)[0];
          if (evaluateForm.evaluationType === '1') {
            followUpOrders.value.push(order);
          } else {
            evaluatedOrders.value.push(order);
          }
        }
      } else if (activeMainTab.value === '1') {
        const index = followUpOrders.value.findIndex((o) => o.orderId === currentOrder.value.orderId);
        if (index > -1) {
          const order = followUpOrders.value.splice(index, 1)[0];
          evaluatedOrders.value.push(order);
        }
      }
    } else {
      ElMessage.error(res.msg || '评价提交失败');
    }
  } catch (error) {
    console.error('评价提交失败:', error);
    ElMessage.error('评价提交失败');
  }
};

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

<style scoped lang="scss">
.order-evaluation-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  width: 100%;
}
.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;
      .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 {
        flex: 1;
        flex-direction: row;
        align-items: center;
        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;
            line-height: 1.4;
          }
          .product-spec {
            font-size: 12px;
            color: #999;
            margin-bottom: 5px;
          }
          .product-price {
            font-size: 16px;
            font-weight: bold;
            color: #e60012;
          }
        }
        .product-quantity {
          font-size: 13px;
          color: #666;
        }
      }
      .amount-cell {
        width: 120px;
        border-left: 1px solid #f5f5f5;
        .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;
        border-left: 1px solid #f5f5f5;
        align-items: center;
        .status-text {
          font-size: 13px;
          font-weight: 500;
          &.success {
            color: #e60012;
          }
        }
      }
      .action-cell {
        width: 80px;
        border-left: 1px solid #f5f5f5;
        align-items: center;
      }
    }
    .more-products-hint {
      padding: 10px 15px;
      background: #f5f5f5;
      font-size: 12px;
      color: #666;
      text-align: center;
      border-top: 1px solid #f0f0f0;
    }
  }
}
.evaluate-product {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 20px;
  .product-image {
    width: 60px;
    height: 60px;
    background: #fff;
    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-info {
    .product-name {
      font-size: 14px;
      color: #333;
      margin-bottom: 5px;
    }
    .product-spec {
      font-size: 12px;
      color: #999;
    }
  }
}
</style>
