import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { usePublicHooks } from "@/views/system/hooks";
import type { PaginationProps } from "@pureadmin/table";
import {
  getNewProductApplyList,
  getNewProductApplyById,
  getNewProductApplyStatistics,
  submitNewProductApply,
  saveNewProductApplyDraft,
  updateNewProductApply,
  deleteNewProductApply,
  checkBarcode,
  refreshApplyStatus
} from "@/api/newProductApply";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElInputNumber,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  reactive,
  defineComponent,
  onMounted
} from "vue";

export function useNewProductApply(tableRef: Ref) {
  const form = reactive({
    productName: "",
    barcode: "",
    status: "",
    applicantId: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const statistics = ref({
    total: 0,
    pending: 0,
    approved: 0,
    rejected: 0
  });
  const { switchStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "申请编号",
      prop: "id",
      width: 90
    },
    {
      label: "商品名称",
      prop: "productName",
      minWidth: 150
    },
    {
      label: "条形码",
      prop: "barcode",
      minWidth: 130
    },
    {
      label: "分类",
      prop: "category",
      minWidth: 100
    },
    {
      label: "品牌",
      prop: "brand",
      minWidth: 100
    },
    {
      label: "售价(元)",
      prop: "price",
      minWidth: 100
    },
    {
      label: "申请人",
      prop: "applicantName",
      minWidth: 100
    },
    {
      label: "申请时间",
      prop: "applyTime",
      minWidth: 160,
      formatter: ({ applyTime }) =>
        applyTime ? dayjs(applyTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: scope => {
        const statusMap = {
          0: { text: "待提交", type: "info" },
          1: { text: "待审核", type: "warning" },
          2: { text: "已通过", type: "success" },
          3: { text: "已拒绝", type: "danger" }
        };
        const status = statusMap[scope.row.status] || { text: "未知", type: "info" };
        return <el-tag type={status.type}>{status.text}</el-tag>;
      }
    },
    {
      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.productName) searchParams.productName = form.productName;
      if (form.barcode) searchParams.barcode = form.barcode;
      if (form.status) searchParams.status = form.status;
      if (form.applicantId) searchParams.applicantId = form.applicantId;
      
      const { data } = await getNewProductApplyList(searchParams);
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(data.total) || 0;
      }
    } finally {
      loading.value = false;
    }
  }

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

  async function getStatistics() {
    const { data } = await getNewProductApplyStatistics();
    if (data) {
      statistics.value = data;
    }
  }

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

  function openDialog(title = "新增", row?: any) {
    addDialog({
      title: `${title}新品申请`,
      props: {
        formInline: {
          id: row?.id,
          productName: row?.productName ?? "",
          barcode: row?.barcode ?? "",
          category: row?.category ?? "",
          brand: row?.brand ?? "",
          specification: row?.specification ?? "",
          unit: row?.unit ?? "",
          price: row?.price ?? 0,
          costPrice: row?.costPrice ?? 0,
          images: row?.images ?? "",
          description: row?.description ?? ""
        }
      },
      width: "600px",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => h(EditForm, { ref: formRef }),
      beforeSure: async (done) => {
        const FormRef = formRef.value.getRef();
        const curData = formRef.value.getForm();
        FormRef.validate(async (valid) => {
          if (valid) {
            let res;
            if (title === "新增") {
              res = await submitNewProductApply(curData);
            } else {
              res = await updateNewProductApply(curData.id, curData);
            }
            if (res.code === 0) {
              message(`${title}成功`, { type: "success" });
              done();
              onSearch();
            }
          }
        });
      }
    });
  }

  async function handleSaveDraft(row) {
    const { code } = await saveNewProductApplyDraft(row);
    if (code === 0) {
      message("草稿保存成功", { type: "success" });
      onSearch();
    }
  }

  async function handleCheckBarcode(barcode: string) {
    const { data } = await checkBarcode(barcode);
    if (data && data.exists) {
      message("该条码已存在商品库中", { type: "warning" });
      return data.product;
    }
    return null;
  }

  // 主动刷新审核状态
  async function handleRefreshStatus(row: any) {
    try {
      const { data, code } = await refreshApplyStatus(row.id);
      if (code === 0 && data) {
        message(`状态刷新成功`, { type: "success" });
        onSearch();
        getStatistics();
      } else {
        message("刷新失败", { type: "error" });
      }
    } catch {
      message("刷新失败", { type: "error" });
    }
  }

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

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

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

  return {
    form,
    loading,
    columns,
    dataList,
    statistics,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleSaveDraft,
    handleCheckBarcode,
    handleRefreshStatus,
    handleSizeChange,
    handleCurrentChange
  };
}

const EditForm = defineComponent({
  props: {
    formInline: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const ruleFormRef = ref();
    const model = reactive({
      id: props.formInline.id,
      productName: props.formInline.productName,
      barcode: props.formInline.barcode,
      category: props.formInline.category,
      brand: props.formInline.brand,
      specification: props.formInline.specification,
      unit: props.formInline.unit,
      price: props.formInline.price,
      costPrice: props.formInline.costPrice,
      images: props.formInline.images,
      description: props.formInline.description
    });
    const rules = {
      productName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
      barcode: [{ required: true, message: "请输入条形码", trigger: "blur" }]
    };

    const getRef = () => ruleFormRef.value;
    const getForm = () => model;

    return () => (
      <ElForm ref={ruleFormRef} model={model} rules={rules} label-width="100px">
        <ElFormItem label="商品名称" prop="productName">
          <ElInput v-model={model.productName} placeholder="请输入商品名称" />
        </ElFormItem>
        <ElFormItem label="条形码" prop="barcode">
          <ElInput v-model={model.barcode} placeholder="请输入条形码" />
        </ElFormItem>
        <ElFormItem label="分类" prop="category">
          <ElInput v-model={model.category} placeholder="请输入分类" />
        </ElFormItem>
        <ElFormItem label="品牌" prop="brand">
          <ElInput v-model={model.brand} placeholder="请输入品牌" />
        </ElFormItem>
        <ElFormItem label="规格" prop="specification">
          <ElInput v-model={model.specification} placeholder="请输入规格" />
        </ElFormItem>
        <ElFormItem label="单位" prop="unit">
          <ElInput v-model={model.unit} placeholder="请输入单位" />
        </ElFormItem>
        <ElFormItem label="售价(元)" prop="price">
          <ElInputNumber v-model={model.price} precision={2} min={0} />
        </ElFormItem>
        <ElFormItem label="成本价(元)" prop="costPrice">
          <ElInputNumber v-model={model.costPrice} precision={2} min={0} />
        </ElFormItem>
        <ElFormItem label="商品描述" prop="description">
          <ElInput
            v-model={model.description}
            type="textarea"
            rows={3}
            placeholder="请输入商品描述"
          />
        </ElFormItem>
      </ElForm>
    );
  }
});
