import {
  ActionType,
  Icon,
  PageList,
  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 { Button } from "@nutui/nutui-react-taro";
import { buildUrl } from "@/utils";
import dayjs from "dayjs";

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

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

  const actionRef = useRef<ActionType>();
  const toolbar: ToolBar<BusinessAPI.SupplierInvoiceVO> = {
    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.SupplierInvoiceVO,
        BusinessAPI.SupplierInvoicePageQry
      >
        rowId={"supplierInvoiceId"}
        itemHeight={182}
        type={"infinite"}
        actionRef={actionRef}
        render={(supplierInvoiceVO: BusinessAPI.SupplierInvoiceVO, index) => {
          // 计算总开票金额
          const totalAmount =
            supplierInvoiceVO.orderSupplierInvoiceList?.reduce(
              (sum, item) => sum + (item.invoiceAmount || 0),
              0,
            ) || 0;

          // 提取所有瓜农名称，用分号分隔
          const farmerNames = supplierInvoiceVO.orderSupplierInvoiceList
            ?.map((item) => item.name)
            .filter(Boolean)
            .join("；");

          // 提取所有车次号，用分号分隔
          const vehicleNos = supplierInvoiceVO.orderSupplierInvoiceList
            ?.map((item) => {
              return `${item.dealerName} ${item?.vehicleNo ? `第${item?.vehicleNo}车` : "暂未生成车次"}`;
            })
            .filter(Boolean)
            .join("；");

          return (
            <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"
                  }
                >
                  <View className={"flex min-w-0 flex-1 flex-col gap-1.5"}>
                    <Text className={"text-neutral-darkest text-lg font-bold"}>
                      {supplierInvoiceVO.supplierName || "-"}
                    </Text>
                    <Text className={"text-neutral-dark text-xs"}>
                      发票开具人
                    </Text>
                  </View>
                  <View className={"flex flex-col items-end gap-1"}>
                    <Text className={"text-primary text-xl font-bold"}>
                      ¥{totalAmount.toFixed(2)}
                    </Text>
                    <Text className={"text-neutral-dark text-xs"}>
                      开票金额
                    </Text>
                  </View>
                </View>

                {/* 详细信息区域 */}
                <View className={"flex flex-col gap-2 px-4 py-3"}>
                  <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"}
                    >
                      {farmerNames || "-"}
                    </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"}
                    >
                      {vehicleNos || "-"}
                    </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"}
                    >
                      {supplierInvoiceVO.registrationTime
                        ? dayjs(supplierInvoiceVO.registrationTime).format(
                            "YYYY-MM-DD",
                          )
                        : "-"}
                    </Text>
                  </View>
                </View>

                {/* 操作按钮区域 */}
                <View
                  className={
                    "flex justify-end gap-2 border-t border-neutral-100 bg-gray-50 px-4 py-3"
                  }
                >
                  <Button
                    type={"primary"}
                    size={"small"}
                    onClick={() => {
                      Taro.navigateTo({
                        url: buildUrl("/pages/invoice/detail", {
                          supplierInvoiceId:
                            supplierInvoiceVO.supplierInvoiceId,
                        }),
                      });
                    }}
                  >
                    查看详情
                  </Button>
                </View>
              </View>
            </View>
          );
        }}
        toolbar={toolbar}
        request={async (params) => {
          const {
            data: { data, success, notEmpty },
          } = await business.supplierInvoice.pageSupplierInvoice({
            supplierInvoicePageQry: {
              ...params,
            },
          });

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