import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import {
  getOrderList,
  getOrderById,
  refundOrder
} from "@/api/order";
import { type Ref, ref, toRaw, reactive, onMounted } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElDescriptions,
  ElDescriptionsItem,
  ElTable,
  ElTableColumn,
  ElMessageBox
} from "element-plus";
import type { OrderItem, OrderSearchForm } from "./types";
import { 
  initPagination, 
  handlePageSizeChange, 
  handleCurrentPageChange, 
  resetPagination,
  updatePaginationData 
} from "@/utils/paginationHelper";

export function useOrder(tableRef: Ref) {
  const form = reactive<OrderSearchForm>({
    orderNo: "",
    deviceId: "",
    payStatus: "",
    status: "",
    startDate: "",
    endDate: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>(initPagination());

  const columns: TableColumnList = [
    {
      label: "订单编号",
      prop: "orderNo",
      minWidth: 160,
      formatter: ({ orderNo }) => orderNo || "-"
    },
    {
      label: "支付订单号",
      prop: "outTradeNo",
      minWidth: 150,
      formatter: ({ outTradeNo }) => outTradeNo || "-"
    },
    {
      label: "用户 ID",
      prop: "userId",
      minWidth: 80,
      formatter: ({ userId }) => userId || "-"
    },
    {
      label: "设备 ID",
      prop: "deviceId",
      minWidth: 120,
      formatter: ({ deviceId }) => deviceId || "-"
    },
    {
      label: "门店名称",
      prop: "shopName",
      minWidth: 120,
      formatter: ({ shopName }) => shopName || "-"
    },
    {
      label: "订单金额",
      prop: "totalAmount",
      minWidth: 90,
      formatter: ({ totalAmount }) => totalAmount ? `¥${(totalAmount / 100).toFixed(2)}` : "¥0.00"
    },
    {
      label: "实付金额",
      prop: "totalAmount",
      minWidth: 90,
      formatter: ({ totalAmount, discountAmount }) => {
        const payAmount = (totalAmount || 0) - (discountAmount || 0);
        return `¥${(payAmount / 100).toFixed(2)}`;
      }
    },
    {
      label: "优惠金额",
      prop: "discountAmount",
      minWidth: 90,
      formatter: ({ discountAmount }) => discountAmount ? `¥${(discountAmount / 100).toFixed(2)}` : "¥0.00"
    },
    {
      label: "支付方式",
      prop: "payType",
      minWidth: 90,
      cellRenderer: ({ row }) => {
        const payTypeMap: Record<string, { text: string; type: string }> = {
          "wechat": { text: "微信支付", type: "success" },
          "alipay": { text: "支付宝", type: "primary" },
          "cash": { text: "现金", type: "warning" },
          "free": { text: "免费", type: "info" }
        };
        const payType = payTypeMap[row.payType] || { text: row.payType || "-", type: "info" };
        return <el-tag type={payType.type as any} size="small">{payType.text}</el-tag>;
      }
    },
    {
      label: "支付状态",
      prop: "payStatus",
      minWidth: 85,
      cellRenderer: ({ row }) => {
        const statusMap: Record<string, { label: string; type: string }> = {
          "unpaid": { label: "待支付", type: "warning" },
          "paid": { label: "已支付", type: "success" },
          "refund": { label: "已退款", type: "danger" }
        };
        const status = statusMap[row.payStatus] || { label: "未知", type: "info" };
        return <el-tag type={status.type as any}>{status.label}</el-tag>;
      }
    },
    {
      label: "订单状态",
      prop: "status",
      minWidth: 85,
      cellRenderer: ({ row }) => {
        const statusMap: Record<number, { text: string; type: string }> = {
          0: { text: "待支付", type: "warning" },
          1: { text: "已完成", type: "success" },
          2: { text: "已取消", type: "info" },
          3: { text: "已退款", type: "danger" }
        };
        const status = statusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={status.type as any}>{status.text}</el-tag>;
      }
    },
    {
      label: "下单时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "支付时间",
      prop: "payTime",
      minWidth: 160,
      formatter: ({ payTime }) =>
        payTime ? dayjs(payTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];

  // 搜索
  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      // 只添加非空的搜索条件
      if (form.orderNo) searchParams.orderNo = form.orderNo;
      if (form.deviceId) searchParams.deviceId = form.deviceId;
      if (form.payStatus) searchParams.payStatus = form.payStatus;
      if (form.status !== "") {
        searchParams.status = parseInt(form.status as string, 10);
      }
      if (form.startDate) searchParams.startDate = form.startDate;
      if (form.endDate) searchParams.endDate = form.endDate;
      
      const { data } = await getOrderList(searchParams as {
        page?: number;
        pageSize?: number;
        orderNo?: string;
        deviceId?: string;
        payStatus?: string;
        status?: number;
        startDate?: string;
        endDate?: string;
      });
      // @ts-ignore - data 是 PageResult 结构
      dataList.value = data.list || [];
      // @ts-ignore - data 是 PageResult 结构
      pagination.total = data.total || 0;
    } catch (error) {
      console.error("获取订单列表失败:", error);
      dataList.value = [];
      pagination.total = 0;
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  // 重置表单
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    resetPagination(pagination, onSearch);
  };

  // 分页
  function handleSizeChange(val: number) {
    handlePageSizeChange(val, pagination, onSearch);
  }

  function handleCurrentChange(val: number) {
    handleCurrentPageChange(val, pagination, onSearch);
  }

  // 查看详情
  async function handleDetail(row: OrderItem) {
    try {
      const { data } = await getOrderById(row.id);
      const order = data;

      addDialog({
        title: `订单详情 - ${order.orderNo}`,
        width: "70%",
        draggable: true,
        fullscreen: deviceDetection(),
        closeOnClickModal: false,
        contentRenderer: () => (
          <div>
            <ElDescriptions column={2} border>
              <ElDescriptionsItem label="订单编号">{order.orderNo}</ElDescriptionsItem>
              <ElDescriptionsItem label="支付订单号">{order.outTradeNo || "-"}</ElDescriptionsItem>
              <ElDescriptionsItem label="用户 ID">{order.userId || "-"}</ElDescriptionsItem>
              <ElDescriptionsItem label="设备 ID">{order.deviceId || "-"}</ElDescriptionsItem>
              <ElDescriptionsItem label="门店名称">{order.shopName || "-"}</ElDescriptionsItem>
              <ElDescriptionsItem label="活动 ID">{order.activityId || "-"}</ElDescriptionsItem>
              <ElDescriptionsItem label="订单金额">
                ¥{((order.totalAmount || 0) / 100).toFixed(2)}
              </ElDescriptionsItem>
              <ElDescriptionsItem label="实付金额">
                ¥{(((order.totalAmount || 0) - (order.discountAmount || 0)) / 100).toFixed(2)}
              </ElDescriptionsItem>
              <ElDescriptionsItem label="优惠金额">
                ¥{((order.discountAmount || 0) / 100).toFixed(2)}
              </ElDescriptionsItem>
              <ElDescriptionsItem label="支付方式">
                <el-tag type={order.payType === "wechat" ? "success" : order.payType === "alipay" ? "primary" : "info"} size="small">
                  {order.payType === "wechat" ? "微信支付" : order.payType === "alipay" ? "支付宝" : order.payType === "cash" ? "现金" : order.payType === "free" ? "免费" : order.payType || "-"}
                </el-tag>
              </ElDescriptionsItem>
              <ElDescriptionsItem label="支付状态">
                <el-tag type={order.payStatus === "paid" ? "success" : order.payStatus === "refund" ? "danger" : "warning"}>
                  {order.payStatus === "paid" ? "已支付" : order.payStatus === "refund" ? "已退款" : "待支付"}
                </el-tag>
              </ElDescriptionsItem>
              <ElDescriptionsItem label="订单状态">
                <el-tag type={order.status === 1 ? "success" : order.status === 3 ? "danger" : order.status === 2 ? "info" : "warning"}>
                  {order.status === 0 ? "待支付" : order.status === 1 ? "已完成" : order.status === 2 ? "已取消" : "已退款"}
                </el-tag>
              </ElDescriptionsItem>
              <ElDescriptionsItem label="下单时间">
                {dayjs(order.createTime).format("YYYY-MM-DD HH:mm:ss")}
              </ElDescriptionsItem>
              <ElDescriptionsItem label="支付时间">
                {order.payTime ? dayjs(order.payTime).format("YYYY-MM-DD HH:mm:ss") : "-"}
              </ElDescriptionsItem>
              {order.videoUrl && (
                <ElDescriptionsItem label="支付视频" span={2}>
                  <video src={order.videoUrl} controls class="w-full max-w-md" />
                </ElDescriptionsItem>
              )}
              {order.confidence && (
                <ElDescriptionsItem label="置信度">
                  {(order.confidence * 100).toFixed(2)}%
                </ElDescriptionsItem>
              )}
            </ElDescriptions>

            <div class="mt-4">
              <div class="font-bold mb-2">订单商品</div>
              <ElTable data={order.items || []} border>
                <ElTableColumn prop="productName" label="商品名称" />
                <ElTableColumn
                  prop="price"
                  label="单价"
                  formatter={({ price }) => `¥${((price || 0) / 100).toFixed(2)}`}
                />
                <ElTableColumn prop="quantity" label="数量" />
                <ElTableColumn
                  prop="amount"
                  label="小计"
                  formatter={({ amount }) => `¥${((amount || 0) / 100).toFixed(2)}`}
                />
              </ElTable>
            </div>
          </div>
        ),
        hideFooter: true
      });
    } catch (error) {
      message("获取订单详情失败", { type: "error" });
    }
  }

  // 退款
  const refundForm = reactive({ reason: "" });

  async function handleRefund(row: OrderItem) {
    if (row.status !== 1) {
      message("只有已完成的订单才能退款", { type: "warning" });
      return;
    }

    refundForm.reason = "";

    addDialog({
      title: `订单退款 - ${row.orderNo}`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <ElForm ref={ruleFormRef} model={refundForm} label-width="80px">
          <ElFormItem
            label="退款原因"
            prop="reason"
            rules={[{ required: true, message: "请输入退款原因", trigger: "blur" }]}
          >
            <ElInput
              v-model={refundForm.reason}
              type="textarea"
              placeholder="请输入退款原因"
              rows={3}
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) return;

        try {
          const res = await refundOrder(row.id, { reason: refundForm.reason });
          if (res.code === 200) {
            message(`订单 ${row.orderNo} 退款成功`, { type: "success" });
            done();
            onSearch();
          } else {
            message(res.message || "退款失败", { type: "error" });
          }
        } catch (error) {
          message("退款失败", { type: "error" });
        }
      }
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    handleDetail,
    handleRefund,
    handleSizeChange,
    handleCurrentChange
  };
}
