import React, { useState } from "react";
import { Cascader } from "@tencent/tea-component";

function update(data, valueList, options) {
  if (!data) {
    return options;
  }

  let current = data;
  valueList.forEach(value => {
    const option = current.find(option => option.value === value);
    if (option && option.children) {
      current = option.children;
    } else {
      option.children = options;
    }
  });

  return [...data];
}

export default function CascaderDynamicExample() {
  const [data, setData] = useState();

  function onLoad(value, options) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟失败
        if (Math.random() > 0.85) {
          reject(new Error("Load Error"));
          return;
        }

        const option = options[options.length - 1];
        setData(
          update(
            data,
            value,
            Array(Math.ceil(Math.random() * 12))
              .fill(0)
              .map((_, i) => ({
                label: `选项 ${i}`,
                value: !option ? `${i}` : `${option.value}-${i}`,
                isLeaf: options.length >= 2,
              }))
          )
        );
        resolve();
      }, 800);
    });
  }

  return (
    <Cascader
      data={data}
      type="menu"
      multiple={false}
      onChange={(value, { options }) => console.log(value, options)}
      onLoad={onLoad}
    />
  );
}
