<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { http } from "@/utils/http";
import { message } from "@/utils/message";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ExtDLabel, ExtDSelect } from "@/components/ExtForm";
import { formatDict } from "@/utils/dict";
import OrderDialog from "./dialog.vue";

defineOptions({
  name: "AdminOrdering"
});

const queryRef = ref();
const tableRef = ref();
const dialogRef = ref();

const state = reactive({
  formQuery: {
    orderId: "",
    mobilePhone: "",
    orderStatus: "",
    payStatus: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "消费站点", prop: "stationName", width: 140 },
      { label: "归属站点", prop: "userStationName", width: 140 },
      { label: "订单号", prop: "orderId", width: 220 },
      { label: "用户手机号", prop: "mobilePhone", width: 120 },
      { label: "设备编号", prop: "shortId", width: 100 },
      { label: "开始时间", prop: "startTime", width: 160 },
      { label: "结束时间", prop: "endTime", width: 160 },
      { label: "消费总额", prop: "amount", width: 100 },
      { label: "应收金额", prop: "amountReceivable", width: 100 },
      { label: "实收金额", prop: "amountReceived", width: 100 },
      { label: "关机方式", prop: "closeType", width: 100 },
      { label: "订单状态", prop: "orderStatus", width: 100 },
      { label: "支付状态", prop: "payStatus", width: 100 },
      { label: "发票状态", prop: "invoiceStatus", width: 100 },
      { label: "更新时间", prop: "updateTime", width: 160 }
    ]
  }
});

onMounted(() => {
  loadData();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    const queryHeight = queryRef.value?.$el?.clientHeight || 0;
    state.tableData.height = bodyHeight - queryHeight - 230;
  });
});

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  http.request("post", "/washOrder/list", { data: { ...state.formQuery, ...state.pageQuery } })
    .then((res: any) => {
      const { list, total } = res || {};
      state.tableData.data = list || [];
      state.pageQuery.total = total || 0;
    })
    .catch(() => {
      state.tableData.data = [];
      message("加载订单数据失败", { type: "error" });
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData(true);
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleSearch = () => {
  loadData(true);
};

const handleReset = () => {
  state.formQuery = {
    orderId: "",
    mobilePhone: "",
    orderStatus: "",
    payStatus: ""
  };
  loadData(true);
};

const handleView = (row: any) => {
  dialogRef.value?.open(row);
};

const handleForceSettle = (row: any) => {
  ElMessageBox.confirm(
    `确定要对订单「${row.orderId}」进行强制结算吗？此操作将强制结束该订单并释放设备。`,
    "提示",
    {
      confirmButtonText: "确定结算",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    http.request("post", `/washOrder/forceSettle/${row.orderId}`).then(() => {
      ElMessage.success("强制结算成功");
      loadData(true);
    });
  }).catch(() => {});
};

const formatMoney = (value: number) => {
  if (value === null || value === undefined) return "0.00";
  return (value / 100).toFixed(2);
};

const formatDuration = (seconds: number) => {
  if (!seconds) return "-";
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  const parts = [];
  if (hours > 0) parts.push(`${hours}时`);
  if (minutes > 0) parts.push(`${minutes}分`);
  if (secs > 0 || parts.length === 0) parts.push(`${secs}秒`);
  return parts.join("");
};

const isMoneyField = (prop: string) => {
  return ["amount", "amountReceivable", "amountReceived"].includes(prop);
};

const processDetailData = (detail: any[]) => {
  if (!detail || !Array.isArray(detail)) return [];
  return detail
    .filter((s: any) => s.amount > 0 || s.seconds > 0)
    .map((s: any) => ({
      name: formatDict("Order.feeType", s.name),
      seconds: formatDuration(s.seconds),
      price: formatMoney(s.price),
      amount: formatMoney(s.amount)
    }));
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">订单管理</span>
      </template>
      <el-form
        ref="queryRef"
        :model="state.formQuery"
        inline
        class="search-form"
      >
        <el-form-item label="订单号">
          <el-input
            v-model="state.formQuery.orderId"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="state.formQuery.mobilePhone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <ExtDSelect
            v-model="state.formQuery.orderStatus"
            type="Order.status"
            placeholder="请选择订单状态"
            @on-change="handleSearch"
          />
        </el-form-item>
        <el-form-item label="支付状态">
          <ExtDSelect
            v-model="state.formQuery.payStatus"
            type="Order.pay"
            placeholder="请选择支付状态"
            @on-change="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="useRenderIcon('ri/refresh-line')"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="tableRef"
        v-loading="state.tableData.loading"
        :data="state.tableData.data"
        :height="state.tableData.height"
        border
        stripe
      >
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
        <el-table-column type="expand" width="60">
          <template #default="{ row }">
            <div class="order-detail">
              <el-table
                v-if="row.detail && row.detail.length > 0"
                :data="processDetailData(row.detail)"
                border
                stripe
              >
                <el-table-column width="120" label="服务项目" prop="name" />
                <el-table-column width="120" label="服务时长" prop="seconds" />
                <el-table-column width="120" label="服务单价" prop="price" />
                <el-table-column width="120" label="小计金额" prop="amount" />
              </el-table>
              <div v-else class="no-detail">暂无消费详情</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="col in state.tableData.columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <template v-if="isMoneyField(col.prop)">
              ¥{{ formatMoney(row[col.prop]) }}
            </template>
            <template v-else-if="col.prop === 'orderStatus'">
              <ExtDLabel type="Order.status" :model-value="row.orderStatus" />
            </template>
            <template v-else-if="col.prop === 'payStatus'">
              <ExtDLabel type="Order.pay" :model-value="row.payStatus" />
            </template>
            <template v-else-if="col.prop === 'closeType'">
              <ExtDLabel type="Order.closeType" :model-value="row.closeType" />
            </template>
            <template v-else-if="col.prop === 'invoiceStatus'">
              <ExtDLabel type="Invoice.status" :model-value="row.invoiceStatus" />
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row)">
              详情
            </el-button>
            <el-button
              v-if="row.orderStatus === 0"
              type="danger"
              link
              size="small"
              @click="handleForceSettle(row)"
            >
              强制结算
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="state.pageQuery.pageNum"
          v-model:page-size="state.pageQuery.pageSize"
          :total="state.pageQuery.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <OrderDialog ref="dialogRef" />
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 16px;
}

.card-header { font-size: 16px; font-weight: 600; }

.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.order-detail {
  margin-left: 20px;
  padding: 10px;
}

.no-detail {
  padding: 20px;
  text-align: center;
  color: var(--el-text-color-secondary);
}
</style>
