import {
  ActionType,
  DealerPicker,
  Icon,
  PageList,
  PurchaseOrderRejectApprove,
  PurchaseOrderRejectFinal,
  PurchaseOrderWithdrawReview,
  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, formatCurrency, PurchaseOrderCalculator } from "@/utils";
import { Button } from "@nutui/nutui-react-taro";
import purchaseOrder from "@/constant/purchaseOrder";
import dayjs from "dayjs";

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

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

  const actionRef = useRef<ActionType>();
  const toolbar: ToolBar = {
    search: {
      activeKey: "vehicleNo",
      defaultActiveKey: "vehicleNo",
      items: [
        {
          key: "vehicleNo",
          name: "车次号",
          placeholder: "请输入车次号",
        },
        {
          key: "plate",
          name: "车牌号",
          placeholder: "请输入车牌号",
        },
        {
          key: "supplierName",
          name: "瓜农姓名",
          placeholder: "请输入瓜农姓名",
        },
      ],
    },
    tabs: {
      activeKey: "state",
      defaultActiveKey: state || "ALL",
      items: purchaseOrder.stateList.filter((item) => {
        if (userRoleVO.slug === "reviewer") {
          return item.value !== "DRAFT";
        }

        return item;
      }),
      onChange: (item) => {
        setState(item as BusinessAPI.PurchaseOrderPageQry["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-2 border-primary flex h-6 items-center rounded-md 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>
    ),
    actions: [
      userRoleVO.slug === "origin-entry" && (
        <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("/pages/purchase/purchaser/create"),
                });
              }}
            >
              <View className="text-base font-bold">新建采购单</View>
            </View>
          </View>
        </View>
      ),
    ],
  };

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

  return (
    <PageList<BusinessAPI.PurchaseOrderVO, BusinessAPI.PurchaseOrderPageQry>
      rowId={"purchaseOrderId"}
      itemHeight={182}
      type={"infinite"}
      actionRef={actionRef}
      render={(purchaseOrderVO: BusinessAPI.PurchaseOrderVO, index) => {
        const calculator = new PurchaseOrderCalculator(purchaseOrderVO);

        return (
          <View className={"mb-2.5"} key={index}>
            <View
              className={
                "relative flex flex-col divide-y-2 divide-neutral-100 rounded-lg bg-white px-2.5"
              }
            >
              <View
                className={"flex flex-col divide-y-2 divide-neutral-100"}
                onClick={(event) => {
                  if (purchaseOrderVO.active === 7) {
                    Taro.navigateTo({
                      url: buildUrl("/pages/purchase/purchaser/preview", {
                        orderId: purchaseOrderVO.orderId,
                      }),
                    });
                    event.stopPropagation();
                  }
                }}
              >
                <View className={"py-2.5"}>
                  <View className={"flex flex-row items-center"}>
                    <View className={"flex flex-1 flex-col gap-2"}>
                      <View className={"flex flex-row gap-1"}>
                        {/* 复制 */}
                        <Text
                          className={"text-neutral-darkest text-xl font-bold"}
                        >
                          {purchaseOrderVO.orderVehicle?.vehicleNo
                            ? "第" +
                              purchaseOrderVO.orderVehicle?.vehicleNo +
                              "车"
                            : "暂未生成车次"}
                        </Text>
                      </View>
                      <Text className={"text-neutral-dark text-sm"}>
                        {purchaseOrderVO.orderSn}
                      </Text>
                    </View>
                    <State
                      state={purchaseOrderVO.state}
                      stateMap={purchaseOrder.stateMap}
                    />
                  </View>
                </View>
                <View className={"py-2.5"}>
                  <View className={"flex flex-col gap-2"}>
                    <View
                      className={
                        "flex flex-row items-center justify-between gap-2.5"
                      }
                    >
                      <Label className={"text-neutral-dark text-sm"}>
                        提交人
                      </Label>
                      <Text className={"text-neutral-darkest text-sm"}>
                        {purchaseOrderVO.createdByName}
                      </Text>
                    </View>
                    <View
                      className={
                        "flex flex-row items-center justify-between gap-2.5"
                      }
                    >
                      <Label className={"text-neutral-dark text-sm"}>
                        提交时间
                      </Label>
                      <Text className={"text-neutral-darkest text-sm"}>
                        {dayjs(purchaseOrderVO.createdAt).format("MM-DD HH:mm")}
                      </Text>
                    </View>
                    <View
                      className={
                        "flex flex-row items-center justify-between gap-2.5"
                      }
                    >
                      <Label className={"text-neutral-dark text-sm"}>
                        路线
                      </Label>
                      <Text className={"text-neutral-darkest text-sm"}>
                        {purchaseOrderVO.orderVehicle?.origin} {"->"}
                        {purchaseOrderVO.orderVehicle?.destination}
                      </Text>
                    </View>
                    <View
                      className={
                        "flex flex-row items-center justify-between gap-2.5"
                      }
                    >
                      <Label className={"text-neutral-dark text-sm"}>
                        经销商
                      </Label>
                      <Text className={"text-neutral-darkest text-sm"}>
                        {purchaseOrderVO.orderVehicle.dealerName}
                      </Text>
                    </View>
                    <View
                      className={
                        "flex flex-row items-center justify-between gap-2.5"
                      }
                    >
                      <Label className={"text-neutral-dark text-sm"}>
                        车牌号
                      </Label>
                      <Text className={"text-neutral-darkest text-sm"}>
                        {purchaseOrderVO.orderVehicle?.plate}
                      </Text>
                    </View>
                    <View
                      className={
                        "flex flex-row items-center justify-between gap-2.5"
                      }
                    >
                      <Label className={"text-neutral-dark text-sm"}>
                        瓜农数量
                      </Label>
                      <Text className={"text-neutral-darkest text-sm"}>
                        {purchaseOrderVO.orderSupplierList.length} 位
                      </Text>
                    </View>
                    <View
                      className={
                        "flex flex-row items-center justify-between gap-2.5"
                      }
                    >
                      <Label className={"text-neutral-dark text-sm"}>
                        重量
                      </Label>
                      <Text className={"text-neutral-darkest text-sm"}>
                        毛重 {formatCurrency(calculator.getTotalGrossWeight())}{" "}
                        斤 / 净重{" "}
                        {formatCurrency(calculator.getTotalNetWeight())} 斤
                      </Text>
                    </View>
                  </View>
                </View>
              </View>
              {userRoleVO.slug === "boss" && (
                <View className={"py-2.5"}>
                  {purchaseOrderVO.state === "WAITING_APPROVE" && (
                    <View className={"flex flex-row justify-end gap-2"}>
                      <PurchaseOrderRejectFinal
                        purchaseOrderVO={purchaseOrderVO}
                        size={"small"}
                        onFinish={() => {
                          actionRef.current?.reload();
                        }}
                      />
                      <Button
                        type={"primary"}
                        size={"small"}
                        onClick={(e) => {
                          Taro.navigateTo({
                            url: buildUrl(
                              "/pages/purchase/approver/audit/audit",
                              {
                                orderId: purchaseOrderVO.orderId,
                              },
                            ),
                          });
                          e.stopPropagation();
                        }}
                      >
                        前往审批
                      </Button>
                    </View>
                  )}
                </View>
              )}
              {userRoleVO.slug === "reviewer" && (
                <View className={"py-2.5"}>
                  {purchaseOrderVO.state === "WAITING_AUDIT" && (
                    <View className={"flex flex-row justify-end gap-2"}>
                      <PurchaseOrderRejectApprove
                        purchaseOrderVO={purchaseOrderVO}
                        size={"small"}
                        onFinish={() => {
                          actionRef.current?.reload();
                        }}
                      />
                      <Button
                        type={"primary"}
                        size={"small"}
                        onClick={(e) => {
                          Taro.navigateTo({
                            url: buildUrl(
                              "/pages/purchase/reviewer/audit/audit",
                              {
                                orderId: purchaseOrderVO.orderId,
                              },
                            ),
                          });
                          e.stopPropagation();
                        }}
                      >
                        前往审核
                      </Button>
                    </View>
                  )}
                  {purchaseOrderVO.state === "WAITING_APPROVE" && (
                    <View className={"flex flex-row justify-end gap-2"}>
                      <Button
                        type={"primary"}
                        size={"small"}
                        onClick={(e) => {
                          Taro.navigateTo({
                            url: buildUrl(
                              "/pages/purchase/reviewer/audit/result",
                              {
                                orderId: purchaseOrderVO.orderId,
                              },
                            ),
                          });
                          e.stopPropagation();
                        }}
                      >
                        审核结果
                      </Button>
                    </View>
                  )}
                </View>
              )}
              {userRoleVO.slug === "origin-entry" && (
                <View className={"py-2.5"}>
                  {purchaseOrderVO.state === "DRAFT" && (
                    <View className={"flex flex-row justify-end gap-2"}>
                      <Button
                        type={"default"}
                        size={"small"}
                        onClick={(e) => {
                          Taro.navigateTo({
                            url: buildUrl("/pages/purchase/purchaser/create", {
                              orderId: purchaseOrderVO.orderId,
                            }),
                          });
                          e.stopPropagation();
                        }}
                      >
                        编辑
                      </Button>
                      {purchaseOrderVO.active === 7 && (
                        <Button
                          type={"primary"}
                          size={"small"}
                          onClick={(e) => {
                            Taro.navigateTo({
                              url: buildUrl(
                                "/pages/purchase/purchaser/preview",
                                {
                                  orderId: purchaseOrderVO.orderId,
                                },
                              ),
                            });
                            e.stopPropagation();
                          }}
                        >
                          提交审核
                        </Button>
                      )}
                      <Button type={"danger"} size={"small"}>
                        删除
                      </Button>
                    </View>
                  )}
                  {purchaseOrderVO.state === "WAITING_AUDIT" && (
                    <View className={"flex flex-row justify-end gap-2"}>
                      <Button
                        type={"default"}
                        size={"small"}
                        onClick={(e) => {
                          Taro.navigateTo({
                            url: buildUrl("/pages/purchase/purchaser/preview", {
                              orderId: purchaseOrderVO.orderId,
                            }),
                          });
                          e.stopPropagation();
                        }}
                      >
                        详情
                      </Button>
                      <PurchaseOrderWithdrawReview
                        purchaseOrderVO={purchaseOrderVO}
                        size={"small"}
                        onFinish={() => {
                          actionRef.current?.reload();
                        }}
                      />
                    </View>
                  )}
                </View>
              )}
            </View>
          </View>
        );
      }}
      toolbar={toolbar}
      request={async (params) => {
        const {
          data: { data, success, notEmpty },
        } = await business.purchaseOrder.pagePurchaseOrder({
          purchaseOrderPageQry: {
            ...params,
            //@ts-ignore
            state: state !== "ALL" ? state : undefined,
            ...(dealerVO
              ? {
                  dealerId: dealerVO.dealerId,
                }
              : {}),
          },
        });

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