import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { getWithdrawalList, reviewWithdrawal, confirmTransfer } from "@/api/distribution";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { onMounted, reactive, ref } from "vue";
import type { WithdrawalQuery } from "../../utils/types";
import {
  ElForm,
  ElFormItem,
  ElInput
} from "element-plus";
import {
  initPagination,
  handlePageSizeChange,
  handleCurrentPageChange,
  resetPagination
} from "@/utils/paginationHelper";

export function useWithdrawal() {
  const form = reactive<WithdrawalQuery>({
    distributorId: undefined,
    status: undefined,
    startDate: "",
    endDate: ""
  });
  const loading = ref(true);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>(initPagination());

  const statusMap: Record<number, { text: string; type: "success" | "warning" | "danger" | "info" | "primary" }> = {
    0: { text: "待审核", type: "warning" },
    1: { text: "已通过", type: "success" },
    2: { text: "已拒绝", type: "danger" },
    3: { text: "已到账", type: "info" }
  };

  const columns: TableColumnList = [
    {
      label: "分销员名称",
      prop: "distributorName",
      minWidth: 120,
      formatter: ({ distributorName }) => distributorName || "-"
    },
    {
      label: "提现金额",
      prop: "amount",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        return row.amount ? (
          <span class="text-red-600 font-bold">¥{row.amount}</span>
        ) : (
          <span class="text-gray-400">-</span>
        );
      }
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={item.type as any} size="small">{item.text}</el-tag>;
      }
    },
    {
      label: "审核人",
      prop: "reviewerName",
      minWidth: 100,
      formatter: ({ reviewerName }) => reviewerName || "-"
    },
    {
      label: "审核时间",
      prop: "reviewTime",
      minWidth: 160,
      formatter: ({ reviewTime }) =>
        reviewTime ? dayjs(reviewTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "审核备注",
      prop: "reviewRemark",
      minWidth: 140,
      showOverflowTooltip: true,
      formatter: ({ reviewRemark }) => reviewRemark || "-"
    },
    {
      label: "到账时间",
      prop: "transferTime",
      minWidth: 160,
      formatter: ({ transferTime }) =>
        transferTime ? dayjs(transferTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

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

      if (form.distributorId) searchParams.distributorId = form.distributorId;
      if (form.status !== undefined && form.status !== null)
        searchParams.status = form.status;
      if (form.startDate) searchParams.startDate = form.startDate;
      if (form.endDate) searchParams.endDate = form.endDate;

      const { data } = await getWithdrawalList(searchParams);
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(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);
  }

  // 审核提现（通过/拒绝）
  const reviewFormRef = ref();
  const reviewFormData = reactive({
    id: 0,
    status: 1,
    remark: ""
  });

  function handleReview(row: any, status: number) {
    reviewFormData.id = row.id;
    reviewFormData.status = status;
    reviewFormData.remark = "";

    const title = status === 1 ? "通过提现申请" : "拒绝提现申请";

    addDialog({
      title,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <ElForm ref={reviewFormRef} model={reviewFormData} label-width="80px">
          <ElFormItem
            label="备注"
            prop="remark"
            rules={[
              {
                required: status === 2,
                message: "拒绝时请填写备注",
                trigger: "blur"
              }
            ]}
          >
            <ElInput
              v-model={reviewFormData.remark}
              type="textarea"
              placeholder={status === 2 ? "请填写拒绝原因" : "备注（选填）"}
              rows={3}
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async done => {
        if (status === 2) {
          const valid = await reviewFormRef.value
            ?.validate()
            .catch(() => false);
          if (!valid) return;
        }

        try {
          const res = await reviewWithdrawal({
            id: reviewFormData.id,
            status: reviewFormData.status,
            remark: reviewFormData.remark
          });
          if (res.code === 200) {
            message(
              status === 1 ? "已通过提现申请" : "已拒绝提现申请",
              { type: "success" }
            );
            done();
            onSearch();
          } else {
            message(res.message || "操作失败", { type: "error" });
          }
        } catch (error) {
          message("操作失败", { type: "error" });
        }
      }
    });
  }

  // 确认到账
  function handleConfirmTransfer(row: any) {
    addDialog({
      title: "确认到账",
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <div>
          <p>
            确认提现金额 <span class="text-red-600 font-bold">¥{row.amount}</span> 已到账？
          </p>
          <p class="text-gray-500 text-sm mt-2">
            分销员：{row.distributorName}
          </p>
        </div>
      ),
      beforeSure: async done => {
        try {
          const res = await confirmTransfer(row.id);
          if (res.code === 200) {
            message("已确认到账", { type: "success" });
            done();
            onSearch();
          } else {
            message(res.message || "操作失败", { type: "error" });
          }
        } catch (error) {
          message("操作失败", { type: "error" });
        }
      }
    });
  }

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

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    statusMap,
    onSearch,
    resetForm,
    handleReview,
    handleConfirmTransfer,
    handleSizeChange,
    handleCurrentChange
  };
}
