import React from "react";
import Taro from "@tarojs/taro";
import { Popup, Button, Cell, Icon, Empty } from "@antmjs/vantui";
import { ScrollView, View } from "@tarojs/components";
import { getSysOrg } from "@/services/sysorg";
import VABC from "@/components/VABC";
import Tree from "@/components/Tree";
import { arr2Tree } from "@/utils/array";

const wrapperStyle = {
  width: "90vw",
  height: "100vh",
  paddingBottom: "env(safe-area-inset-bottom)",
};

export default function OrgTree(props) {
  const { show, onCancel, onChange } = props;

  const [dict, setDict] = React.useState([]);
  const [checked, setChecked] = React.useState();

  const onSubmit = () => {
    if (!checked) return;
    onChange(checked?.orgId, checked);
  };

  const onCheck = (e, it) => {
    // e.stopPropagation();
    // e.preventDefault();
    setChecked(it);
  };

  React.useEffect(() => {
    getSysOrg({
      pageSize: 500,
      isResponsible: 1,
      parentId: props.parentId,
    }).then((res) => {
      const [treeData] = arr2Tree(res.records || [], "orgPId", "orgId");
      console.log("-------treeData-------", treeData);
      setDict(treeData);
    });
  }, [props.parentId]);

  return (
    <Popup position="right" show={show} onClose={onCancel}>
      <VABC
        footer={
          <View style={{ padding: "8px 2em" }}>
            <Button block type="primary" disabled={!checked} onClick={onSubmit}>
              确定
            </Button>
          </View>
        }
        style={wrapperStyle}
      >
        <ScrollView scrollY style={{ height: "100%" }}>
          {dict.length == 0 ? (
            <Empty description="暂无数据" />
          ) : (
            <Tree
              data={dict}
              renderTitle={(it) => (
                <Cell
                  title={it.name}
                  value={
                    <View>
                      {checked?.orgId == it.orgId ? (
                        <Icon name="success" color="#1A7565" />
                      ) : (
                        <View style={{ width: "100%", minHeight: "10px" }} />
                      )}
                    </View>
                  }
                  renderIcon={
                    it.children?.length > 0 ? (
                      <Icon name="arrow" />
                    ) : (
                      <View style={{ minWidth: "16px" }} />
                    )
                  }
                  onClick={(e) => onCheck(e, it)}
                />
              )}
            />
          )}
        </ScrollView>
      </VABC>
    </Popup>
  );
}
