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 { getUserList, updateUserStatus, updateUserCreditScore } from "@/api/user";
import { type Ref, ref, toRaw, reactive, onMounted } from "vue";
import { ElForm, ElFormItem, ElInput, ElInputNumber, ElMessageBox } from "element-plus";
import type { CustomerItem, CustomerSearchForm } from "./types";

export function useCustomer(tableRef: Ref) {
  const form = reactive<CustomerSearchForm>({
    phone: "",
    nickname: "",
    status: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "客户ID",
      prop: "id",
      width: 80
    },
    {
      label: "手机号",
      prop: "phone",
      minWidth: 120
    },
    {
      label: "消费标签",
      prop: "userTagLabel",
      minWidth: 90,
      cellRenderer: ({ row }) => {
        if (!row.userTagLabel) return <span>-</span>;
        const tagMap: Record<string, { type: string; label: string }> = {
          "new": { type: "success", label: "新用户" },
          "regular": { type: "", label: "老用户" },
          "frequent": { type: "warning", label: "常客" }
        };
        const tag = tagMap[row.userTag] || { type: "info", label: row.userTagLabel };
        return <el-tag type={tag.type as any} size="small">{tag.label}</el-tag>;
      }
    },
    {
      label: "订单数",
      prop: "totalOrders",
      minWidth: 80,
      formatter: ({ totalOrders }) => totalOrders ?? 0
    },
    {
      label: "消费金额",
      prop: "totalSpent",
      minWidth: 100,
      formatter: ({ totalSpent }) => totalSpent != null ? `¥${Number(totalSpent).toFixed(2)}` : "¥0.00"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <el-tag type={row.status === 1 ? "success" : "danger"}>
          {row.status === 1 ? "正常" : "禁用"}
        </el-tag>
      )
    },
    {
      label: "注册时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  // 搜索
  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      // 只添加非空的搜索条件
      if (form.phone) searchParams.phone = form.phone;
      if (form.nickname) searchParams.nickname = form.nickname;
      if (form.status) searchParams.status = form.status;
      
      const { data } = await getUserList(searchParams);
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(data.total) || 0;
      }
    } catch (error) {
      console.error("获取客户列表失败:", error);
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

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

  // 分页
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 切换状态
  async function handleToggleStatus(row: CustomerItem) {
    const newStatus = row.status === 1 ? 0 : 1;
    const actionText = newStatus === 1 ? "启用" : "禁用";

    try {
      await ElMessageBox.confirm(`确认要${actionText}客户 ${row.nickname} 吗?`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });

      const res = await updateUserStatus(row.id, { status: newStatus });
      if (res.code === 200 || res.code === 0) {
        row.status = newStatus;
        message(`已${actionText}客户 ${row.nickname}`, { type: "success" });
      } else {
        message(res.message || `${actionText}失败`, { type: "error" });
      }
    } catch (error) {
      // 用户取消或请求失败
    }
  }

  // 修改信用分
  const creditForm = reactive({
    creditScore: 0
  });

  function handleEditCredit(row: CustomerItem) {
    creditForm.creditScore = row.creditScore;

    addDialog({
      title: `修改 ${row.nickname} 的信用分`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <ElForm ref={ruleFormRef} model={creditForm} label-width="80px">
          <ElFormItem
            label="信用分"
            prop="creditScore"
            rules={[
              { required: true, message: "请输入信用分", trigger: "blur" },
              { type: "number", min: 0, max: 100, message: "信用分范围0-100", trigger: "blur" }
            ]}
          >
            <ElInputNumber
              v-model={creditForm.creditScore}
              min={0}
              max={100}
              class="w-full!"
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) return;

        try {
          const res = await updateUserCreditScore(row.id, { creditScore: creditForm.creditScore });
          if (res.code === 200 || res.code === 0) {
            row.creditScore = creditForm.creditScore;
            message(`已修改 ${row.nickname} 的信用分为 ${creditForm.creditScore}`, { type: "success" });
            done();
          } else {
            message(res.message || "修改失败", { type: "error" });
          }
        } catch (error) {
          message("修改失败", { type: "error" });
        }
      }
    });
  }

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

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    handleToggleStatus,
    handleEditCredit,
    handleSizeChange,
    handleCurrentChange
  };
}
