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

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

  const [state, setState] = useState<BusinessAPI.OrderShipPageQry["state"]>();
  const [dealerVO, setDealerVO] = useState<BusinessAPI.DealerVO>();

  const actionRef = useRef<ActionType>();
  const toolbar: ToolBar<BusinessAPI.OrderShipVO> = {
    search: {
      activeKey: "vehicleNo",
      defaultActiveKey: "vehicleNo",
      items: [
        {
          key: "vehicleNo",
          name: "车次号",
          placeholder: "请输入车次号",
        },
        {
          key: "plate",
          name: "车牌号",
          placeholder: "请输入车牌号",
        },
      ],
    },
    tabs: {
      activeKey: "state",
      defaultActiveKey: state || "ALL",
      items: orderShip.stateList,
      onChange: (item) => {
        setState(item as BusinessAPI.OrderShipPageQry["state"]);
        actionRef.current?.reload();
      },
    },
    render: () => (
      <>
        <View className={"flex flex-row gap-2.5"}>
          <DealerPicker
            onFinish={(dealerVO) => {
              setDealerVO(dealerVO);
              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"}>
                  {dealerVO?.shortName || "经销商"}
                </View>
                {dealerVO?.shortName ? (
                  <Icon
                    name={"circle-xmark"}
                    size={16}
                    onClick={(event) => {
                      setDealerVO(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.OrderShipVO, BusinessAPI.OrderShipPageQry>
      rowId={"orderShipId"}
      itemHeight={182}
      type={"infinite"}
      actionRef={actionRef}
      render={(orderShipVO: BusinessAPI.OrderShipVO, 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={async () => {
              //   await Taro.navigateTo({
              //     url: buildUrl("/pages/delivery/document", {
              //       orderShipId: orderShipVO.orderShipId,
              //       orderId: orderShipVO.orderId,
              //     }),
              //   });
              // }}
            >
              <View className={"flex min-w-0 flex-1 flex-col gap-1.5"}>
                <View className={"flex min-w-0 flex-1 flex-col gap-1.5"}>
                  <Text className={"text-neutral-darkest text-lg font-bold"}>
                    {orderShipVO.orderVO?.orderVehicle?.dealerName}{" "}
                    {orderShipVO.orderVO?.orderVehicle?.vehicleNo
                      ? `第${orderShipVO.orderVO?.orderVehicle?.vehicleNo}车`
                      : "暂未生成车次"}
                  </Text>
                  <Text className={"text-neutral-dark text-xs"}>
                    {`${orderShipVO.orderVO?.orderVehicle?.origin} → ${orderShipVO.orderVO?.orderVehicle?.destination}`}
                  </Text>
                </View>
              </View>
              <State
                position={"relative"}
                state={orderShipVO.state}
                stateMap={orderShip.stateMap}
              />
            </View>

            {/* 详细信息区域 */}
            <View
              className={"flex cursor-pointer flex-col gap-2 px-4 py-3"}
              onClick={async () => {
                // await Taro.navigateTo({
                //   url: buildUrl("/pages/delivery/document", {
                //     orderShipId: orderShipVO.orderShipId,
                //     orderId: orderShipVO.orderId,
                //   }),
                // });
              }}
            >
              <View className={"flex flex-row items-center justify-between"}>
                <Label className={"text-neutral-dark text-xs"}>发货单号</Label>
                <CopyText copyData={orderShipVO.orderSn}>
                  <Text className={"text-neutral-darkest text-xs font-medium"}>
                    {orderShipVO.orderSn}
                  </Text>
                </CopyText>
              </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"}>
                  {orderShip.getTypeLabel(orderShipVO.type)}
                </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"}>
                  {orderShipVO.createdByName}
                </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(orderShipVO.createdAt).format("MM-DD HH:mm")}
                </Text>
              </View>
            </View>

            {/* 操作按钮区域 */}
            <View
              className={
                "flex justify-end gap-2 border-t border-neutral-100 bg-gray-50 px-4 py-3"
              }
            >
              {orderShipVO.state !== "DRAFT" &&
                orderShipVO.state !== "WAIT_SHIPMENT" && (
                  <Button
                    type={"primary"}
                    size={"small"}
                    onClick={async (e) => {
                      // 跳转到发货单据生成页面
                      await Taro.navigateTo({
                        url: buildUrl("/pages/delivery/document", {
                          orderShipId: orderShipVO.orderShipId,
                          orderId: orderShipVO.orderId,
                        }),
                      });
                      e.stopPropagation();
                    }}
                  >
                    下载发货单据
                  </Button>
                )}
            </View>
          </View>
        </View>
      )}
      toolbar={toolbar}
      request={async (params) => {
        const {
          data: { data, success, notEmpty },
        } = await business.orderShip.pageOrderShip({
          orderShipPageQry: {
            ...params,
            //@ts-ignore
            state: state !== "ALL" ? state : undefined,
            ...(dealerVO
              ? {
                  dealerId: dealerVO.dealerId,
                }
              : {}),
          },
        });

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