import {
  ActionType,
  Icon,
  PageList,
  State,
  SupplierPicker,
  ToolBar,
} from "@/components";
import Taro, { useShareAppMessage } from "@tarojs/taro";
import { useRef, useState } from "react";
import { business } from "@/services";
import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import { Label, Text, View } from "@tarojs/components";
import dayjs from "dayjs";
import order from "@/constant/order";
import { Button, Toast } from "@nutui/nutui-react-taro";
import classNames from "classnames";

export default hocAuth(function Page(props: CommonComponent) {
  const { shareOptions } = props;

  const [supplierVO, setSupplierVO] = useState<BusinessAPI.SupplierVO>();

  const actionRef = useRef<ActionType>();
  const toolbar: ToolBar<BusinessAPI.OrderSupplierVO> = {
    search: {
      activeKey: "vehicleNo",
      defaultActiveKey: "vehicleNo",
      items: [
        {
          key: "vehicleNo",
          name: "车次号",
          placeholder: "请输入车次号",
        },
        {
          key: "plate",
          name: "车牌号",
          placeholder: "请输入车牌号",
        },
      ],
    },
    render: () => (
      <>
        <View className={"flex flex-row gap-2.5"}>
          <SupplierPicker
            type={"FARMER"}
            onFinish={(supplierVO) => {
              setSupplierVO(supplierVO);
              actionRef.current?.reload();
            }}
            trigger={
              <View
                className={`border-primary flex h-6 items-center rounded-md border-2 px-2.5`}
              >
                <View className={"text-primary text-xs"}>
                  {supplierVO?.name || "瓜农"}
                </View>
                {supplierVO?.name ? (
                  <Icon
                    name={"circle-xmark"}
                    size={16}
                    onClick={(event) => {
                      setSupplierVO(undefined);
                      actionRef.current?.reload();
                      event.stopPropagation();
                    }}
                  />
                ) : (
                  <Icon name={"chevron-down"} size={16} />
                )}
              </View>
            }
          />
        </View>
      </>
    ),
  };

  useShareAppMessage((res) => {
    console.log("useShareAppMessage1", res, shareOptions);
    // 如果是按钮触发的转发，使用默认配置
    if (res.from === "button") {
      return shareOptions;
    }
    // 页面转发使用设置的配置
    return {};
  });

  return (
    <>
      <PageList<BusinessAPI.OrderSupplierVO, BusinessAPI.OrderSupplierPageQry>
        rowId={"orderSupplierId"}
        itemHeight={182}
        type={"infinite"}
        actionRef={actionRef}
        render={(orderSupplierVO: BusinessAPI.OrderSupplierVO, index) => (
          <View className={"mb-2"} key={index}>
            <View
              className={
                "relative flex flex-col divide-y divide-neutral-100 overflow-hidden rounded-xl bg-white shadow-sm"
              }
            >
              {/* 头部区域：名称 + 状态 */}
              <View
                className={
                  "flex cursor-pointer items-center justify-between gap-2 px-4 py-3"
                }
                onClick={() => {
                  const imageUrls =
                    orderSupplierVO.invoiceImg?.map((file) => file.filePath!) ||
                    [];
                  // 使用 Taro.previewImage 预览图片
                  if (imageUrls?.length > 0) {
                    Taro.previewImage({
                      urls: imageUrls,
                    });
                  } else {
                    Toast.show("toast", {
                      title: "暂无发票图片",
                      icon: "none",
                      content: "",
                    });
                  }
                }}
              >
                <View className={"flex min-w-0 flex-1 flex-col gap-1.5"}>
                  <Text className={"text-neutral-darkest text-lg font-bold"}>
                    {orderSupplierVO.name}
                  </Text>
                  <Text className={"text-neutral-dark text-xs"}>
                    {orderSupplierVO.orderVO?.orderVehicle?.origin} →{" "}
                    {orderSupplierVO.orderVO?.orderVehicle?.destination}
                  </Text>
                </View>
                <View className={"flex flex-col items-end gap-1"}>
                  {orderSupplierVO.poState && (
                    <State
                      position="relative"
                      state={orderSupplierVO.poState}
                      stateMap={order.stateMap}
                    />
                  )}
                </View>
              </View>

              {/* 详细信息区域 */}
              <View
                className={"flex cursor-pointer flex-col gap-2 px-4 py-3"}
                onClick={() => {
                  const imageUrls =
                    orderSupplierVO.invoiceImg?.map((file) => file.filePath!) ||
                    [];
                  // 使用 Taro.previewImage 预览图片
                  if (imageUrls?.length > 0) {
                    Taro.previewImage({
                      urls: imageUrls,
                    });
                  } else {
                    Toast.show("toast", {
                      title: "暂无发票图片",
                      icon: "none",
                      content: "",
                    });
                  }
                }}
              >
                <View className={"flex flex-row items-center justify-between"}>
                  <Label className={"text-neutral-dark text-xs"}>
                    车次信息
                  </Label>
                  <Text
                    className={classNames(
                      "text-xs font-medium",
                      "text-primary",
                    )}
                  >
                    {orderSupplierVO.orderVO?.orderVehicle?.vehicleNo
                      ? `第${orderSupplierVO.orderVO?.orderVehicle?.vehicleNo}车`
                      : "暂未生成车次"}
                  </Text>
                </View>
                <View className={"flex flex-row items-center justify-between"}>
                  <Label className={"text-neutral-dark text-xs"}>
                    发货时间
                  </Label>
                  <Text className={"text-neutral-darkest text-xs font-medium"}>
                    {dayjs(
                      orderSupplierVO.orderVO?.orderVehicle?.deliveryTime,
                    ).format("YYYY-MM-DD")}
                  </Text>
                </View>
                <View className={"flex flex-row items-center justify-between"}>
                  <Label className={"text-neutral-dark text-xs"}>重量</Label>
                  <Text className={"text-neutral-darkest text-xs font-medium"}>
                    {orderSupplierVO.netWeight} 斤
                  </Text>
                </View>
                <View className={"flex flex-row items-center justify-between"}>
                  <Label className={"text-neutral-dark text-xs"}>
                    开票金额
                  </Label>
                  <Text className={"text-neutral-darkest text-xs font-medium"}>
                    ¥{orderSupplierVO.invoiceAmount}
                  </Text>
                </View>
                <View className={"flex flex-row items-center justify-between"}>
                  <Label className={"text-neutral-dark text-xs"}>品种</Label>
                  <Text className={"text-neutral-darkest text-xs font-medium"}>
                    {orderSupplierVO.productName}
                  </Text>
                </View>
              </View>

              {/* 操作按钮区域 */}
              <View
                className={
                  "flex justify-end gap-2 border-t border-neutral-100 bg-gray-50 px-4 py-3"
                }
              >
                <Button
                  size={"small"}
                  type={"primary"}
                  onClick={(e) => {
                    e.stopPropagation();
                    const imageUrls =
                      orderSupplierVO.invoiceImg?.map(
                        (file) => file.filePath!,
                      ) || [];
                    // 使用 Taro.previewImage 预览图片
                    if (imageUrls?.length > 0) {
                      Taro.previewImage({
                        urls: imageUrls,
                      });
                    } else {
                      Toast.show("toast", {
                        title: "暂无发票图片",
                        icon: "none",
                        content: "",
                      });
                    }
                  }}
                >
                  查看发票
                </Button>
              </View>
            </View>
          </View>
        )}
        toolbar={toolbar}
        request={async (params) => {
          const {
            data: { data, success, notEmpty },
          } = await business.orderSupplier.pageOrderSupplier({
            orderSupplierPageQry: {
              ...params,
              invoiceUpload: true,
              poStates: ["AUDITING", "COMPLETED"],
              poType: "PRODUCTION_PURCHASE",
              ...(supplierVO
                ? {
                    supplierId: supplierVO.supplierId,
                  }
                : {}),
            },
          });

          return {
            data,
            success,
            hasMore: notEmpty,
          };
        }}
        pagination={{
          pageSize: 10,
        }}
      />
    </>
  );
});
