import "./index.module.css";
import { useEffect, useMemo, useState } from "react";

import { cloneDeep, isEqual } from "lodash";
import RenderComponent from "../FormComponentRender";
import { View } from "@tarojs/components";
import { Flex, Row, Col } from "@taroify/core";

interface GroupProps {
  value: boolean | string;
  onChange?: (value: Record<string, any>[]) => void;
  children?: any[];
  /** 是否无限层级  */
  isInfinite?: boolean;
  metaData: any;
}

export default function (props: GroupProps) {
  const { value, onChange, children, isInfinite, metaData } = props;

  const [groupData, setGroupData] = useState<Record<string, any>[]>([{}]);

  const defValue = useMemo(() => {
    const result: { [key: string]: undefined } = {};
    children?.forEach((v) => {
      result[v.key] = undefined;
    });
    return result;
  }, [children]);

  useEffect(() => {
    if (typeof value === "object" && !isEqual(value, groupData)) {
      setGroupData(value);
    }
  }, [value]);

  /**
   * 初始化
   */
  useEffect(() => {
    setGroupData([defValue]);
  }, [children, defValue]);
  const onAdd = (i: number) => {
    const cur = cloneDeep(groupData);
    cur.splice(i + 1, 0, defValue);
    setGroupData(cur);
  };

  const onRemove = (i: number) => {
    setGroupData(groupData.filter((_, index) => index !== i));
  };
  const valueChange = (v: any, key: string, index: number) => {
    const newData = groupData.map((item, i) => {
      if (i === index) {
        return { ...item, [key]: v.target?.value ?? v };
      }
      return item;
    });
    onChange && onChange(newData);
    setGroupData(newData);
  };

  return (
    <View className="groupContainer">
      {groupData.map((item, i) => {
        return (
          <View>
            <Flex
              className={"groupTitle"}
              align="center"
              justify="space-between"
              key={i}
            >
              <View>
                {metaData.label}
                {isInfinite ? i + 1 : ""}
              </View>
              <View className="rightWrap">
                {isInfinite && (
                  <View className="action-btn" onClick={() => onAdd(i)}>
                    新增
                  </View>
                )}
                {i != 0 && (
                  <View className="action-btn" onClick={() => onRemove(i)}>
                    删除
                  </View>
                )}
              </View>
            </Flex>
            {children?.map((configItem) => {
              return (
                <Row style={{ margin: "16px 0" }} key={configItem.key}>
                  <Col
                    span={6}
                    style={{
                      textAlign: "right",
                      fontWeight: "bold",
                      color: "#000",
                      paddingRight: 12,
                    }}
                  >
                    {configItem.label}
                  </Col>
                  <Col span={18}>
                    <RenderComponent
                      config={configItem.componentOption}
                      componentType={configItem.componentType}
                      metaData={configItem}
                      onChange={(v) => {
                        valueChange(v, configItem.key, i);
                      }}
                      value={item[configItem.key]}
                    ></RenderComponent>
                  </Col>
                </Row>
              );
            })}
          </View>
        );
      })}
    </View>
  );
}
