<template>
  <div class="after-sale-container">
    <div class="page-title">
      <i class="title-bar"></i>
      <span>售后服务</span>
    </div>

    <div class="main-tabs">
      <div v-for="tab in mainTabs" :key="tab.key" :class="['tab-item', { active: activeMainTab === tab.key }]" @click="handleMainTabChange(tab.key)">
        <el-icon><component :is="tab.icon" /></el-icon>
        <span>{{ tab.label }}</span>
      </div>
    </div>

    <template v-if="activeMainTab !== 'complaint'">
      <div class="status-tabs">
        <div
          v-for="tab in statusTabs"
          :key="tab.key"
          :class="['status-tab', { active: activeStatusTab === tab.key }]"
          @click="handleStatusTabChange(tab.key)"
        >
          {{ tab.label }}
        </div>
      </div>

      <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>
        <div style="width: 240px">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="—"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </div>
        <el-select v-model="queryParams.status" placeholder="状态" style="width: 240px" clearable>
          <el-option label="申请中" value="0" />
          <el-option label="已退货" value="1" />
          <el-option label="已拒绝" value="2" />
          <el-option label="已完成" value="3" />
          <el-option label="已取消" value="4" />
        </el-select>
      </div>

      <div class="table-header">
        <div class="col-product">商品信息</div>
        <div class="col-time">申请时间</div>
        <div class="col-type">服务类型</div>
        <div class="col-status">服务状态</div>
        <div class="col-action">操作</div>
      </div>

      <div v-loading="loading" class="after-sale-list">
        <div v-for="(item, index) in afterSaleList" :key="index" class="after-sale-card">
          <div class="card-header">
            <span class="service-no">服务单号：{{ item.serviceNo }}</span>
            <span class="order-no">订单号：{{ item.orderNo }}</span>
          </div>
          <div class="card-content">
            <div class="col-product">
              <div class="product-image">
                <el-image :src="item.productImage" 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">{{ item.productName }}</div>
                <div class="product-quantity">x{{ item.quantity }}</div>
              </div>
            </div>
            <div class="col-time">{{ item.applyTime }}</div>
            <div class="col-type">{{ getDictLabel(service_type, item.serviceType) }}</div>
            <div class="col-status">
              <span :class="['status-text', getStatusClass(item.status)]">{{ item.statusText }}</span>
            </div>
            <div class="col-action"><el-button type="primary" link size="small" @click="handleViewDetail(item)">查看详情</el-button></div>
          </div>
        </div>
        <el-empty v-if="afterSaleList.length === 0" description="暂无售后记录" />
      </div>
      <div class="pagination-wrapper">
        <TablePagination v-model:page="pagination.page" v-model:pageSize="pagination.pageSize" :total="pagination.total" />
      </div>
    </template>

    <template v-else>
      <!-- <div class="status-tabs">
        <div
          v-for="tab in complaintStatusTabs"
          :key="tab.key"
          :class="['status-tab', { active: activeStatusTab === tab.key }]"
          @click="activeStatusTab = tab.key"
        >
          {{ tab.label }}
        </div>
      </div> -->

      <div class="search-filter-bar">
        <div class="left">
          <el-input v-model="queryParams.keyword" placeholder="搜索" style="width: 150px" clearable>
            <template #prefix
              ><el-icon><Search /></el-icon
            ></template>
          </el-input>
          <span class="filter-label">处理结果</span>
          <el-select v-model="queryParams.handleResult" placeholder="请选择" style="width: 100px" clearable>
            <el-option label="已处理" value="handled" />
            <el-option label="未处理" value="unhandled" />
          </el-select>
          <span class="filter-label">反馈类型</span>
          <el-select v-model="queryParams.feedbackType" placeholder="请选择" style="width: 100px" clearable>
            <el-option v-for="dict in complaints_suggestion_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </div>
        <div class="right">
          <el-button type="danger" @click="handleAddComplaint">新增投诉与建议</el-button>
        </div>
      </div>

      <el-table :data="complaintList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="createTime" label="提交时间" min-width="150" align="center">
          <template #default="{ row }"
            ><span>{{ parseTime(row.createTime, '{y}-{m}-{d}') }}</span></template
          >
        </el-table-column>
        <el-table-column prop="createName" label="提交人" min-width="100" align="center" />
        <el-table-column prop="feedbackType" label="反馈类型" min-width="100" align="center">
          <template #default="{ row }">
            {{ getDictLabel(complaints_suggestion_type, row.feedbackType) }}
          </template>
        </el-table-column>

        <el-table-column prop="processTime" label="处理时间" min-width="150" align="center">
          <template #default="{ row }"
            ><span>{{ parseTime(row.processTime, '{y}-{m}-{d}') }}</span></template
          >
        </el-table-column>
        <el-table-column prop="processStaff" label="处理人员" min-width="100" align="center" />
        <el-table-column prop="processResult" label="处理结果" min-width="100" align="center" />
        <el-table-column label="操作" min-width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEditComplaint(row)">修改</el-button>
            <el-button type="danger" link size="small" @click="handleDeleteComplaint(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="complaintList.length === 0" description="暂无投诉与建议" />
      <div class="pagination-wrapper">
        <TablePagination v-model:page="pagination.page" v-model:pageSize="pagination.pageSize" :total="pagination.total" />
      </div>
    </template>

    <el-dialog v-model="complaintDialogVisible" :title="complaintDialogTitle" width="500px">
      <el-form ref="complaintFormRef" :model="complaintForm" :rules="complaintRules" label-width="80px">
        <el-form-item label="反馈类型" prop="feedbackType">
          <el-select v-model="complaintForm.feedbackType" placeholder="请选择" style="width: 100%">
            <el-option v-for="dict in complaints_suggestion_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="反馈内容" prop="feedbackContent">
          <el-input v-model="complaintForm.feedbackContent" type="textarea" :rows="4" placeholder="请输入反馈内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="complaintDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmitComplaint">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="returnDialogVisible" title="查看详情" width="900px" class="return-detail-dialog">
      <div v-loading="returnLoading" class="return-detail-body">
        <div v-for="item in returnItemList" :key="item.id" class="return-product-row">
          <div class="product-left">
            <div class="product-image">
              <el-image :src="item.productImage" 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">{{ item.productName || '-' }}</div>
              <div class="product-meta">商品编号：{{ item.productNo || '-' }}</div>
              <div class="product-meta">单位：{{ item.productUnit || '-' }}</div>
            </div>
          </div>

          <div class="product-right">
            <div class="right-line">
              <span class="k">退货数量：</span><span class="v">{{ item.returnQuantity || 0 }}</span>
            </div>
            <div class="right-line">
              <span class="k">单价：</span><span class="v">¥{{ formatMoney(getItemPrice(item)) }}</span>
            </div>
            <div class="right-line">
              <span class="k">小计：</span><span class="v">¥{{ formatMoney(getItemSubtotal(item)) }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div>
          <el-button @click="returnDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Search, RefreshRight, Tools, ChatLineSquare, Picture } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PageTitle, SearchBar, TablePagination } from '@/components';
import { getOrderReturnList, getOrderReturnInfo, addOrderReturn, updateOrderReturn } from '@/api/pc/enterprise/orderReturn';
import type { OrderReturn } from '@/api/pc/enterprise/orderReturnTypes';
import {
  getComplaintsSuggestionsList,
  addComplaintsSuggestions,
  updateComplaintsSuggestions,
  deleteComplaintsSuggestions
} from '@/api/pc/valueAdded';
import { status } from 'nprogress';
import { stat } from 'fs';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { service_type, complaints_suggestion_type } = toRefs<any>(proxy?.useDict('service_type', 'complaints_suggestion_type'));

const router = useRouter();
const activeMainTab = ref('return');
const activeStatusTab = ref('all');
const complaintDialogVisible = ref(false);
const complaintDialogTitle = ref('新增投诉与建议');
const complaintFormRef = ref();
const currentComplaint = ref<any>(null);
const loading = ref(false);
const pagination = reactive({ page: 1, pageSize: 5, total: 0 });
const returnDialogVisible = ref(false);
const returnLoading = ref(false);
const returnItemList = ref<any[]>([]);

const mainTabs = [
  { key: 'return', label: '退换货', icon: RefreshRight },
  { key: 'repair', label: '返修/维修', icon: Tools },
  { key: 'complaint', label: '投诉与建议', icon: ChatLineSquare }
];

const statusTabs = [
  { key: 'all', label: '全部订单' },
  { key: '0', label: '申请中' },
  { key: '1', label: '已退货' },
  { key: '2', label: '已拒绝' },
  { key: '3', label: '已完成' },
  { key: '4', label: '已取消' }
];

const complaintStatusTabs = [
  { key: 'all', label: '全部订单' },
  { key: '0', label: '申请中' },
  { key: '1', label: '已退货' },
  { key: '2', label: '已拒绝' },
  { key: '3', label: '已完成' },
  { key: '4', label: '已取消' }
];

const queryParams = reactive({ keyword: '', dateRange: null, status: '', handleResult: '', feedbackType: '' });
const complaintForm = reactive({ id: undefined, feedbackType: '', feedbackContent: '' });
const complaintRules = {
  feedbackType: [{ required: true, message: '请选择反馈类型', trigger: 'change' }],
  feedbackContent: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }]
};

// 售后数据列表
const allAfterSaleData = ref<any[]>([]);

// 加载售后数据
const loadAfterSaleData = async () => {
  try {
    loading.value = true;
    const res = await getOrderReturnList({
      pageNum: pagination.page,
      pageSize: pagination.pageSize,
      returnStatus: activeStatusTab.value === 'all' ? '' : activeStatusTab.value,
      serviceType: activeMainTab.value === 'return' ? '1' : activeMainTab.value === 'repair' ? '3' : ''
    });

    if (res.code === 200 && res.rows) {
      // 将后端数据转换为前端展示格式
      allAfterSaleData.value = res.rows.map((item: OrderReturn) => ({
        id: item.id,
        serviceNo: item.returnNo,
        orderNo: item.orderNo,
        productImage: '',
        productName: item.orderReturnItemList?.[0]?.productName || '商品名称',
        quantity: item.returnProductNum || 1,
        applyTime: item.returnTime,
        serviceType: item.serviceType,
        status: item.returnStatus,
        statusText: getStatusText(item.returnStatus),
        type: item.serviceType === '1' ? 'return' : 'repair'
      }));
      pagination.total = res.total | 0;
    }
  } catch (error) {
    console.error('加载售后数据失败:', error);
    ElMessage.error('加载售后数据失败');
  } finally {
    loading.value = false;
  }
};

const getDictLabel = (dictOptions: any[], value: string) => {
  if (!dictOptions || !value) return value;
  const dict = dictOptions.find((item) => item.value === value);
  return dict ? dict.label : value;
};

// 获取状态文本
const getStatusText = (status?: string) => {
  const statusMap: Record<string, string> = {
    '0': '申请中',
    '1': '已退货',
    '2': '已拒绝',
    '3': '已完成',
    '4': '已取消'
  };
  return statusMap[status || ''] || status || '未知';
};

const allComplaintData = ref([]);

const afterSaleList = computed(() => {
  let list = allAfterSaleData.value.filter((item) => item.type === activeMainTab.value);
  if (activeStatusTab.value !== 'all') list = list.filter((item) => item.status === activeStatusTab.value);
  return list;
});

const complaintList = ref([]);

const handleMainTabChange = (key: string) => {
  activeMainTab.value = key;
  activeStatusTab.value = 'all';
  if (key != 'complaint') {
    loadAfterSaleData();
  } else {
    loadComplaintData();
  }
};

// 状态切换时刷新数据
const handleStatusTabChange = (key: string) => {
  activeStatusTab.value = key;
  loadAfterSaleData();
};

// 页面加载时获取数据
onMounted(() => {
  loadAfterSaleData();
});
const getStatusClass = (status: string) => {
  const map: Record<string, string> = { 0: 'warning', 1: 'success', 2: 'danger', 3: 'success', 4: 'info' };
  return map[status] || 'info';
};
const handleViewDetail = async (item: any) => {
  returnDialogVisible.value = true;
  await getOrderReturnInfo(item.id).then((res) => {
    returnItemList.value = res.data.orderReturnItemList;
  });
};

const formatMoney = (val: number | string) => {
  const num = Number(val) || 0;
  return num.toFixed(2);
};

const getItemPrice = (item: any) => {
  if (item?.returnPrice != null && item.returnPrice !== '') return Number(item.returnPrice) || 0;
  if (item?.price != null && item.price !== '') return Number(item.price) || 0;
  if (item?.orderPrice != null && item.orderPrice !== '') return Number(item.orderPrice) || 0;

  const qty = Number(item?.returnQuantity) || 0;
  const total = Number(item?.totalAmount) || 0;
  if (!qty) return 0;
  return total / qty;
};

const getItemSubtotal = (item: any) => {
  if (item?.totalAmount != null && item.totalAmount !== '') return Number(item.totalAmount) || 0;
  const qty = Number(item?.returnQuantity) || 0;
  return getItemPrice(item) * qty;
};
const handleAddComplaint = () => {
  currentComplaint.value = null;
  complaintDialogTitle.value = '新增投诉与建议';
  complaintForm.feedbackType = '';
  complaintForm.feedbackContent = '';
  complaintDialogVisible.value = true;
};
const handleEditComplaint = (row: any) => {
  currentComplaint.value = row;
  complaintDialogTitle.value = '修改投诉与建议';
  complaintForm.id = row.id;
  complaintForm.feedbackType = row.feedbackType;
  complaintForm.feedbackContent = row.feedbackContent || '';
  complaintDialogVisible.value = true;
};
const handleDeleteComplaint = (row: any) => {
  ElMessageBox.confirm('确定要删除该记录吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(async () => {
    try {
      await deleteComplaintsSuggestions([row.id]);
      ElMessage.success('删除成功');
      loadComplaintData();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

const handleSubmitComplaint = async () => {
  const valid = await complaintFormRef.value?.validate();
  if (!valid) return;
  if (complaintForm.id) {
    await updateComplaintsSuggestions(complaintForm);
    ElMessage.success('修改成功');
  } else {
    await addComplaintsSuggestions(complaintForm);
    ElMessage.success('提交成功');
  }
  loadComplaintData();
  complaintDialogVisible.value = false;
};

const loadComplaintData = async () => {
  const params: any = { pageNum: pagination.page, pageSize: pagination.pageSize };
  const res = await getComplaintsSuggestionsList(params);
  if (res.code === 200 && res.rows) {
    complaintList.value = res.rows;
    pagination.total = res.total || 0;
  }
};
</script>

<style scoped lang="scss">
.after-sale-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  width: 100%;
}
.page-title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}
.title-bar {
  display: inline-block;
  width: 3px;
  height: 16px;
  background: #e60012;
  border-radius: 2px;
}
.main-tabs {
  display: flex;
  gap: 30px;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
  .tab-item {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 12px 0;
    cursor: pointer;
    color: #666;
    font-size: 14px;
    border-bottom: 2px solid transparent;
    margin-bottom: -1px;
    &:hover,
    &.active {
      color: #333;
    }
    &.active {
      border-bottom-color: #e60012;
    }
  }
}

.return-detail-dialog {
  .return-detail-body {
    border: 1px solid #eee;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
  }

  .return-product-row {
    display: flex;
    justify-content: space-between;
    gap: 20px;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;

    &:nth-child(odd) {
      background: #f7fafc;
    }

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

  .product-left {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 14px;
    min-width: 0;
  }

  .product-image {
    width: 60px;
    height: 60px;
    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-info {
    min-width: 0;
  }

  .product-name {
    font-size: 14px;
    color: #333;
    line-height: 1.4;
    margin-bottom: 6px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .product-meta {
    font-size: 12px;
    color: #999;
    line-height: 1.6;
  }

  .product-right {
    width: 160px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 6px;
    color: #333;
    font-size: 12px;
  }

  .right-line {
    display: flex;
    justify-content: flex-start;
    gap: 6px;
    .k {
      color: #666;
    }
    .v {
      color: #333;
    }
  }
}
.status-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  .status-tab {
    padding: 6px 18px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 13px;
    color: #666;
    background: #f5f5f5;
    transition: all 0.2s;
    &:hover {
      color: #e60012;
    }
    &.active {
      background: #e60012;
      color: #fff;
    }
  }
}
.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;
  }
}
.search-filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  .left {
    display: flex;
    align-items: center;
    gap: 10px;
    .filter-label {
      font-size: 14px;
      color: #666;
      margin-left: 10px;
    }
  }
}
.table-header {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background: #f9f9f9;
  border: 1px solid #eee;
  border-bottom: none;
  font-size: 13px;
  color: #666;
  .col-product {
    flex: 1;
  }
  .col-time {
    width: 150px;
    text-align: center;
  }
  .col-type {
    width: 100px;
    text-align: center;
  }
  .col-status {
    width: 100px;
    text-align: center;
  }
  .col-action {
    width: 100px;
    text-align: center;
  }
}
.after-sale-list {
  .after-sale-card {
    border: 1px solid #eee;
    margin-bottom: -1px;
    .card-header {
      display: flex;
      align-items: center;
      gap: 20px;
      padding: 10px 15px;
      background: #fafafa;
      border-bottom: 1px solid #eee;
      font-size: 13px;
      color: #333;
    }
    .card-content {
      display: flex;
      align-items: center;
      padding: 15px;
      .col-product {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 12px;
        .product-image {
          width: 70px;
          height: 70px;
          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-info {
          .product-name {
            font-size: 13px;
            color: #333;
            line-height: 1.4;
            margin-bottom: 5px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          .product-quantity {
            font-size: 12px;
            color: #666;
          }
        }
      }
      .col-time {
        width: 150px;
        text-align: center;
        font-size: 13px;
        color: #666;
      }
      .col-type {
        width: 100px;
        text-align: center;
        font-size: 13px;
        color: #666;
      }
      .col-status {
        width: 100px;
        text-align: center;
        .status-text {
          font-size: 13px;
          &.success {
            color: #e60012;
          }
          &.warning {
            color: #e6a23c;
          }
          &.danger {
            color: #f56c6c;
          }
          &.info {
            color: #909399;
          }
        }
      }
      .col-action {
        width: 100px;
        text-align: center;
      }
    }
  }
}
</style>
