import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import QRCode from "qrcode";
import {
  getDistributorList,
  createDistributor,
  updateDistributor,
  activateDistributor,
  deactivateDistributor,
  deleteDistributor,
  generateQrcode
} from "@/api/distribution";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { onMounted, reactive, ref, toRaw, h } from "vue";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElTag,
  ElSelect,
  ElOption,
  ElImageViewer
} from "element-plus";
import {
  initPagination,
  handlePageSizeChange,
  handleCurrentPageChange,
  resetPagination,
  updatePaginationData
} from "@/utils/paginationHelper";
import type { Distributor, DistributorQuery } from "./types";

interface SearchFormProps {
  code?: string;
  name?: string;
  phone?: string;
  status?: number | undefined;
}

interface DistributorFormProps {
  id?: string;
  name: string;
  phone: string;
  remark: string;
}

const statusMap: Record<number, { text: string; type: "success" | "warning" | "danger" | "info" | "primary" }> = {
  0: { text: "待激活", type: "info" },
  1: { text: "已激活", type: "success" },
  2: { text: "已停用", type: "danger" }
};

const statusOptions = [
  { value: 0, label: "待激活" },
  { value: 1, label: "已激活" },
  { value: 2, label: "已停用" }
];

export function useDistributor() {
  const form = reactive<SearchFormProps>({
    code: "",
    name: "",
    phone: "",
    status: undefined
  });
  const loading = ref(true);
  const dataList = ref<Distributor[]>([]);
  const pagination = reactive<PaginationProps>(initPagination());
  const qrcodeMap = reactive<Record<string, string>>({});
  const qrcodePreviewMap = reactive<Record<string, string>>({});
  const showImageViewer = ref(false);
  const currentPreviewUrl = ref<string>("");

  async function generateQrcodeForRow(row: Distributor) {
    if (!row.qrcodeContent) return "";
    if (qrcodeMap[row.id]) return qrcodeMap[row.id];
    try {
      const dataUrl = await QRCode.toDataURL(row.qrcodeContent, {
        width: 80,
        margin: 1,
        color: { dark: "#000000", light: "#ffffff" }
      });
      qrcodeMap[row.id] = dataUrl;
      return dataUrl;
    } catch {
      return "";
    }
  }

  async function generateQrcodePreview(row: Distributor) {
    if (!row.qrcodeContent) return "";
    if (qrcodePreviewMap[row.id]) return qrcodePreviewMap[row.id];
    try {
      const dataUrl = await QRCode.toDataURL(row.qrcodeContent, {
        width: 400,
        margin: 2,
        color: { dark: "#000000", light: "#ffffff" }
      });
      qrcodePreviewMap[row.id] = dataUrl;
      return dataUrl;
    } catch {
      return "";
    }
  }

  function handlePreviewQrcode(row: Distributor) {
    if (!row.qrcodeContent) return;
    const previewUrl = qrcodePreviewMap[row.id];
    if (previewUrl) {
      currentPreviewUrl.value = previewUrl;
      showImageViewer.value = true;
    } else {
      generateQrcodePreview(row).then(url => {
        if (url) {
          currentPreviewUrl.value = url;
          showImageViewer.value = true;
        }
      });
    }
  }

  const columns = [
    {
      label: "分销员编码",
      prop: "code",
      minWidth: 120
    },
    {
      label: "姓名",
      prop: "name",
      minWidth: 100
    },
    {
      label: "手机号",
      prop: "phone",
      minWidth: 130
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" as const };
        return <ElTag type={item.type as "success" | "warning" | "danger" | "info" | "primary"}>{item.text}</ElTag>;
      }
    },
    {
      label: "二维码",
      prop: "qrcodeContent",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        if (!row.qrcodeContent) {
          return <span style="color: var(--el-text-color-placeholder)">未生成</span>;
        }
        const qrcodeUrl = qrcodeMap[row.id];
        if (!qrcodeUrl) {
          generateQrcodeForRow(row);
          return <span style="color: var(--el-text-color-secondary)">加载中...</span>;
        }
        return (
          <img
            src={qrcodeUrl}
            style={{ width: "60px", height: "60px", cursor: "pointer", borderRadius: "4px" }}
            onClick={() => handlePreviewQrcode(row)}
            title="点击查看大图"
          />
        );
      }
    },
    {
      label: "总推荐数",
      prop: "totalReferrals",
      width: 100,
      formatter: ({ totalReferrals }) => totalReferrals || 0
    },
    {
      label: "有效推荐数",
      prop: "validReferrals",
      width: 100,
      formatter: ({ validReferrals }) => validReferrals || 0
    },
    {
      label: "佣金余额",
      prop: "commissionBalance",
      width: 120,
      formatter: ({ commissionBalance }) =>
        commissionBalance !== undefined && commissionBalance !== null
          ? `¥${commissionBalance.toFixed(2)}`
          : "¥0.00"
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "操作",
      fixed: "right",
      width: 280,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: DistributorQuery = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };

      if (form.code) searchParams.code = form.code;
      if (form.name) searchParams.name = form.name;
      if (form.phone) searchParams.phone = form.phone;
      if (form.status !== undefined && form.status !== null)
        searchParams.status = form.status;

      const res = await getDistributorList(searchParams);
      if (res && res.data) {
        dataList.value = res.data.list || [];
        updatePaginationData(pagination, res.data);
        dataList.value.forEach((row: Distributor) => {
          if (row.qrcodeContent) {
            generateQrcodeForRow(row);
            generateQrcodePreview(row);
          }
        });
      }
    } finally {
      loading.value = false;
    }
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    resetPagination(pagination, onSearch);
  }

  async function handleDelete(row) {
    const { code } = await deleteDistributor(row.id);
    if (code === 200) {
      message("删除成功", { type: "success" });
      onSearch();
    }
  }

  async function handleActivate(row) {
    const { code } = await activateDistributor(row.id);
    if (code === 200) {
      message("激活成功", { type: "success" });
      onSearch();
    }
  }

  async function handleDeactivate(row) {
    const { code } = await deactivateDistributor(row.id);
    if (code === 200) {
      message("停用成功", { type: "success" });
      onSearch();
    }
  }

  async function handleGenerateQrcode(row) {
    if (row.qrcodeContent) {
      message("该分销员已生成二维码", { type: "info" });
      return;
    }
    const { code } = await generateQrcode(row.id);
    if (code === 200) {
      message("二维码生成成功", { type: "success" });
      onSearch();
    }
  }

  function renderForm(formData: DistributorFormProps) {
    return (
      <ElForm label-width="100px" size="default">
        <ElFormItem label="姓名" required>
          <ElInput
            v-model={formData.name}
            placeholder="请输入分销员姓名"
            clearable
            maxlength={20}
            showWordLimit
          />
        </ElFormItem>
        <ElFormItem label="手机号" required>
          <ElInput
            v-model={formData.phone}
            placeholder="请输入手机号"
            clearable
            maxlength={11}
          />
        </ElFormItem>
        <ElFormItem label="备注">
          <ElInput
            v-model={formData.remark}
            type="textarea"
            rows={3}
            placeholder="请输入备注（可选）"
            maxlength={200}
            showWordLimit
          />
        </ElFormItem>
      </ElForm>
    );
  }

  function validateForm(formData: DistributorFormProps): boolean {
    if (!formData.name) {
      message("请输入分销员姓名", { type: "warning" });
      return false;
    }
    if (!formData.phone) {
      message("请输入手机号", { type: "warning" });
      return false;
    }
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(formData.phone)) {
      message("请输入正确的手机号", { type: "warning" });
      return false;
    }
    return true;
  }

  function handleCreate() {
    const formData = reactive<DistributorFormProps>({
      name: "",
      phone: "",
      remark: ""
    });

    addDialog({
      title: "新增分销员",
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      contentRenderer: () => renderForm(formData),
      beforeSure: async done => {
        if (!validateForm(formData)) return;
        try {
          const { code } = await createDistributor(toRaw(formData));
          if (code === 200) {
            message("新增成功", { type: "success" });
            done();
            onSearch();
          }
        } catch (error) {
          message("新增失败", { type: "error" });
        }
      }
    });
  }

  function handleUpdate(row) {
    const formData = reactive<DistributorFormProps>({
      id: row.id,
      name: row.name,
      phone: row.phone,
      remark: row.remark || ""
    });

    addDialog({
      title: "编辑分销员",
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      contentRenderer: () => renderForm(formData),
      beforeSure: async done => {
        if (!validateForm(formData)) return;
        try {
          const { code } = await updateDistributor(toRaw(formData));
          if (code === 200) {
            message("编辑成功", { type: "success" });
            done();
            onSearch();
          }
        } catch (error) {
          message("编辑失败", { type: "error" });
        }
      }
    });
  }

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

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

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

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    statusMap,
    statusOptions,
    onSearch,
    resetForm,
    handleCreate,
    handleUpdate,
    handleActivate,
    handleDeactivate,
    handleDelete,
    handleGenerateQrcode,
    handlePreviewQrcode,
    handleSizeChange,
    handleCurrentChange,
    showImageViewer,
    currentPreviewUrl
  };
}
