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

function update(data, valueList, options) {
  let current = data;
  valueList.forEach(value => {
    const option = current.options.find(option => option.value === value);
    if (option && option.child) {
      current = option.child;
    }
  });
  current.options = options;
  return { ...data };
}

export default function CascaderDynamicExample() {
  const [data, setData] = useState({
    title: "标题 1",
  });

  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}`,
                child:
                  options.length >= 2
                    ? null
                    : { title: `标题 ${options.length + 2}` },
              }))
          )
        );
        resolve();
      }, 800);
    });
  }

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