import Taro, { useShareAppMessage } from "@tarojs/taro";
import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import { View } from "@tarojs/components";
import { ExpenseCostList, ExpenseProvisionList, Icon } from "@/components";
import { useEffect, useRef, useState } from "react";
import {
  Button,
  Calendar,
  Dialog,
  SafeArea,
  Toast,
} from "@nutui/nutui-react-taro";
import dayjs from "dayjs";
import { business } from "@/services";
import { globalStore } from "@/store/global-store";

export default hocAuth(function Page(props: CommonComponent) {
  const { shareOptions, router } = props;
  const date = router.params.date as string;

  const [currentDate, setCurrentDate] = useState<string>(() => {
    return dayjs(date || new Date()).format("YYYY-MM-DD");
  });
  const [expenseRecord, setExpenseRecord] =
    useState<BusinessAPI.ExpenseRecordVO>();
  const { setLoading } = globalStore((state: any) => state);

  const [show, setShow] = useState(false);

  // 数据变更检测相关状态
  const [originalData, setOriginalData] =
    useState<BusinessAPI.ExpenseRecordVO>(); // 原始数据
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); // 是否有未保存的变更
  const [confirmVisible, setConfirmVisible] = useState(false); // 确认对话框状态
  const [pendingDate, setPendingDate] = useState<string>(""); // 待切换的日期

  const lastSaveTime = useRef<number>(Date.now()); // 最后保存时间，用于优化变更检测

  // 数据变更检测函数
  const hasDataChanged = (
    current: BusinessAPI.ExpenseRecordVO,
    original: BusinessAPI.ExpenseRecordVO,
  ) => {
    if (!current || !original) return false;

    // 比较计提列表
    const currentProvisions = current.expenseProvisionList || [];
    const originalProvisions = original.expenseProvisionList || [];

    if (currentProvisions.length !== originalProvisions.length) return true;

    for (let i = 0; i < currentProvisions.length; i++) {
      const curr = currentProvisions[i];
      const orig = originalProvisions[i];
      if (
        curr.dealerName !== orig.dealerName ||
        curr.provisionAmount !== orig.provisionAmount ||
        curr.vehicleNo !== orig.vehicleNo ||
        curr.remark !== orig.remark
      ) {
        return true;
      }
    }

    // 比较费用列表
    const currentCosts = current.expenseCostList || [];
    const originalCosts = original.expenseCostList || [];

    if (currentCosts.length !== originalCosts.length) return true;

    for (let i = 0; i < currentCosts.length; i++) {
      const curr = currentCosts[i];
      const orig = originalCosts[i];
      if (
        curr.costName !== orig.costName ||
        curr.expenseAmount !== orig.expenseAmount ||
        curr.remark !== orig.remark
      ) {
        return true;
      }
    }

    return false;
  };

  // 检查数据变更的函数
  const checkForChanges = (newData: BusinessAPI.ExpenseRecordVO) => {
    console.log("newData:", newData);
    console.log("originalData:", originalData);
    if (originalData) {
      const changed = hasDataChanged(newData, originalData);
      console.log("数据变更:", changed);
      setHasUnsavedChanges(changed);
    } else if (newData) {
      setHasUnsavedChanges(true);
    } else if (!newData) {
      setHasUnsavedChanges(false);
    }
  };

  // 保存数据函数
  const saveCurrentData = async () => {
    if (expenseRecord) {
      try {
        // 这里添加实际的保存逻辑
        console.log("保存数据:", expenseRecord);
        const {
          data: { success },
        } = await business.expenseRecord.createExpenseRecord({
          ...expenseRecord,
          recordDate: currentDate,
        });

        if (success) {
          // 保存成功后更新原始数据
          setOriginalData(JSON.parse(JSON.stringify(expenseRecord)));
          setHasUnsavedChanges(false);
          lastSaveTime.current = Date.now();
        }

        return success;
      } catch (error) {
        console.error("保存数据失败:", error);
        return false;
      }
    }
    return false;
  };

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

  useEffect(() => {
    if (currentDate) {
      loadExpenseData(currentDate).then();
    }
  }, [currentDate]);

  const loadExpenseData = async (currentDate: string) => {
    try {
      setLoading(true);
      const {
        data: { data: expenseRecord, success },
      } = await business.expenseRecord.showExpenseRecord({
        expenseRecordShowQry: {
          recordDate: currentDate, // 使用今天的日期
        },
      });

      if (success) {
        if (expenseRecord) {
          setExpenseRecord(expenseRecord);
          // 保存原始数据用于变更检测
          setOriginalData(JSON.parse(JSON.stringify(expenseRecord)));
        } else {
          setExpenseRecord(undefined);
          setOriginalData(undefined);
        }
        // 重置未保存变更状态
        setHasUnsavedChanges(false);
        lastSaveTime.current = Date.now();
      }
    } catch (error) {
      console.error("加载费用数据失败:", error);
    } finally {
      setLoading(false);
    }
  };

  function onchange(expenseRecord: BusinessAPI.ExpenseRecordVO) {
    setExpenseRecord((prev) => {
      const totalProvision =
        expenseRecord.expenseProvisionList?.reduce(
          (sum, provision) => sum + (provision.provisionAmount || 0),
          0,
        ) || 0;

      const totalExpense =
        expenseRecord.expenseCostList?.reduce(
          (sum, expense) => sum + (expense.expenseAmount || 0),
          0,
        ) || 0;

      const newExpenseRecord = {
        ...prev!,
        ...expenseRecord,
        totalProvision: totalProvision,
        totalExpense: totalExpense,
        dailyProfit: totalProvision - totalExpense,
      };

      // 检查数据变更
      setTimeout(() => {
        checkForChanges(newExpenseRecord);
      }, 100);

      return newExpenseRecord;
    });
  }

  return (
    <>
      <View className={"flex flex-1 flex-col gap-2.5 p-2.5"}>
        <View className="overflow-hidden rounded-md bg-white">
          <View className="bg-gray-50">
            <View
              className={`flex h-10 w-full items-center rounded-md border-4 border-gray-300`}
            >
              <View
                className={
                  "flex flex-1 flex-row items-center justify-between px-5"
                }
                style={{
                  color: "var(--nutui-color-title, #1a1a1a)",
                }}
                onClick={() => {
                  if (hasUnsavedChanges) {
                    setConfirmVisible(true);
                  } else {
                    setShow(true);
                  }
                }}
              >
                <View className={"text-sm"}>
                  {currentDate
                    ? dayjs(currentDate).format("YYYY年MM月DD日")
                    : "请选择录入花销时间"}
                </View>
                <Icon name={"chevron-down"} />
              </View>
            </View>
          </View>
        </View>

        <ExpenseProvisionList
          expenseRecord={expenseRecord}
          onChange={onchange}
        />

        <ExpenseCostList expenseRecord={expenseRecord} onChange={onchange} />

        <View className="overflow-hidden rounded-md bg-white shadow-md">
          <View className={"flex flex-col gap-2.5 p-2.5"}>
            <View className="text-neutral-darkest text-base font-medium">
              今日利润计算
            </View>
            <View className="flex items-center justify-between">
              <View className="text-neutral-darker text-sm">计提总金额</View>
              <View className="text-neutral-darkest text-sm font-medium">
                ¥{(expenseRecord?.totalProvision || 0).toLocaleString()}
              </View>
            </View>
            <View className="flex items-center justify-between">
              <View className="text-neutral-darker text-sm">花销小计</View>
              <View className="text-neutral-darkest text-sm font-medium">
                ¥
                {expenseRecord?.expenseCostList
                  ?.reduce(
                    (sum, expense) => sum + (expense.expenseAmount || 0),
                    0,
                  )
                  .toFixed(2)}
              </View>
            </View>
            <View className="border-t border-gray-200 pt-2.5">
              <View className="flex items-center justify-between">
                <View className="text-neutral-darker text-sm">日常利润</View>
                <View
                  className={`text-sm font-medium ${(expenseRecord?.dailyProfit || 0) >= 0 ? "text-green-600" : "text-red-600"}`}
                >
                  ¥{(expenseRecord?.dailyProfit || 0).toLocaleString()}
                </View>
              </View>
              <View className={"flex flex-row items-center"}>
                <Icon
                  name={
                    (expenseRecord?.dailyProfit || 0) >= 0
                      ? "arrow-up"
                      : "arrow-down"
                  }
                  color={
                    (expenseRecord?.dailyProfit || 0) >= 0 ? "green" : "red"
                  }
                  className="mr-1"
                  size={14}
                />
                <View
                  className={`text-sm font-medium ${(expenseRecord?.dailyProfit || 0) >= 0 ? "text-green-600" : "text-red-600"}`}
                >
                  {(expenseRecord?.dailyProfit || 0) >= 0
                    ? "盈利状态"
                    : "亏损状态"}
                </View>
              </View>
            </View>
          </View>
        </View>
      </View>
      <View className="sticky bottom-0 z-10 bg-white">
        <View className="flex justify-between gap-2 border-t border-gray-200 p-2.5">
          {/* 返回 */}
          <View className="flex-1">
            <Button
              size={"large"}
              block
              type={"default"}
              onClick={() => {
                Taro.navigateBack();
              }}
            >
              返回
            </Button>
          </View>
          <View className="flex-1">
            <Button
              size={"large"}
              block
              type={"primary"}
              onClick={async () => {
                const saveSuccess = await saveCurrentData();
                if (saveSuccess) {
                  Toast.show("toast", {
                    icon: "success",
                    title: "提示",
                    content: "保存成功",
                  });
                }
              }}
              disabled={!hasUnsavedChanges}
            >
              保存数据 {hasUnsavedChanges ? "(有变更)" : ""}
            </Button>
          </View>
        </View>
        <SafeArea position="bottom" />
      </View>

      <Calendar
        visible={show}
        defaultValue={dayjs(currentDate).format("YYYY-MM-DD")}
        startDate={"2025-01-01"}
        onClose={() => setShow(false)}
        onConfirm={(data) => {
          const newDate = dayjs(data[3]).format("YYYY-MM-DD");

          // 如果没有未保存变更，直接切换日期
          if (!hasUnsavedChanges) {
            setCurrentDate(newDate);
          } else {
            // 有未保存变更时，保存待切换日期，显示确认对话框
            setPendingDate(newDate);
            setConfirmVisible(true);
          }
        }}
      />

      {/* 日期切换确认对话框 */}
      <Dialog
        visible={confirmVisible}
        title="未保存的变更"
        content="当前日期有未保存的变更，是否要保存这些更改？"
        onCancel={() => {
          // 取消操作，停留在当前日期
          setConfirmVisible(false);
          setPendingDate("");
        }}
        onConfirm={async () => {
          // 保存并切换
          setConfirmVisible(false);
          const saveSuccess = await saveCurrentData();
          if (saveSuccess && pendingDate) {
            setCurrentDate(pendingDate);
            setPendingDate("");
          }
        }}
        confirmText="保存并切换"
        cancelText="取消"
      />
    </>
  );
});
