import {
  ActionType,
  DealerPicker,
  Icon,
  OrderItem,
  PageList,
  SupplierPicker,
  ToolBar,
} from "@/components";
import React, { useRef, useState } from "react";
import { business } from "@/services";
import { View } from "@tarojs/components";
import { buildUrl } from "@/utils";
import Taro from "@tarojs/taro";
import { purchase } from "@/constant";

interface IOrderListProps {
  params: BusinessAPI.OrderPageQry;
  create?: boolean;
  toolbar?: ToolBar<BusinessAPI.OrderVO>;
  actionRef?: React.MutableRefObject<ActionType | undefined>;
}

export default function OrderList(props: IOrderListProps) {
  const {
    params: bizParams,
    create = false,
    toolbar: defaultToolbar,
    actionRef: externalActionRef,
  } = props;

  const { type = "PRODUCTION_PURCHASE" } = bizParams;

  const internalActionRef = useRef<ActionType>();
  const actionRef = externalActionRef || internalActionRef;
  const [dealerVO, setDealerVO] = useState<BusinessAPI.DealerVO>();
  const [supplierVO, setSupplierVO] = useState<BusinessAPI.SupplierVO>();
  const toolbar: ToolBar<BusinessAPI.OrderVO> = {
    ...defaultToolbar,
    search: {
      activeKey: "plate",
      defaultActiveKey: "plate",
      items: [
        {
          key: "plate",
          name: "车牌号",
          placeholder: "请输入车牌号",
        },
      ],
    },
    render: () => (
      <View className={"item-start flex flex-row gap-2.5"}>
        <View>
          <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>
        <View>
          <SupplierPicker
            type={type === "PRODUCTION_PURCHASE" ? "FARMER" : "STALL"}
            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 ||
                    (type === "PRODUCTION_PURCHASE" ? "瓜农" : "档口")}
                </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>
      </View>
    ),
    actions: [
      create && (
        <View className={"flex flex-row gap-2 p-3"} key={"create"}>
          <View className={"flex-1"}>
            <View
              className="bg-primary flex w-full flex-col items-center justify-center space-y-2 rounded-xl py-2.5 text-white"
              onClick={() => {
                Taro.navigateTo({
                  url: buildUrl(purchase.path[type].create),
                });
              }}
            >
              <View className="text-base font-bold">新建采购单</View>
            </View>
          </View>
        </View>
      ),
    ],
  };

  return (
    <PageList<BusinessAPI.OrderVO, BusinessAPI.OrderPageQry>
      rowId={"orderId"}
      itemHeight={182}
      type={"infinite"}
      actionRef={actionRef}
      render={(orderVO: BusinessAPI.OrderVO, index) => {
        return (
          <View className={"mb-2.5"} key={index}>
            <OrderItem orderVO={orderVO} actionRef={actionRef} />
          </View>
        );
      }}
      toolbar={toolbar}
      request={async (params) => {
        const {
          data: { data, success, notEmpty },
        } = await business.order.pageOrder({
          orderPageQry: {
            ...params,
            ...bizParams,
            dealerId: dealerVO?.dealerId,
            supplierId: supplierVO?.supplierId,
          },
        });

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