<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="退货原因" prop="returnReasonId">
              <el-select v-model="queryParams.returnReasonId" placeholder="请选择退货原因" clearable>
                <el-option v-for="reason in returnReasonList" :key="reason.id" :label="reason.returnReasonName" :value="reason.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态" prop="returnStatus">
              <el-select v-model="queryParams.returnStatus" placeholder="请选择订单状态" clearable>
                <el-option v-for="dict in return_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="提交时间" prop="dateRange">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="19"> 退货单信息列表 </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain>关闭订单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain>删除订单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain>导出订单</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="orderReturnList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单时间" align="center" prop="createTime" width="180" :resizable="false">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售后单号" align="center" prop="returnNo" :resizable="false" />
        <el-table-column label="售后类型" align="center" prop="serviceType" :resizable="false">
          <template #default="scope">
            <dict-tag :options="return_type" :value="scope.row.serviceType" />
          </template>
        </el-table-column>
        <el-table-column label="客户编号" align="center" prop="customerNo" :resizable="false" />
        <el-table-column label="客户姓名" align="center" prop="customerName" :resizable="false" />
        <el-table-column label="售后金额" align="center" prop="afterSaleAmount" :resizable="false" />
        <el-table-column label="订单状态" align="center" prop="returnStatus" :resizable="false">
          <template #default="scope">
            <dict-tag :options="return_order_status" :value="scope.row.returnStatus" />
          </template>
        </el-table-column>
        <el-table-column label="退货原因" align="center" prop="returnReason" :resizable="false" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :resizable="false">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleReview(scope.row)" v-hasPermi="['order:orderReturn:edit']"
              >查看退货信息</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="OrderReturn" lang="ts">
import { listOrderReturn, getOrderReturn, delOrderReturn, addOrderReturn, updateOrderReturn } from '@/api/order/orderReturn';
import { OrderReturnVO, OrderReturnQuery, OrderReturnForm } from '@/api/order/orderReturn/types';
import { listReturnReason } from '@/api/order/returnReason';
import { ReturnReasonVO } from '@/api/order/returnReason/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { return_order_status, return_type } = toRefs<any>(proxy?.useDict('return_order_status', 'return_type'));

const orderReturnList = ref<OrderReturnVO[]>([]);
const returnReasonList = ref<ReturnReasonVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const orderReturnFormRef = ref<ElFormInstance>();
const router = useRouter();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderReturnForm = {
  id: undefined,
  orderId: undefined,
  orderNo: undefined,
  serviceType: undefined,
  returnTime: undefined,
  returnNo: undefined,
  customerId: undefined,
  customerNo: undefined,
  customerName: undefined,
  afterSaleAmount: undefined,
  returnStatus: undefined,
  returnProductNum: undefined,
  processingTime: undefined,
  returnReasonId: undefined,
  returnReason: undefined,
  problemDescription: undefined,
  voucherPhoto: undefined,
  shippingFee: undefined,
  isShippingFee: undefined,
  orderAmount: undefined,
  returnAmount: undefined,
  afterSalesRemarks: undefined,
  returnMethod: undefined,
  chargebackName: undefined,
  chargebackPhone: undefined,
  chargebackPickupTime: undefined,
  chargebackProvincial: undefined,
  chargebackCity: undefined,
  chargebackCounty: undefined,
  provincialCityCounty: undefined,
  chargebackAddress: undefined,
  pushStatus: undefined,
  logisticsId: undefined,
  logisticsName: undefined,
  logisticsNo: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<OrderReturnForm, OrderReturnQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: undefined,
    orderNo: undefined,
    serviceType: undefined,
    returnNo: undefined,
    customerId: undefined,
    customerNo: undefined,
    customerName: undefined,
    returnStatus: undefined,
    processingTime: undefined,
    returnReasonId: undefined,
    returnReason: undefined,
    pushStatus: undefined,
    status: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询退货主列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrderReturn(proxy?.addDateRange(queryParams.value, dateRange.value));
  orderReturnList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  orderReturnFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderReturnVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加退货主';
};

const handleReview = (row?: OrderReturnVO) => {
  router.push({
    path: '/order-center/return-detail',
    query: { id: row.id }
  });
};

/** 提交按钮 */
const submitForm = () => {
  orderReturnFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateOrderReturn(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addOrderReturn(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrderReturnVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除退货主编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delOrderReturn(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'order/orderReturn/export',
    {
      ...queryParams.value
    },
    `orderReturn_${new Date().getTime()}.xlsx`
  );
};

// 加载退货原因列表
const loadReturnReasonList = async () => {
  try {
    const res = await listReturnReason({
      pageNum: 1,
      pageSize: 1000
    });
    returnReasonList.value = res.rows || [];
  } catch (error) {
    console.error('加载退货原因列表失败:', error);
    returnReasonList.value = [];
  }
};

onMounted(() => {
  getList();
  loadReturnReasonList();
});
</script>
